text
stringlengths
5
1.04M
/* * Copyright(c) 2020 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http ://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "camera_server.h" #include <cstdio> #include <list> #include <string> #include "camera_device.h" #include "camera_service.h" #include "camera_type.h" #include "media_log.h" #include "meta_data.h" #include "surface.h" #include "surface_impl.h" using namespace std; namespace OHOS { namespace Media { CameraServer *CameraServer::GetInstance() { static CameraServer server; return &server; } void CameraServer::CameraServerRequestHandle(int funcId, void *origin, IpcIo *req, IpcIo *reply) { switch (funcId) { case CAMERA_SERVER_GET_CAMERA_ABILITY: CameraServer::GetInstance()->GetCameraAbility(req, reply); break; case CAMERA_SERVER_GET_CAMERA_INFO: CameraServer::GetInstance()->GetCameraInfo(req, reply); break; case CAMERA_SERVER_GET_CAMERAIDLIST: CameraServer::GetInstance()->GetCameraIdList(req, reply); break; case CAMERA_SERVER_CREATE_CAMERA: CameraServer::GetInstance()->CreateCamera(req, reply); break; case CAMERA_SERVER_CLOSE_CAMERA: CameraServer::GetInstance()->CloseCamera(req, reply); break; case CAEMRA_SERVER_SET_CAMERA_CONFIG: CameraServer::GetInstance()->SetCameraConfig(req, reply); break; case CAMERA_SERVER_TRIGGER_LOOPING_CAPTURE: CameraServer::GetInstance()->TriggerLoopingCapture(req, reply); break; case CAMERA_SERVER_STOP_LOOPING_CAPTURE: CameraServer::GetInstance()->StopLoopingCapture(req, reply); break; case CAMERA_SERVER_TRIGGER_SINGLE_CAPTURE: CameraServer::GetInstance()->TriggerSingleCapture(req, reply); break; case CAMERA_SERVER_SET_CAMERA_CALLBACK: CameraServer::GetInstance()->SetCameraCallback(req, reply); break; default: MEDIA_ERR_LOG("code not support:%d!", funcId); break; } } void CameraServer::InitCameraServer() { CameraService *service = CameraService::GetInstance(); service->Initialize(); } void CameraServer::GetCameraAbility(IpcIo *req, IpcIo *reply) { size_t sz; string cameraId((const char*)(IpcIoPopString(req, &sz))); CameraAbility *ability = CameraService::GetInstance()->GetCameraAbility(cameraId); if (ability == nullptr) { return; } list<CameraPicSize> supportSizeList = ability->GetSupportedSizes(PARAM_KEY_SIZE); uint32_t supportProperties = 0; IpcIoPushUint32(reply, supportProperties); uint32_t listSize = supportSizeList.size(); IpcIoPushUint32(reply, listSize); for (auto supportSizeItem : supportSizeList) { IpcIoPushFlatObj(reply, &supportSizeItem, sizeof(CameraPicSize)); } // af list<int32_t> afModeList = ability->GetSupportedAfModes(); uint32_t afListSize = afModeList.size(); IpcIoPushUint32(reply, afListSize); for (auto supportAfMode : afModeList) { IpcIoPushInt32(reply, supportAfMode); } // ae list<int32_t> aeModeList = ability->GetSupportedAeModes(); uint32_t aeListSize = aeModeList.size(); IpcIoPushUint32(reply, aeListSize); for (auto supportAeMode : aeModeList) { IpcIoPushInt32(reply, supportAeMode); } } void CameraServer::GetCameraInfo(IpcIo *req, IpcIo *reply) { size_t sz; string cameraId((const char*)(IpcIoPopString(req, &sz))); CameraInfo *info = CameraService::GetInstance()->GetCameraInfo(cameraId); if (info == nullptr) { return; } IpcIoPushInt32(reply, info->GetCameraType()); IpcIoPushInt32(reply, info->GetCameraFacingType()); } void CameraServer::GetCameraIdList(IpcIo *req, IpcIo *reply) { list<string> cameraIdList = CameraService::GetInstance()->GetCameraIdList(); IpcIoPushUint32(reply, cameraIdList.size()); for (string cameraId : cameraIdList) { IpcIoPushString(reply, cameraId.c_str()); } } void CameraServer::CreateCamera(IpcIo *req, IpcIo *reply) { size_t sz; string cameraId((const char*)(IpcIoPopString(req, &sz))); int32_t cameraStatus = CameraService::GetInstance()->CreateCamera(cameraId); SvcIdentity *sid = IpcIoPopSvc(req); #ifdef __LINUX__ BinderAcquire(sid->ipcContext, sid->handle); #endif if (sid == nullptr) { MEDIA_ERR_LOG("sid is null, failed."); return; } OnCameraStatusChange(cameraStatus, sid); } void CameraServer::CloseCamera(IpcIo *req, IpcIo *reply) { MEDIA_INFO_LOG("CloseCamera enter."); size_t sz; string cameraId((const char*)(IpcIoPopString(req, &sz))); int32_t cameraStatus = CameraService::GetInstance()->CloseCamera(cameraId); SvcIdentity *sid = IpcIoPopSvc(req); #ifdef __LINUX__ BinderAcquire(sid->ipcContext, sid->handle); #endif if (sid == nullptr) { MEDIA_ERR_LOG("sid is null, failed."); return; } OnCameraStatusChange(cameraStatus, sid); } void CameraServer::SetCameraConfig(IpcIo *req, IpcIo *reply) { size_t sz; string cameraId((const char*)(IpcIoPopString(req, &sz))); CameraDevice *device_ = CameraService::GetInstance()->GetCameraDevice(cameraId); int32_t setStatus = device_->SetCameraConfig(); IpcIoPushInt32(reply, setStatus); OnCameraConfigured(setStatus); } void CameraServer::SetCameraCallback(IpcIo *req, IpcIo *reply) { sid_ = *IpcIoPopSvc(req); #ifdef __LINUX__ BinderAcquire(sid_.ipcContext, sid_.handle); #endif } FrameConfig *DeserializeFrameConfig(IpcIo &io) { int32_t type = IpcIoPopInt32(&io); auto fc = new FrameConfig(type); uint32_t surfaceNum = IpcIoPopUint32(&io); for (uint32_t i = 0; i < surfaceNum; i++) { Surface *surface = SurfaceImpl::GenericSurfaceByIpcIo(io); if (surface == nullptr) { MEDIA_ERR_LOG("Camera server receive null surface."); delete fc; return nullptr; } fc->AddSurface(*surface); } int32_t qfactor = IpcIoPopInt32(&io); if (qfactor >= 0) { fc->SetParameter(PARAM_KEY_IMAGE_ENCODE_QFACTOR, qfactor); } int32_t frameRate = IpcIoPopInt32(&io); fc->SetParameter(PARAM_KEY_STREAM_FPS, frameRate); MEDIA_INFO_LOG("frameRate is %d", frameRate); int32_t streamFormat = IpcIoPopInt32(&io); fc->SetParameter(CAM_IMAGE_FORMAT, streamFormat); MEDIA_INFO_LOG("streamFormat is %d", streamFormat); BuffPtr *dataBuff = IpcIoPopDataBuff(&io); if (dataBuff == nullptr || dataBuff->buff == nullptr) { MEDIA_ERR_LOG("dataBuff is nullptr."); return fc; } uint8_t *data = (uint8_t *)dataBuff->buff; fc->SetVendorParameter((uint8_t *)dataBuff->buff, dataBuff->buffSz); return fc; } void CameraServer::SetFrameConfig(IpcIo *req, IpcIo *reply) { size_t sz; string cameraId((const char *)(IpcIoPopString(req, &sz))); int32_t streamId = IpcIoPopInt32(req); MEDIA_ERR_LOG("SetFrameConfig streamId(%d).", streamId); CameraDevice *device_ = CameraService::GetInstance()->GetCameraDevice(cameraId); FrameConfig *fc = DeserializeFrameConfig(*req); if (fc == nullptr) { MEDIA_ERR_LOG("Deserialize frame config failed."); return; } delete fc; } void CameraServer::TriggerLoopingCapture(IpcIo *req, IpcIo *reply) { size_t sz; string cameraId((const char*)(IpcIoPopString(req, &sz))); CameraDevice *device_ = CameraService::GetInstance()->GetCameraDevice(cameraId); FrameConfig *fc = DeserializeFrameConfig(*req); if (fc == nullptr) { MEDIA_ERR_LOG("Deserialize frame config failed."); return; } uint32_t streamId = 0; int32_t loopingCaptureStatus = device_->TriggerLoopingCapture(*fc, &streamId); OnTriggerLoopingCaptureFinished(loopingCaptureStatus, streamId); delete fc; } void CameraServer::TriggerSingleCapture(IpcIo *req, IpcIo *reply) { size_t sz; string cameraId((const char *)(IpcIoPopString(req, &sz))); CameraDevice *device_ = CameraService::GetInstance()->GetCameraDevice(cameraId); FrameConfig *fc = DeserializeFrameConfig(*req); if (fc == nullptr) { MEDIA_ERR_LOG("Deserialize frame config failed."); return; } uint32_t streamId = 0; int32_t singleCaptureStatus = device_->TriggerSingleCapture(*fc, &streamId); OnTriggerSingleCaptureFinished(singleCaptureStatus); delete fc; } void CameraServer::StopLoopingCapture(IpcIo *req, IpcIo *reply) { MEDIA_INFO_LOG("StopLoopingCapture in camera_server.cpp!"); size_t sz; string cameraId((const char *)(IpcIoPopString(req, &sz))); CameraDevice *device_ = CameraService::GetInstance()->GetCameraDevice(cameraId); if (device_ == nullptr) { MEDIA_INFO_LOG("device_ is null in camera_server.cpp!"); } device_->StopLoopingCapture(); } void CameraServer::OnCameraStatusChange(int32_t ret, SvcIdentity *sid) { IpcIo io; uint8_t tmpData[DEFAULT_IPC_SIZE]; IpcIoInit(&io, tmpData, DEFAULT_IPC_SIZE, 0); IpcIoPushInt32(&io, ret); int32_t ans = Transact(nullptr, *sid, ON_CAMERA_STATUS_CHANGE, &io, nullptr, LITEIPC_FLAG_ONEWAY, nullptr); if (ans != LITEIPC_OK) { MEDIA_ERR_LOG("Create camera callback : on camera status change failed."); } } void CameraServer::OnTriggerSingleCaptureFinished(int32_t ret) { IpcIo io; uint8_t tmpData[DEFAULT_IPC_SIZE]; IpcIoInit(&io, tmpData, DEFAULT_IPC_SIZE, 0); IpcIoPushInt32(&io, ret); int32_t ans = Transact(nullptr, sid_, ON_TRIGGER_SINGLE_CAPTURE_FINISHED, &io, nullptr, LITEIPC_FLAG_ONEWAY, nullptr); if (ans != LITEIPC_OK) { MEDIA_ERR_LOG("Trigger single capture callback : on trigger single capture frame finished failed."); return; } } void CameraServer::OnTriggerLoopingCaptureFinished(int32_t ret, int32_t streamId) { IpcIo io; uint8_t tmpData[DEFAULT_IPC_SIZE]; IpcIoInit(&io, tmpData, DEFAULT_IPC_SIZE, 0); IpcIoPushInt32(&io, ret); int32_t ans = Transact(nullptr, sid_, ON_TRIGGER_LOOPING_CAPTURE_FINISHED, &io, nullptr, LITEIPC_FLAG_ONEWAY, nullptr); if (ans != LITEIPC_OK) { MEDIA_ERR_LOG("Trigger looping capture callback : on trigger looping capture finished failed."); } } void CameraServer::OnCameraConfigured(int32_t ret) { IpcIo io; uint8_t tmpData[DEFAULT_IPC_SIZE]; IpcIoInit(&io, tmpData, DEFAULT_IPC_SIZE, 0); IpcIoPushInt32(&io, ret); int32_t ans = Transact(nullptr, sid_, ON_CAMERA_CONFIGURED, &io, nullptr, LITEIPC_FLAG_ONEWAY, nullptr); if (ans != LITEIPC_OK) { MEDIA_ERR_LOG("Camera config callback : on trigger looping capture finished failed."); } } } // namespace Media } // namespace OHOS
/*============================================================================ KWSys - Kitware System Library Copyright 2000-2009 Kitware, Inc., Insight Software Consortium Distributed under the OSI-approved BSD License (the "License"); see accompanying file Copyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the License for more information. ============================================================================*/ #include "kwsysPrivate.h" #include KWSYS_HEADER(CommandLineArguments.hxx) #include KWSYS_HEADER(Configure.hxx) #include KWSYS_HEADER(String.hxx) // Work-around CMake dependency scanning limitation. This must // duplicate the above list of headers. #if 0 # include "CommandLineArguments.hxx.in" # include "Configure.hxx.in" # include "String.hxx.in" #endif #include <vector> #include <map> #include <set> #include <sstream> #include <iostream> #include <stdio.h> #include <stdlib.h> #include <string.h> #ifdef _MSC_VER # pragma warning (disable: 4786) #endif #if defined(__sgi) && !defined(__GNUC__) # pragma set woff 1375 /* base class destructor not virtual */ #endif #if 0 # define CommandLineArguments_DEBUG(x) \ std::cout << __LINE__ << " CLA: " << x << std::endl #else # define CommandLineArguments_DEBUG(x) #endif namespace KWSYS_NAMESPACE { //---------------------------------------------------------------------------- //============================================================================ struct CommandLineArgumentsCallbackStructure { const char* Argument; int ArgumentType; CommandLineArguments::CallbackType Callback; void* CallData; void* Variable; int VariableType; const char* Help; }; class CommandLineArgumentsVectorOfStrings : public std::vector<kwsys::String> {}; class CommandLineArgumentsSetOfStrings : public std::set<kwsys::String> {}; class CommandLineArgumentsMapOfStrucs : public std::map<kwsys::String, CommandLineArgumentsCallbackStructure> {}; class CommandLineArgumentsInternal { public: CommandLineArgumentsInternal() { this->UnknownArgumentCallback = 0; this->ClientData = 0; this->LastArgument = 0; } typedef CommandLineArgumentsVectorOfStrings VectorOfStrings; typedef CommandLineArgumentsMapOfStrucs CallbacksMap; typedef kwsys::String String; typedef CommandLineArgumentsSetOfStrings SetOfStrings; VectorOfStrings Argv; String Argv0; CallbacksMap Callbacks; CommandLineArguments::ErrorCallbackType UnknownArgumentCallback; void* ClientData; VectorOfStrings::size_type LastArgument; VectorOfStrings UnusedArguments; }; //============================================================================ //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- CommandLineArguments::CommandLineArguments() { this->Internals = new CommandLineArguments::Internal; this->Help = ""; this->LineLength = 80; this->StoreUnusedArgumentsFlag = false; } //---------------------------------------------------------------------------- CommandLineArguments::~CommandLineArguments() { delete this->Internals; } //---------------------------------------------------------------------------- void CommandLineArguments::Initialize(int argc, const char* const argv[]) { int cc; this->Initialize(); this->Internals->Argv0 = argv[0]; for ( cc = 1; cc < argc; cc ++ ) { this->ProcessArgument(argv[cc]); } } //---------------------------------------------------------------------------- void CommandLineArguments::Initialize(int argc, char* argv[]) { this->Initialize(argc, static_cast<const char* const*>(argv)); } //---------------------------------------------------------------------------- void CommandLineArguments::Initialize() { this->Internals->Argv.clear(); this->Internals->LastArgument = 0; } //---------------------------------------------------------------------------- void CommandLineArguments::ProcessArgument(const char* arg) { this->Internals->Argv.push_back(arg); } //---------------------------------------------------------------------------- bool CommandLineArguments::GetMatchedArguments( std::vector<std::string>* matches, const std::string& arg) { matches->clear(); CommandLineArguments::Internal::CallbacksMap::iterator it; // Does the argument match to any we know about? for ( it = this->Internals->Callbacks.begin(); it != this->Internals->Callbacks.end(); it ++ ) { const CommandLineArguments::Internal::String& parg = it->first; CommandLineArgumentsCallbackStructure *cs = &it->second; if (cs->ArgumentType == CommandLineArguments::NO_ARGUMENT || cs->ArgumentType == CommandLineArguments::SPACE_ARGUMENT) { if ( arg == parg ) { matches->push_back(parg); } } else if ( arg.find( parg ) == 0 ) { matches->push_back(parg); } } return !matches->empty(); } //---------------------------------------------------------------------------- int CommandLineArguments::Parse() { std::vector<std::string>::size_type cc; std::vector<std::string> matches; if ( this->StoreUnusedArgumentsFlag ) { this->Internals->UnusedArguments.clear(); } for ( cc = 0; cc < this->Internals->Argv.size(); cc ++ ) { const std::string& arg = this->Internals->Argv[cc]; CommandLineArguments_DEBUG("Process argument: " << arg); this->Internals->LastArgument = cc; if ( this->GetMatchedArguments(&matches, arg) ) { // Ok, we found one or more arguments that match what user specified. // Let's find the longest one. CommandLineArguments::Internal::VectorOfStrings::size_type kk; CommandLineArguments::Internal::VectorOfStrings::size_type maxidx = 0; CommandLineArguments::Internal::String::size_type maxlen = 0; for ( kk = 0; kk < matches.size(); kk ++ ) { if ( matches[kk].size() > maxlen ) { maxlen = matches[kk].size(); maxidx = kk; } } // So, the longest one is probably the right one. Now see if it has any // additional value CommandLineArgumentsCallbackStructure *cs = &this->Internals->Callbacks[matches[maxidx]]; const std::string& sarg = matches[maxidx]; if ( cs->Argument != sarg ) { abort(); } switch ( cs->ArgumentType ) { case NO_ARGUMENT: // No value if ( !this->PopulateVariable(cs, 0) ) { return 0; } break; case SPACE_ARGUMENT: if ( cc == this->Internals->Argv.size()-1 ) { this->Internals->LastArgument --; return 0; } CommandLineArguments_DEBUG("This is a space argument: " << arg << " value: " << this->Internals->Argv[cc+1]); // Value is the next argument if ( !this->PopulateVariable(cs, this->Internals->Argv[cc+1].c_str()) ) { return 0; } cc ++; break; case EQUAL_ARGUMENT: if ( arg.size() == sarg.size() || arg.at(sarg.size()) != '=' ) { this->Internals->LastArgument --; return 0; } // Value is everythng followed the '=' sign if ( !this->PopulateVariable(cs, arg.c_str() + sarg.size() + 1) ) { return 0; } break; case CONCAT_ARGUMENT: // Value is whatever follows the argument if ( !this->PopulateVariable(cs, arg.c_str() + sarg.size()) ) { return 0; } break; case MULTI_ARGUMENT: // Suck in all the rest of the arguments CommandLineArguments_DEBUG("This is a multi argument: " << arg); for (cc++; cc < this->Internals->Argv.size(); ++ cc ) { const std::string& marg = this->Internals->Argv[cc]; CommandLineArguments_DEBUG(" check multi argument value: " << marg); if ( this->GetMatchedArguments(&matches, marg) ) { CommandLineArguments_DEBUG("End of multi argument " << arg << " with value: " << marg); break; } CommandLineArguments_DEBUG(" populate multi argument value: " << marg); if ( !this->PopulateVariable(cs, marg.c_str()) ) { return 0; } } if ( cc != this->Internals->Argv.size() ) { CommandLineArguments_DEBUG("Again End of multi argument " << arg); cc--; continue; } break; default: std::cerr << "Got unknown argument type: \"" << cs->ArgumentType << "\"" << std::endl; this->Internals->LastArgument --; return 0; } } else { // Handle unknown arguments if ( this->Internals->UnknownArgumentCallback ) { if ( !this->Internals->UnknownArgumentCallback(arg.c_str(), this->Internals->ClientData) ) { this->Internals->LastArgument --; return 0; } return 1; } else if ( this->StoreUnusedArgumentsFlag ) { CommandLineArguments_DEBUG("Store unused argument " << arg); this->Internals->UnusedArguments.push_back(arg); } else { std::cerr << "Got unknown argument: \"" << arg << "\"" << std::endl; this->Internals->LastArgument --; return 0; } } } return 1; } //---------------------------------------------------------------------------- void CommandLineArguments::GetRemainingArguments(int* argc, char*** argv) { CommandLineArguments::Internal::VectorOfStrings::size_type size = this->Internals->Argv.size() - this->Internals->LastArgument + 1; CommandLineArguments::Internal::VectorOfStrings::size_type cc; // Copy Argv0 as the first argument char** args = new char*[ size ]; args[0] = new char[ this->Internals->Argv0.size() + 1 ]; strcpy(args[0], this->Internals->Argv0.c_str()); int cnt = 1; // Copy everything after the LastArgument, since that was not parsed. for ( cc = this->Internals->LastArgument+1; cc < this->Internals->Argv.size(); cc ++ ) { args[cnt] = new char[ this->Internals->Argv[cc].size() + 1]; strcpy(args[cnt], this->Internals->Argv[cc].c_str()); cnt ++; } *argc = cnt; *argv = args; } //---------------------------------------------------------------------------- void CommandLineArguments::GetUnusedArguments(int* argc, char*** argv) { CommandLineArguments::Internal::VectorOfStrings::size_type size = this->Internals->UnusedArguments.size() + 1; CommandLineArguments::Internal::VectorOfStrings::size_type cc; // Copy Argv0 as the first argument char** args = new char*[ size ]; args[0] = new char[ this->Internals->Argv0.size() + 1 ]; strcpy(args[0], this->Internals->Argv0.c_str()); int cnt = 1; // Copy everything after the LastArgument, since that was not parsed. for ( cc = 0; cc < this->Internals->UnusedArguments.size(); cc ++ ) { kwsys::String &str = this->Internals->UnusedArguments[cc]; args[cnt] = new char[ str.size() + 1]; strcpy(args[cnt], str.c_str()); cnt ++; } *argc = cnt; *argv = args; } //---------------------------------------------------------------------------- void CommandLineArguments::DeleteRemainingArguments(int argc, char*** argv) { int cc; for ( cc = 0; cc < argc; ++ cc ) { delete [] (*argv)[cc]; } delete [] *argv; } //---------------------------------------------------------------------------- void CommandLineArguments::AddCallback(const char* argument, ArgumentTypeEnum type, CallbackType callback, void* call_data, const char* help) { CommandLineArgumentsCallbackStructure s; s.Argument = argument; s.ArgumentType = type; s.Callback = callback; s.CallData = call_data; s.VariableType = CommandLineArguments::NO_VARIABLE_TYPE; s.Variable = 0; s.Help = help; this->Internals->Callbacks[argument] = s; this->GenerateHelp(); } //---------------------------------------------------------------------------- void CommandLineArguments::AddArgument(const char* argument, ArgumentTypeEnum type, VariableTypeEnum vtype, void* variable, const char* help) { CommandLineArgumentsCallbackStructure s; s.Argument = argument; s.ArgumentType = type; s.Callback = 0; s.CallData = 0; s.VariableType = vtype; s.Variable = variable; s.Help = help; this->Internals->Callbacks[argument] = s; this->GenerateHelp(); } //---------------------------------------------------------------------------- #define CommandLineArgumentsAddArgumentMacro(type, ctype) \ void CommandLineArguments::AddArgument(const char* argument, ArgumentTypeEnum type, \ ctype* variable, const char* help) \ { \ this->AddArgument(argument, type, CommandLineArguments::type##_TYPE, variable, help); \ } CommandLineArgumentsAddArgumentMacro(BOOL, bool) CommandLineArgumentsAddArgumentMacro(INT, int) CommandLineArgumentsAddArgumentMacro(DOUBLE, double) CommandLineArgumentsAddArgumentMacro(STRING, char*) CommandLineArgumentsAddArgumentMacro(STL_STRING, std::string) CommandLineArgumentsAddArgumentMacro(VECTOR_BOOL, std::vector<bool>) CommandLineArgumentsAddArgumentMacro(VECTOR_INT, std::vector<int>) CommandLineArgumentsAddArgumentMacro(VECTOR_DOUBLE, std::vector<double>) CommandLineArgumentsAddArgumentMacro(VECTOR_STRING, std::vector<char*>) CommandLineArgumentsAddArgumentMacro(VECTOR_STL_STRING, std::vector<std::string>) //---------------------------------------------------------------------------- #define CommandLineArgumentsAddBooleanArgumentMacro(type, ctype) \ void CommandLineArguments::AddBooleanArgument(const char* argument, \ ctype* variable, const char* help) \ { \ this->AddArgument(argument, CommandLineArguments::NO_ARGUMENT, \ CommandLineArguments::type##_TYPE, variable, help); \ } CommandLineArgumentsAddBooleanArgumentMacro(BOOL, bool) CommandLineArgumentsAddBooleanArgumentMacro(INT, int) CommandLineArgumentsAddBooleanArgumentMacro(DOUBLE, double) CommandLineArgumentsAddBooleanArgumentMacro(STRING, char*) CommandLineArgumentsAddBooleanArgumentMacro(STL_STRING, std::string) //---------------------------------------------------------------------------- void CommandLineArguments::SetClientData(void* client_data) { this->Internals->ClientData = client_data; } //---------------------------------------------------------------------------- void CommandLineArguments::SetUnknownArgumentCallback( CommandLineArguments::ErrorCallbackType callback) { this->Internals->UnknownArgumentCallback = callback; } //---------------------------------------------------------------------------- const char* CommandLineArguments::GetHelp(const char* arg) { CommandLineArguments::Internal::CallbacksMap::iterator it = this->Internals->Callbacks.find(arg); if ( it == this->Internals->Callbacks.end() ) { return 0; } // Since several arguments may point to the same argument, find the one this // one point to if this one is pointing to another argument. CommandLineArgumentsCallbackStructure *cs = &(it->second); for(;;) { CommandLineArguments::Internal::CallbacksMap::iterator hit = this->Internals->Callbacks.find(cs->Help); if ( hit == this->Internals->Callbacks.end() ) { break; } cs = &(hit->second); } return cs->Help; } //---------------------------------------------------------------------------- void CommandLineArguments::SetLineLength(unsigned int ll) { if ( ll < 9 || ll > 1000 ) { return; } this->LineLength = ll; this->GenerateHelp(); } //---------------------------------------------------------------------------- const char* CommandLineArguments::GetArgv0() { return this->Internals->Argv0.c_str(); } //---------------------------------------------------------------------------- unsigned int CommandLineArguments::GetLastArgument() { return static_cast<unsigned int>(this->Internals->LastArgument + 1); } //---------------------------------------------------------------------------- void CommandLineArguments::GenerateHelp() { std::ostringstream str; // Collapse all arguments into the map of vectors of all arguments that do // the same thing. CommandLineArguments::Internal::CallbacksMap::iterator it; typedef std::map<CommandLineArguments::Internal::String, CommandLineArguments::Internal::SetOfStrings > MapArgs; MapArgs mp; MapArgs::iterator mpit, smpit; for ( it = this->Internals->Callbacks.begin(); it != this->Internals->Callbacks.end(); it ++ ) { CommandLineArgumentsCallbackStructure *cs = &(it->second); mpit = mp.find(cs->Help); if ( mpit != mp.end() ) { mpit->second.insert(it->first); mp[it->first].insert(it->first); } else { mp[it->first].insert(it->first); } } for ( it = this->Internals->Callbacks.begin(); it != this->Internals->Callbacks.end(); it ++ ) { CommandLineArgumentsCallbackStructure *cs = &(it->second); mpit = mp.find(cs->Help); if ( mpit != mp.end() ) { mpit->second.insert(it->first); smpit = mp.find(it->first); CommandLineArguments::Internal::SetOfStrings::iterator sit; for ( sit = smpit->second.begin(); sit != smpit->second.end(); sit++ ) { mpit->second.insert(*sit); } mp.erase(smpit); } else { mp[it->first].insert(it->first); } } // Find the length of the longest string CommandLineArguments::Internal::String::size_type maxlen = 0; for ( mpit = mp.begin(); mpit != mp.end(); mpit ++ ) { CommandLineArguments::Internal::SetOfStrings::iterator sit; for ( sit = mpit->second.begin(); sit != mpit->second.end(); sit++ ) { CommandLineArguments::Internal::String::size_type clen = sit->size(); switch ( this->Internals->Callbacks[*sit].ArgumentType ) { case CommandLineArguments::NO_ARGUMENT: clen += 0; break; case CommandLineArguments::CONCAT_ARGUMENT: clen += 3; break; case CommandLineArguments::SPACE_ARGUMENT: clen += 4; break; case CommandLineArguments::EQUAL_ARGUMENT: clen += 4; break; } if ( clen > maxlen ) { maxlen = clen; } } } // Create format for that string char format[80]; sprintf(format, " %%-%us ", static_cast<unsigned int>(maxlen)); maxlen += 4; // For the space before and after the option // Print help for each option for ( mpit = mp.begin(); mpit != mp.end(); mpit ++ ) { CommandLineArguments::Internal::SetOfStrings::iterator sit; for ( sit = mpit->second.begin(); sit != mpit->second.end(); sit++ ) { str << std::endl; char argument[100]; sprintf(argument, "%s", sit->c_str()); switch ( this->Internals->Callbacks[*sit].ArgumentType ) { case CommandLineArguments::NO_ARGUMENT: break; case CommandLineArguments::CONCAT_ARGUMENT: strcat(argument, "opt"); break; case CommandLineArguments::SPACE_ARGUMENT: strcat(argument, " opt"); break; case CommandLineArguments::EQUAL_ARGUMENT: strcat(argument, "=opt"); break; case CommandLineArguments::MULTI_ARGUMENT: strcat(argument, " opt opt ..."); break; } char buffer[80]; sprintf(buffer, format, argument); str << buffer; } const char* ptr = this->Internals->Callbacks[mpit->first].Help; size_t len = strlen(ptr); int cnt = 0; while ( len > 0) { // If argument with help is longer than line length, split it on previous // space (or tab) and continue on the next line CommandLineArguments::Internal::String::size_type cc; for ( cc = 0; ptr[cc]; cc ++ ) { if ( *ptr == ' ' || *ptr == '\t' ) { ptr ++; len --; } } if ( cnt > 0 ) { for ( cc = 0; cc < maxlen; cc ++ ) { str << " "; } } CommandLineArguments::Internal::String::size_type skip = len; if ( skip > this->LineLength - maxlen ) { skip = this->LineLength - maxlen; for ( cc = skip-1; cc > 0; cc -- ) { if ( ptr[cc] == ' ' || ptr[cc] == '\t' ) { break; } } if ( cc != 0 ) { skip = cc; } } str.write(ptr, static_cast<std::streamsize>(skip)); str << std::endl; ptr += skip; len -= skip; cnt ++; } } /* // This can help debugging help string str << endl; unsigned int cc; for ( cc = 0; cc < this->LineLength; cc ++ ) { str << cc % 10; } str << endl; */ this->Help = str.str(); } //---------------------------------------------------------------------------- void CommandLineArguments::PopulateVariable( bool* variable, const std::string& value) { if ( value == "1" || value == "ON" || value == "on" || value == "On" || value == "TRUE" || value == "true" || value == "True" || value == "yes" || value == "Yes" || value == "YES" ) { *variable = true; } else { *variable = false; } } //---------------------------------------------------------------------------- void CommandLineArguments::PopulateVariable( int* variable, const std::string& value) { char* res = 0; *variable = static_cast<int>(strtol(value.c_str(), &res, 10)); //if ( res && *res ) // { // Can handle non-int // } } //---------------------------------------------------------------------------- void CommandLineArguments::PopulateVariable( double* variable, const std::string& value) { char* res = 0; *variable = strtod(value.c_str(), &res); //if ( res && *res ) // { // Can handle non-double // } } //---------------------------------------------------------------------------- void CommandLineArguments::PopulateVariable( char** variable, const std::string& value) { if ( *variable ) { delete [] *variable; *variable = 0; } *variable = new char[ value.size() + 1 ]; strcpy(*variable, value.c_str()); } //---------------------------------------------------------------------------- void CommandLineArguments::PopulateVariable( std::string* variable, const std::string& value) { *variable = value; } //---------------------------------------------------------------------------- void CommandLineArguments::PopulateVariable( std::vector<bool>* variable, const std::string& value) { bool val = false; if ( value == "1" || value == "ON" || value == "on" || value == "On" || value == "TRUE" || value == "true" || value == "True" || value == "yes" || value == "Yes" || value == "YES" ) { val = true; } variable->push_back(val); } //---------------------------------------------------------------------------- void CommandLineArguments::PopulateVariable( std::vector<int>* variable, const std::string& value) { char* res = 0; variable->push_back(static_cast<int>(strtol(value.c_str(), &res, 10))); //if ( res && *res ) // { // Can handle non-int // } } //---------------------------------------------------------------------------- void CommandLineArguments::PopulateVariable( std::vector<double>* variable, const std::string& value) { char* res = 0; variable->push_back(strtod(value.c_str(), &res)); //if ( res && *res ) // { // Can handle non-int // } } //---------------------------------------------------------------------------- void CommandLineArguments::PopulateVariable( std::vector<char*>* variable, const std::string& value) { char* var = new char[ value.size() + 1 ]; strcpy(var, value.c_str()); variable->push_back(var); } //---------------------------------------------------------------------------- void CommandLineArguments::PopulateVariable( std::vector<std::string>* variable, const std::string& value) { variable->push_back(value); } //---------------------------------------------------------------------------- bool CommandLineArguments::PopulateVariable(CommandLineArgumentsCallbackStructure* cs, const char* value) { // Call the callback if ( cs->Callback ) { if ( !cs->Callback(cs->Argument, value, cs->CallData) ) { this->Internals->LastArgument --; return 0; } } CommandLineArguments_DEBUG("Set argument: " << cs->Argument << " to " << value); if ( cs->Variable ) { std::string var = "1"; if ( value ) { var = value; } switch ( cs->VariableType ) { case CommandLineArguments::INT_TYPE: this->PopulateVariable(static_cast<int*>(cs->Variable), var); break; case CommandLineArguments::DOUBLE_TYPE: this->PopulateVariable(static_cast<double*>(cs->Variable), var); break; case CommandLineArguments::STRING_TYPE: this->PopulateVariable(static_cast<char**>(cs->Variable), var); break; case CommandLineArguments::STL_STRING_TYPE: this->PopulateVariable(static_cast<std::string*>(cs->Variable), var); break; case CommandLineArguments::BOOL_TYPE: this->PopulateVariable(static_cast<bool*>(cs->Variable), var); break; case CommandLineArguments::VECTOR_BOOL_TYPE: this->PopulateVariable(static_cast<std::vector<bool>*>(cs->Variable), var); break; case CommandLineArguments::VECTOR_INT_TYPE: this->PopulateVariable(static_cast<std::vector<int>*>(cs->Variable), var); break; case CommandLineArguments::VECTOR_DOUBLE_TYPE: this->PopulateVariable(static_cast<std::vector<double>*>(cs->Variable), var); break; case CommandLineArguments::VECTOR_STRING_TYPE: this->PopulateVariable(static_cast<std::vector<char*>*>(cs->Variable), var); break; case CommandLineArguments::VECTOR_STL_STRING_TYPE: this->PopulateVariable(static_cast<std::vector<std::string>*>(cs->Variable), var); break; default: std::cerr << "Got unknown variable type: \"" << cs->VariableType << "\"" << std::endl; this->Internals->LastArgument --; return 0; } } return 1; } } // namespace KWSYS_NAMESPACE
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // On Linux, when the user tries to launch a second copy of chrome, we check // for a socket in the user's profile directory. If the socket file is open we // send a message to the first chrome browser process with the current // directory and second process command line flags. The second process then // exits. // // Because many networked filesystem implementations do not support unix domain // sockets, we create the socket in a temporary directory and create a symlink // in the profile. This temporary directory is no longer bound to the profile, // and may disappear across a reboot or login to a separate session. To bind // them, we store a unique cookie in the profile directory, which must also be // present in the remote directory to connect. The cookie is checked both before // and after the connection. /tmp is sticky, and different Chrome sessions use // different cookies. Thus, a matching cookie before and after means the // connection was to a directory with a valid cookie. // // We also have a lock file, which is a symlink to a non-existent destination. // The destination is a string containing the hostname and process id of // chrome's browser process, eg. "SingletonLock -> example.com-9156". When the // first copy of chrome exits it will delete the lock file on shutdown, so that // a different instance on a different host may then use the profile directory. // // If writing to the socket fails, the hostname in the lock is checked to see if // another instance is running a different host using a shared filesystem (nfs, // etc.) If the hostname differs an error is displayed and the second process // exits. Otherwise the first process (if any) is killed and the second process // starts as normal. // // When the second process sends the current directory and command line flags to // the first process, it waits for an ACK message back from the first process // for a certain time. If there is no ACK message back in time, then the first // process will be considered as hung for some reason. The second process then // retrieves the process id from the symbol link and kills it by sending // SIGKILL. Then the second process starts as normal. #include "chrome/browser/process_singleton.h" #include <errno.h> #include <fcntl.h> #include <signal.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/un.h> #include <unistd.h> #include <cstring> #include <memory> #include <set> #include <string> #include <stddef.h> #include "atom/browser/browser.h" #include "atom/common/atom_command_line.h" #include "base/base_paths.h" #include "base/bind.h" #include "base/command_line.h" #include "base/files/file_descriptor_watcher_posix.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/location.h" #include "base/logging.h" #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/message_loop/message_loop.h" #include "base/metrics/histogram_macros.h" #include "base/path_service.h" #include "base/posix/eintr_wrapper.h" #include "base/posix/safe_strerror.h" #include "base/rand_util.h" #include "base/sequenced_task_runner_helpers.h" #include "base/single_thread_task_runner.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_split.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/strings/sys_string_conversions.h" #include "base/strings/utf_string_conversions.h" #include "base/task/post_task.h" #include "base/threading/platform_thread.h" #include "base/threading/thread_restrictions.h" #include "base/threading/thread_task_runner_handle.h" #include "base/time/time.h" #include "base/timer/timer.h" #include "build/build_config.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "net/base/network_interfaces.h" #include "ui/base/l10n/l10n_util.h" #if defined(TOOLKIT_VIEWS) && defined(OS_LINUX) && !defined(OS_CHROMEOS) #include "ui/views/linux_ui/linux_ui.h" #endif using content::BrowserThread; namespace { // Timeout for the current browser process to respond. 20 seconds should be // enough. const int kTimeoutInSeconds = 20; // Number of retries to notify the browser. 20 retries over 20 seconds = 1 try // per second. const int kRetryAttempts = 20; static bool g_disable_prompt; const char kStartToken[] = "START"; const char kACKToken[] = "ACK"; const char kShutdownToken[] = "SHUTDOWN"; const char kTokenDelimiter = '\0'; const int kMaxMessageLength = 32 * 1024; const int kMaxACKMessageLength = arraysize(kShutdownToken) - 1; const char kLockDelimiter = '-'; const base::FilePath::CharType kSingletonCookieFilename[] = FILE_PATH_LITERAL("SingletonCookie"); const base::FilePath::CharType kSingletonLockFilename[] = FILE_PATH_LITERAL("SingletonLock"); const base::FilePath::CharType kSingletonSocketFilename[] = FILE_PATH_LITERAL("SS"); // Set the close-on-exec bit on a file descriptor. // Returns 0 on success, -1 on failure. int SetCloseOnExec(int fd) { int flags = fcntl(fd, F_GETFD, 0); if (-1 == flags) return flags; if (flags & FD_CLOEXEC) return 0; return fcntl(fd, F_SETFD, flags | FD_CLOEXEC); } // Close a socket and check return value. void CloseSocket(int fd) { int rv = IGNORE_EINTR(close(fd)); DCHECK_EQ(0, rv) << "Error closing socket: " << base::safe_strerror(errno); } // Write a message to a socket fd. bool WriteToSocket(int fd, const char* message, size_t length) { DCHECK(message); DCHECK(length); size_t bytes_written = 0; do { ssize_t rv = HANDLE_EINTR( write(fd, message + bytes_written, length - bytes_written)); if (rv < 0) { if (errno == EAGAIN || errno == EWOULDBLOCK) { // The socket shouldn't block, we're sending so little data. Just give // up here, since NotifyOtherProcess() doesn't have an asynchronous api. LOG(ERROR) << "ProcessSingleton would block on write(), so it gave up."; return false; } PLOG(ERROR) << "write() failed"; return false; } bytes_written += rv; } while (bytes_written < length); return true; } struct timeval TimeDeltaToTimeVal(const base::TimeDelta& delta) { struct timeval result; result.tv_sec = delta.InSeconds(); result.tv_usec = delta.InMicroseconds() % base::Time::kMicrosecondsPerSecond; return result; } // Wait a socket for read for a certain timeout. // Returns -1 if error occurred, 0 if timeout reached, > 0 if the socket is // ready for read. int WaitSocketForRead(int fd, const base::TimeDelta& timeout) { fd_set read_fds; struct timeval tv = TimeDeltaToTimeVal(timeout); FD_ZERO(&read_fds); FD_SET(fd, &read_fds); return HANDLE_EINTR(select(fd + 1, &read_fds, NULL, NULL, &tv)); } // Read a message from a socket fd, with an optional timeout. // If |timeout| <= 0 then read immediately. // Return number of bytes actually read, or -1 on error. ssize_t ReadFromSocket(int fd, char* buf, size_t bufsize, const base::TimeDelta& timeout) { if (timeout > base::TimeDelta()) { int rv = WaitSocketForRead(fd, timeout); if (rv <= 0) return rv; } size_t bytes_read = 0; do { ssize_t rv = HANDLE_EINTR(read(fd, buf + bytes_read, bufsize - bytes_read)); if (rv < 0) { if (errno != EAGAIN && errno != EWOULDBLOCK) { PLOG(ERROR) << "read() failed"; return rv; } else { // It would block, so we just return what has been read. return bytes_read; } } else if (!rv) { // No more data to read. return bytes_read; } else { bytes_read += rv; } } while (bytes_read < bufsize); return bytes_read; } // Set up a sockaddr appropriate for messaging. void SetupSockAddr(const std::string& path, struct sockaddr_un* addr) { addr->sun_family = AF_UNIX; CHECK(path.length() < arraysize(addr->sun_path)) << "Socket path too long: " << path; base::strlcpy(addr->sun_path, path.c_str(), arraysize(addr->sun_path)); } // Set up a socket appropriate for messaging. int SetupSocketOnly() { int sock = socket(PF_UNIX, SOCK_STREAM, 0); PCHECK(sock >= 0) << "socket() failed"; DCHECK(base::SetNonBlocking(sock)) << "Failed to make non-blocking socket."; int rv = SetCloseOnExec(sock); DCHECK_EQ(0, rv) << "Failed to set CLOEXEC on socket."; return sock; } // Set up a socket and sockaddr appropriate for messaging. void SetupSocket(const std::string& path, int* sock, struct sockaddr_un* addr) { *sock = SetupSocketOnly(); SetupSockAddr(path, addr); } // Read a symbolic link, return empty string if given path is not a symbol link. base::FilePath ReadLink(const base::FilePath& path) { base::FilePath target; if (!base::ReadSymbolicLink(path, &target)) { // The only errno that should occur is ENOENT. if (errno != 0 && errno != ENOENT) PLOG(ERROR) << "readlink(" << path.value() << ") failed"; } return target; } // Unlink a path. Return true on success. bool UnlinkPath(const base::FilePath& path) { int rv = unlink(path.value().c_str()); if (rv < 0 && errno != ENOENT) PLOG(ERROR) << "Failed to unlink " << path.value(); return rv == 0; } // Create a symlink. Returns true on success. bool SymlinkPath(const base::FilePath& target, const base::FilePath& path) { if (!base::CreateSymbolicLink(target, path)) { // Double check the value in case symlink suceeded but we got an incorrect // failure due to NFS packet loss & retry. int saved_errno = errno; if (ReadLink(path) != target) { // If we failed to create the lock, most likely another instance won the // startup race. errno = saved_errno; PLOG(ERROR) << "Failed to create " << path.value(); return false; } } return true; } // Extract the hostname and pid from the lock symlink. // Returns true if the lock existed. bool ParseLockPath(const base::FilePath& path, std::string* hostname, int* pid) { std::string real_path = ReadLink(path).value(); if (real_path.empty()) return false; std::string::size_type pos = real_path.rfind(kLockDelimiter); // If the path is not a symbolic link, or doesn't contain what we expect, // bail. if (pos == std::string::npos) { *hostname = ""; *pid = -1; return true; } *hostname = real_path.substr(0, pos); const std::string& pid_str = real_path.substr(pos + 1); if (!base::StringToInt(pid_str, pid)) *pid = -1; return true; } // Returns true if the user opted to unlock the profile. bool DisplayProfileInUseError(const base::FilePath& lock_path, const std::string& hostname, int pid) { return true; } bool IsChromeProcess(pid_t pid) { base::FilePath other_chrome_path(base::GetProcessExecutablePath(pid)); auto* command_line = base::CommandLine::ForCurrentProcess(); base::FilePath exec_path(command_line->GetProgram()); base::PathService::Get(base::FILE_EXE, &exec_path); return (!other_chrome_path.empty() && other_chrome_path.BaseName() == exec_path.BaseName()); } // A helper class to hold onto a socket. class ScopedSocket { public: ScopedSocket() : fd_(-1) { Reset(); } ~ScopedSocket() { Close(); } int fd() { return fd_; } void Reset() { Close(); fd_ = SetupSocketOnly(); } void Close() { if (fd_ >= 0) CloseSocket(fd_); fd_ = -1; } private: int fd_; }; // Returns a random string for uniquifying profile connections. std::string GenerateCookie() { return base::NumberToString(base::RandUint64()); } bool CheckCookie(const base::FilePath& path, const base::FilePath& cookie) { return (cookie == ReadLink(path)); } bool IsAppSandboxed() { #if defined(OS_MACOSX) // NB: There is no sane API for this, we have to just guess by // reading tea leaves base::FilePath home_dir; if (!base::PathService::Get(base::DIR_HOME, &home_dir)) { return false; } return home_dir.value().find("Library/Containers") != std::string::npos; #else return false; #endif // defined(OS_MACOSX) } bool ConnectSocket(ScopedSocket* socket, const base::FilePath& socket_path, const base::FilePath& cookie_path) { base::FilePath socket_target; if (base::ReadSymbolicLink(socket_path, &socket_target)) { // It's a symlink. Read the cookie. base::FilePath cookie = ReadLink(cookie_path); if (cookie.empty()) return false; base::FilePath remote_cookie = socket_target.DirName().Append(kSingletonCookieFilename); // Verify the cookie before connecting. if (!CheckCookie(remote_cookie, cookie)) return false; // Now we know the directory was (at that point) created by the profile // owner. Try to connect. sockaddr_un addr; SetupSockAddr(socket_target.value(), &addr); int ret = HANDLE_EINTR(connect( socket->fd(), reinterpret_cast<sockaddr*>(&addr), sizeof(addr))); if (ret != 0) return false; // Check the cookie again. We only link in /tmp, which is sticky, so, if the // directory is still correct, it must have been correct in-between when we // connected. POSIX, sadly, lacks a connectat(). if (!CheckCookie(remote_cookie, cookie)) { socket->Reset(); return false; } // Success! return true; } else if (errno == EINVAL) { // It exists, but is not a symlink (or some other error we detect // later). Just connect to it directly; this is an older version of Chrome. sockaddr_un addr; SetupSockAddr(socket_path.value(), &addr); int ret = HANDLE_EINTR(connect( socket->fd(), reinterpret_cast<sockaddr*>(&addr), sizeof(addr))); return (ret == 0); } else { // File is missing, or other error. if (errno != ENOENT) PLOG(ERROR) << "readlink failed"; return false; } } #if defined(OS_MACOSX) bool ReplaceOldSingletonLock(const base::FilePath& symlink_content, const base::FilePath& lock_path) { // Try taking an flock(2) on the file. Failure means the lock is taken so we // should quit. base::ScopedFD lock_fd(HANDLE_EINTR( open(lock_path.value().c_str(), O_RDWR | O_CREAT | O_SYMLINK, 0644))); if (!lock_fd.is_valid()) { PLOG(ERROR) << "Could not open singleton lock"; return false; } int rc = HANDLE_EINTR(flock(lock_fd.get(), LOCK_EX | LOCK_NB)); if (rc == -1) { if (errno == EWOULDBLOCK) { LOG(ERROR) << "Singleton lock held by old process."; } else { PLOG(ERROR) << "Error locking singleton lock"; } return false; } // Successfully taking the lock means we can replace it with the a new symlink // lock. We never flock() the lock file from now on. I.e. we assume that an // old version of Chrome will not run with the same user data dir after this // version has run. if (!base::DeleteFile(lock_path, false)) { PLOG(ERROR) << "Could not delete old singleton lock."; return false; } return SymlinkPath(symlink_content, lock_path); } #endif // defined(OS_MACOSX) } // namespace /////////////////////////////////////////////////////////////////////////////// // ProcessSingleton::LinuxWatcher // A helper class for a Linux specific implementation of the process singleton. // This class sets up a listener on the singleton socket and handles parsing // messages that come in on the singleton socket. class ProcessSingleton::LinuxWatcher : public base::RefCountedThreadSafe<ProcessSingleton::LinuxWatcher, BrowserThread::DeleteOnIOThread> { public: // A helper class to read message from an established socket. class SocketReader { public: SocketReader(ProcessSingleton::LinuxWatcher* parent, scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner, int fd) : parent_(parent), ui_task_runner_(ui_task_runner), fd_(fd), bytes_read_(0) { DCHECK_CURRENTLY_ON(BrowserThread::IO); // Wait for reads. fd_watch_controller_ = base::FileDescriptorWatcher::WatchReadable( fd, base::Bind(&SocketReader::OnSocketCanReadWithoutBlocking, base::Unretained(this))); // If we haven't completed in a reasonable amount of time, give up. timer_.Start(FROM_HERE, base::TimeDelta::FromSeconds(kTimeoutInSeconds), this, &SocketReader::CleanupAndDeleteSelf); } ~SocketReader() { CloseSocket(fd_); } // Finish handling the incoming message by optionally sending back an ACK // message and removing this SocketReader. void FinishWithACK(const char* message, size_t length); private: void OnSocketCanReadWithoutBlocking(); void CleanupAndDeleteSelf() { DCHECK_CURRENTLY_ON(BrowserThread::IO); parent_->RemoveSocketReader(this); // We're deleted beyond this point. } // Controls watching |fd_|. std::unique_ptr<base::FileDescriptorWatcher::Controller> fd_watch_controller_; // The ProcessSingleton::LinuxWatcher that owns us. ProcessSingleton::LinuxWatcher* const parent_; // A reference to the UI task runner. scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner_; // The file descriptor we're reading. const int fd_; // Store the message in this buffer. char buf_[kMaxMessageLength]; // Tracks the number of bytes we've read in case we're getting partial // reads. size_t bytes_read_; base::OneShotTimer timer_; DISALLOW_COPY_AND_ASSIGN(SocketReader); }; // We expect to only be constructed on the UI thread. explicit LinuxWatcher(ProcessSingleton* parent) : ui_task_runner_(base::ThreadTaskRunnerHandle::Get()), parent_(parent) {} // Start listening for connections on the socket. This method should be // called from the IO thread. void StartListening(int socket); // This method determines if we should use the same process and if we should, // opens a new browser tab. This runs on the UI thread. // |reader| is for sending back ACK message. void HandleMessage(const std::string& current_dir, const std::vector<std::string>& argv, SocketReader* reader); private: friend struct BrowserThread::DeleteOnThread<BrowserThread::IO>; friend class base::DeleteHelper<ProcessSingleton::LinuxWatcher>; ~LinuxWatcher() { DCHECK_CURRENTLY_ON(BrowserThread::IO); } void OnSocketCanReadWithoutBlocking(int socket); // Removes and deletes the SocketReader. void RemoveSocketReader(SocketReader* reader); std::unique_ptr<base::FileDescriptorWatcher::Controller> socket_watcher_; // A reference to the UI message loop (i.e., the message loop we were // constructed on). scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner_; // The ProcessSingleton that owns us. ProcessSingleton* const parent_; std::set<std::unique_ptr<SocketReader>> readers_; DISALLOW_COPY_AND_ASSIGN(LinuxWatcher); }; void ProcessSingleton::LinuxWatcher::OnSocketCanReadWithoutBlocking( int socket) { DCHECK_CURRENTLY_ON(BrowserThread::IO); // Accepting incoming client. sockaddr_un from; socklen_t from_len = sizeof(from); int connection_socket = HANDLE_EINTR( accept(socket, reinterpret_cast<sockaddr*>(&from), &from_len)); if (-1 == connection_socket) { PLOG(ERROR) << "accept() failed"; return; } DCHECK(base::SetNonBlocking(connection_socket)) << "Failed to make non-blocking socket."; readers_.insert( std::make_unique<SocketReader>(this, ui_task_runner_, connection_socket)); } void ProcessSingleton::LinuxWatcher::StartListening(int socket) { DCHECK_CURRENTLY_ON(BrowserThread::IO); // Watch for client connections on this socket. socket_watcher_ = base::FileDescriptorWatcher::WatchReadable( socket, base::Bind(&LinuxWatcher::OnSocketCanReadWithoutBlocking, base::Unretained(this), socket)); } void ProcessSingleton::LinuxWatcher::HandleMessage( const std::string& current_dir, const std::vector<std::string>& argv, SocketReader* reader) { DCHECK(ui_task_runner_->BelongsToCurrentThread()); DCHECK(reader); if (parent_->notification_callback_.Run(argv, base::FilePath(current_dir))) { // Send back "ACK" message to prevent the client process from starting up. reader->FinishWithACK(kACKToken, arraysize(kACKToken) - 1); } else { LOG(WARNING) << "Not handling interprocess notification as browser" " is shutting down"; // Send back "SHUTDOWN" message, so that the client process can start up // without killing this process. reader->FinishWithACK(kShutdownToken, arraysize(kShutdownToken) - 1); return; } } void ProcessSingleton::LinuxWatcher::RemoveSocketReader(SocketReader* reader) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK(reader); auto it = std::find_if(readers_.begin(), readers_.end(), [reader](const std::unique_ptr<SocketReader>& ptr) { return ptr.get() == reader; }); readers_.erase(it); } /////////////////////////////////////////////////////////////////////////////// // ProcessSingleton::LinuxWatcher::SocketReader // void ProcessSingleton::LinuxWatcher::SocketReader:: OnSocketCanReadWithoutBlocking() { DCHECK_CURRENTLY_ON(BrowserThread::IO); while (bytes_read_ < sizeof(buf_)) { ssize_t rv = HANDLE_EINTR(read(fd_, buf_ + bytes_read_, sizeof(buf_) - bytes_read_)); if (rv < 0) { if (errno != EAGAIN && errno != EWOULDBLOCK) { PLOG(ERROR) << "read() failed"; CloseSocket(fd_); return; } else { // It would block, so we just return and continue to watch for the next // opportunity to read. return; } } else if (!rv) { // No more data to read. It's time to process the message. break; } else { bytes_read_ += rv; } } // Validate the message. The shortest message is kStartToken\0x\0x const size_t kMinMessageLength = arraysize(kStartToken) + 4; if (bytes_read_ < kMinMessageLength) { buf_[bytes_read_] = 0; LOG(ERROR) << "Invalid socket message (wrong length):" << buf_; CleanupAndDeleteSelf(); return; } std::string str(buf_, bytes_read_); std::vector<std::string> tokens = base::SplitString(str, std::string(1, kTokenDelimiter), base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); if (tokens.size() < 3 || tokens[0] != kStartToken) { LOG(ERROR) << "Wrong message format: " << str; CleanupAndDeleteSelf(); return; } // Stop the expiration timer to prevent this SocketReader object from being // terminated unexpectly. timer_.Stop(); std::string current_dir = tokens[1]; // Remove the first two tokens. The remaining tokens should be the command // line argv array. tokens.erase(tokens.begin()); tokens.erase(tokens.begin()); // Return to the UI thread to handle opening a new browser tab. ui_task_runner_->PostTask( FROM_HERE, base::Bind(&ProcessSingleton::LinuxWatcher::HandleMessage, parent_, current_dir, tokens, this)); fd_watch_controller_.reset(); // LinuxWatcher::HandleMessage() is in charge of destroying this SocketReader // object by invoking SocketReader::FinishWithACK(). } void ProcessSingleton::LinuxWatcher::SocketReader::FinishWithACK( const char* message, size_t length) { if (message && length) { // Not necessary to care about the return value. WriteToSocket(fd_, message, length); } if (shutdown(fd_, SHUT_WR) < 0) PLOG(ERROR) << "shutdown() failed"; base::PostTaskWithTraits( FROM_HERE, {BrowserThread::IO}, base::Bind(&ProcessSingleton::LinuxWatcher::RemoveSocketReader, parent_, this)); // We will be deleted once the posted RemoveSocketReader task runs. } /////////////////////////////////////////////////////////////////////////////// // ProcessSingleton // ProcessSingleton::ProcessSingleton( const base::FilePath& user_data_dir, const NotificationCallback& notification_callback) : notification_callback_(notification_callback), current_pid_(base::GetCurrentProcId()) { // The user_data_dir may have not been created yet. base::ThreadRestrictions::ScopedAllowIO allow_io; base::CreateDirectoryAndGetError(user_data_dir, nullptr); socket_path_ = user_data_dir.Append(kSingletonSocketFilename); lock_path_ = user_data_dir.Append(kSingletonLockFilename); cookie_path_ = user_data_dir.Append(kSingletonCookieFilename); kill_callback_ = base::Bind(&ProcessSingleton::KillProcess, base::Unretained(this)); } ProcessSingleton::~ProcessSingleton() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); // Manually free resources with IO explicitly allowed. base::ThreadRestrictions::ScopedAllowIO allow_io; watcher_ = nullptr; ignore_result(socket_dir_.Delete()); } ProcessSingleton::NotifyResult ProcessSingleton::NotifyOtherProcess() { return NotifyOtherProcessWithTimeout( *base::CommandLine::ForCurrentProcess(), kRetryAttempts, base::TimeDelta::FromSeconds(kTimeoutInSeconds), true); } ProcessSingleton::NotifyResult ProcessSingleton::NotifyOtherProcessWithTimeout( const base::CommandLine& cmd_line, int retry_attempts, const base::TimeDelta& timeout, bool kill_unresponsive) { DCHECK_GE(retry_attempts, 0); DCHECK_GE(timeout.InMicroseconds(), 0); base::TimeDelta sleep_interval = timeout / retry_attempts; ScopedSocket socket; for (int retries = 0; retries <= retry_attempts; ++retries) { // Try to connect to the socket. if (ConnectSocket(&socket, socket_path_, cookie_path_)) break; // If we're in a race with another process, they may be in Create() and have // created the lock but not attached to the socket. So we check if the // process with the pid from the lockfile is currently running and is a // chrome browser. If so, we loop and try again for |timeout|. std::string hostname; int pid; if (!ParseLockPath(lock_path_, &hostname, &pid)) { // No lockfile exists. return PROCESS_NONE; } if (hostname.empty()) { // Invalid lockfile. UnlinkPath(lock_path_); return PROCESS_NONE; } if (hostname != net::GetHostName() && !IsChromeProcess(pid)) { // Locked by process on another host. If the user selected to unlock // the profile, try to continue; otherwise quit. if (DisplayProfileInUseError(lock_path_, hostname, pid)) { UnlinkPath(lock_path_); return PROCESS_NONE; } return PROFILE_IN_USE; } if (!IsChromeProcess(pid)) { // Orphaned lockfile (no process with pid, or non-chrome process.) UnlinkPath(lock_path_); return PROCESS_NONE; } if (IsSameChromeInstance(pid)) { // Orphaned lockfile (pid is part of same chrome instance we are, even // though we haven't tried to create a lockfile yet). UnlinkPath(lock_path_); return PROCESS_NONE; } if (retries == retry_attempts) { // Retries failed. Kill the unresponsive chrome process and continue. if (!kill_unresponsive || !KillProcessByLockPath()) return PROFILE_IN_USE; return PROCESS_NONE; } base::PlatformThread::Sleep(sleep_interval); } timeval socket_timeout = TimeDeltaToTimeVal(timeout); setsockopt(socket.fd(), SOL_SOCKET, SO_SNDTIMEO, &socket_timeout, sizeof(socket_timeout)); // Found another process, prepare our command line // format is "START\0<current dir>\0<argv[0]>\0...\0<argv[n]>". std::string to_send(kStartToken); to_send.push_back(kTokenDelimiter); base::FilePath current_dir; if (!base::PathService::Get(base::DIR_CURRENT, &current_dir)) return PROCESS_NONE; to_send.append(current_dir.value()); const std::vector<std::string>& argv = atom::AtomCommandLine::argv(); for (std::vector<std::string>::const_iterator it = argv.begin(); it != argv.end(); ++it) { to_send.push_back(kTokenDelimiter); to_send.append(*it); } // Send the message if (!WriteToSocket(socket.fd(), to_send.data(), to_send.length())) { // Try to kill the other process, because it might have been dead. if (!kill_unresponsive || !KillProcessByLockPath()) return PROFILE_IN_USE; return PROCESS_NONE; } if (shutdown(socket.fd(), SHUT_WR) < 0) PLOG(ERROR) << "shutdown() failed"; // Read ACK message from the other process. It might be blocked for a certain // timeout, to make sure the other process has enough time to return ACK. char buf[kMaxACKMessageLength + 1]; ssize_t len = ReadFromSocket(socket.fd(), buf, kMaxACKMessageLength, timeout); // Failed to read ACK, the other process might have been frozen. if (len <= 0) { if (!kill_unresponsive || !KillProcessByLockPath()) return PROFILE_IN_USE; return PROCESS_NONE; } buf[len] = '\0'; if (strncmp(buf, kShutdownToken, arraysize(kShutdownToken) - 1) == 0) { // The other process is shutting down, it's safe to start a new process. return PROCESS_NONE; } else if (strncmp(buf, kACKToken, arraysize(kACKToken) - 1) == 0) { #if defined(TOOLKIT_VIEWS) && defined(OS_LINUX) && !defined(OS_CHROMEOS) // Likely NULL in unit tests. views::LinuxUI* linux_ui = views::LinuxUI::instance(); if (linux_ui) linux_ui->NotifyWindowManagerStartupComplete(); #endif // Assume the other process is handling the request. return PROCESS_NOTIFIED; } NOTREACHED() << "The other process returned unknown message: " << buf; return PROCESS_NOTIFIED; } ProcessSingleton::NotifyResult ProcessSingleton::NotifyOtherProcessOrCreate() { return NotifyOtherProcessWithTimeoutOrCreate( *base::CommandLine::ForCurrentProcess(), kRetryAttempts, base::TimeDelta::FromSeconds(kTimeoutInSeconds)); } void ProcessSingleton::StartListeningOnSocket() { watcher_ = new LinuxWatcher(this); base::PostTaskWithTraits( FROM_HERE, {BrowserThread::IO}, base::Bind(&ProcessSingleton::LinuxWatcher::StartListening, watcher_, sock_)); } void ProcessSingleton::OnBrowserReady() { if (listen_on_ready_) { StartListeningOnSocket(); listen_on_ready_ = false; } } ProcessSingleton::NotifyResult ProcessSingleton::NotifyOtherProcessWithTimeoutOrCreate( const base::CommandLine& command_line, int retry_attempts, const base::TimeDelta& timeout) { const base::TimeTicks begin_ticks = base::TimeTicks::Now(); NotifyResult result = NotifyOtherProcessWithTimeout( command_line, retry_attempts, timeout, true); if (result != PROCESS_NONE) { if (result == PROCESS_NOTIFIED) { UMA_HISTOGRAM_MEDIUM_TIMES("Chrome.ProcessSingleton.TimeToNotify", base::TimeTicks::Now() - begin_ticks); } else { UMA_HISTOGRAM_MEDIUM_TIMES("Chrome.ProcessSingleton.TimeToFailure", base::TimeTicks::Now() - begin_ticks); } return result; } if (Create()) { UMA_HISTOGRAM_MEDIUM_TIMES("Chrome.ProcessSingleton.TimeToCreate", base::TimeTicks::Now() - begin_ticks); return PROCESS_NONE; } // If the Create() failed, try again to notify. (It could be that another // instance was starting at the same time and managed to grab the lock before // we did.) // This time, we don't want to kill anything if we aren't successful, since we // aren't going to try to take over the lock ourselves. result = NotifyOtherProcessWithTimeout(command_line, retry_attempts, timeout, false); if (result == PROCESS_NOTIFIED) { UMA_HISTOGRAM_MEDIUM_TIMES("Chrome.ProcessSingleton.TimeToNotify", base::TimeTicks::Now() - begin_ticks); } else { UMA_HISTOGRAM_MEDIUM_TIMES("Chrome.ProcessSingleton.TimeToFailure", base::TimeTicks::Now() - begin_ticks); } if (result != PROCESS_NONE) return result; return LOCK_ERROR; } void ProcessSingleton::OverrideCurrentPidForTesting(base::ProcessId pid) { current_pid_ = pid; } void ProcessSingleton::OverrideKillCallbackForTesting( const base::Callback<void(int)>& callback) { kill_callback_ = callback; } void ProcessSingleton::DisablePromptForTesting() { g_disable_prompt = true; } bool ProcessSingleton::Create() { base::ThreadRestrictions::ScopedAllowIO allow_io; int sock; sockaddr_un addr; // The symlink lock is pointed to the hostname and process id, so other // processes can find it out. base::FilePath symlink_content(base::StringPrintf( "%s%c%u", net::GetHostName().c_str(), kLockDelimiter, current_pid_)); // Create symbol link before binding the socket, to ensure only one instance // can have the socket open. if (!SymlinkPath(symlink_content, lock_path_)) { // TODO(jackhou): Remove this case once this code is stable on Mac. // http://crbug.com/367612 #if defined(OS_MACOSX) // On Mac, an existing non-symlink lock file means the lock could be held by // the old process singleton code. If we can successfully replace the lock, // continue as normal. if (base::IsLink(lock_path_) || !ReplaceOldSingletonLock(symlink_content, lock_path_)) { return false; } #else // If we failed to create the lock, most likely another instance won the // startup race. return false; #endif } if (IsAppSandboxed()) { // For sandboxed applications, the tmp dir could be too long to fit // addr->sun_path, so we need to make it as short as possible. base::FilePath tmp_dir; if (!base::GetTempDir(&tmp_dir)) { LOG(ERROR) << "Failed to get temporary directory."; return false; } if (!socket_dir_.Set(tmp_dir.Append("S"))) { LOG(ERROR) << "Failed to set socket directory."; return false; } } else { // Create the socket file somewhere in /tmp which is usually mounted as a // normal filesystem. Some network filesystems (notably AFS) are screwy and // do not support Unix domain sockets. if (!socket_dir_.CreateUniqueTempDir()) { LOG(ERROR) << "Failed to create socket directory."; return false; } } // Check that the directory was created with the correct permissions. int dir_mode = 0; CHECK(base::GetPosixFilePermissions(socket_dir_.GetPath(), &dir_mode) && dir_mode == base::FILE_PERMISSION_USER_MASK) << "Temp directory mode is not 700: " << std::oct << dir_mode; // Setup the socket symlink and the two cookies. base::FilePath socket_target_path = socket_dir_.GetPath().Append(kSingletonSocketFilename); base::FilePath cookie(GenerateCookie()); base::FilePath remote_cookie_path = socket_dir_.GetPath().Append(kSingletonCookieFilename); UnlinkPath(socket_path_); UnlinkPath(cookie_path_); if (!SymlinkPath(socket_target_path, socket_path_) || !SymlinkPath(cookie, cookie_path_) || !SymlinkPath(cookie, remote_cookie_path)) { // We've already locked things, so we can't have lost the startup race, // but something doesn't like us. LOG(ERROR) << "Failed to create symlinks."; if (!socket_dir_.Delete()) LOG(ERROR) << "Encountered a problem when deleting socket directory."; return false; } SetupSocket(socket_target_path.value(), &sock, &addr); if (bind(sock, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) < 0) { PLOG(ERROR) << "Failed to bind() " << socket_target_path.value(); CloseSocket(sock); return false; } if (listen(sock, 5) < 0) NOTREACHED() << "listen failed: " << base::safe_strerror(errno); sock_ = sock; if (BrowserThread::IsThreadInitialized(BrowserThread::IO)) { StartListeningOnSocket(); } else { listen_on_ready_ = true; } return true; } void ProcessSingleton::Cleanup() { UnlinkPath(socket_path_); UnlinkPath(cookie_path_); UnlinkPath(lock_path_); } bool ProcessSingleton::IsSameChromeInstance(pid_t pid) { pid_t cur_pid = current_pid_; while (pid != cur_pid) { pid = base::GetParentProcessId(pid); if (pid < 0) return false; if (!IsChromeProcess(pid)) return false; } return true; } bool ProcessSingleton::KillProcessByLockPath() { std::string hostname; int pid; ParseLockPath(lock_path_, &hostname, &pid); if (!hostname.empty() && hostname != net::GetHostName()) { return DisplayProfileInUseError(lock_path_, hostname, pid); } UnlinkPath(lock_path_); if (IsSameChromeInstance(pid)) return true; if (pid > 0) { kill_callback_.Run(pid); return true; } LOG(ERROR) << "Failed to extract pid from path: " << lock_path_.value(); return true; } void ProcessSingleton::KillProcess(int pid) { // TODO(james.su@gmail.com): Is SIGKILL ok? int rv = kill(static_cast<base::ProcessHandle>(pid), SIGKILL); // ESRCH = No Such Process (can happen if the other process is already in // progress of shutting down and finishes before we try to kill it). DCHECK(rv == 0 || errno == ESRCH) << "Error killing process: " << base::safe_strerror(errno); }
#include "stdafx.h" #include "MainMenu.h" #include "UI/UIDialogWnd.h" #include "ui/UIMessageBoxEx.h" #include "../xr_IOConsole.h" #include "../IGame_Level.h" #include "../CameraManager.h" #include "xr_Level_controller.h" #include "ui\UITextureMaster.h" #include "ui\UIXmlInit.h" #include <dinput.h> #include "ui\UIBtnHint.h" #include "UICursor.h" extern CMainMenu* MainMenu() {return (CMainMenu*)g_pGamePersistent->m_pMainMenu; }; //---------------------------------------------------------------------------------- //---------------------------------------------------------------------------------- CMainMenu::CMainMenu () { m_Flags.zero (); m_startDialog = NULL; g_pGamePersistent->m_pMainMenu= this; if (Device.bReady) OnDeviceCreate(); ReadTextureInfo (); CUIXmlInit::InitColorDefs (); g_btnHint = xr_new<CUIButtonHint>(); m_pMessageBox = NULL; m_deactivated_frame = 0; } CMainMenu::~CMainMenu () { xr_delete (g_btnHint); xr_delete (m_startDialog); xr_delete (m_pMessageBox); g_pGamePersistent->m_pMainMenu = NULL; CUITextureMaster::WriteLog (); } void CMainMenu::ReadTextureInfo() { if (pSettings->section_exist("texture_desc")) { xr_string itemsList; string256 single_item; itemsList = pSettings->r_string("texture_desc", "files"); int itemsCount = _GetItemCount(itemsList.c_str()); for (int i = 0; i < itemsCount; i++) { _GetItem(itemsList.c_str(), i, single_item); strcat(single_item,".xml"); CUITextureMaster::ParseShTexInfo(single_item); } } } extern ENGINE_API BOOL bShowPauseString; extern bool IsGameTypeSingle(); void CMainMenu::Activate (bool bActivate) { if(!!m_Flags.test(flActive) == bActivate) return; bool b_is_single = IsGameTypeSingle(); if(bActivate) { Device.PauseSound (TRUE); m_Flags.set (flActive|flNeedChangeCapture,TRUE); //. if(!m_startDialog) { DLL_Pure* dlg = NEW_INSTANCE(TEXT2CLSID("MAIN_MNU")); if(!dlg) { m_Flags.set (flActive|flNeedChangeCapture,FALSE); return; } xr_delete (m_startDialog); m_startDialog = smart_cast<CUIDialogWnd*>(dlg); VERIFY (m_startDialog); } m_Flags.set (flRestoreConsole,Console->bVisible); if(b_is_single) m_Flags.set (flRestorePause,Device.Pause()); Console->Hide (); m_Flags.set (flRestoreCursor,GetUICursor()->IsVisible()); if(b_is_single) { m_Flags.set (flRestorePauseStr, bShowPauseString); bShowPauseString = FALSE; if(!m_Flags.test(flRestorePause)) Device.Pause (TRUE); } m_startDialog->m_bWorkInPause = true; StartStopMenu (m_startDialog,true); if(g_pGameLevel) { if(b_is_single) Device.seqFrame.Remove (g_pGameLevel); Device.seqRender.Remove (g_pGameLevel); CCameraManager::ResetPP (); }; Device.seqRender.Add (this, 4); // 1-console 2-cursor 3-tutorial }else{ m_deactivated_frame = Device.dwFrame; m_Flags.set (flActive, FALSE); m_Flags.set (flNeedChangeCapture, TRUE); Device.seqRender.Remove (this); bool b = !!Console->bVisible; if(b){ Console->Hide (); } IR_Release (); if(b){ Console->Show (); } StartStopMenu (m_startDialog,true); CleanInternals (); //. xr_delete (m_startDialog); if(g_pGameLevel) { if(b_is_single) Device.seqFrame.Add (g_pGameLevel); Device.seqRender.Add (g_pGameLevel); }; if(m_Flags.test(flRestoreConsole)) Console->Show (); if(b_is_single) { if(!m_Flags.test(flRestorePause)) Device.Pause (FALSE); bShowPauseString = m_Flags.test(flRestorePauseStr); } if(m_Flags.test(flRestoreCursor)) GetUICursor()->Show (); Device.PauseSound (FALSE); } } bool CMainMenu::IsActive() { return !!m_Flags.test(flActive); } //IInputReceiver static int mouse_button_2_key [] = {MOUSE_1,MOUSE_2,MOUSE_3}; void CMainMenu::IR_OnMousePress (int btn) { if(!IsActive()) return; IR_OnKeyboardPress(mouse_button_2_key[btn]); }; void CMainMenu::IR_OnMouseRelease(int btn) { if(!IsActive()) return; IR_OnKeyboardRelease(mouse_button_2_key[btn]); }; void CMainMenu::IR_OnMouseHold(int btn) { if(!IsActive()) return; IR_OnKeyboardHold(mouse_button_2_key[btn]); }; void CMainMenu::IR_OnMouseMove(int x, int y) { if(!IsActive()) return; if(MainInputReceiver()) MainInputReceiver()->IR_OnMouseMove(x, y); }; void CMainMenu::IR_OnMouseStop(int x, int y) { }; void CMainMenu::IR_OnKeyboardPress(int dik) { if(!IsActive()) return; if(key_binding[dik]== kCONSOLE) { Console->Show(); return; } if (DIK_F12 == dik){ Render->Screenshot(); return; } if(MainInputReceiver()) MainInputReceiver()->IR_OnKeyboardPress( dik); }; void CMainMenu::IR_OnKeyboardRelease (int dik) { if(!IsActive()) return; if(MainInputReceiver()) MainInputReceiver()->IR_OnKeyboardRelease(dik); }; void CMainMenu::IR_OnKeyboardHold (int dik) { }; void CMainMenu::IR_OnMouseWheel(int direction) { if(!IsActive()) return; if(MainInputReceiver()) MainInputReceiver()->IR_OnMouseWheel(direction); } bool CMainMenu::OnRenderPPUI_query() { return IsActive() && !m_Flags.test(flGameSaveScreenshot); } void CMainMenu::OnRender () { if(m_Flags.test(flGameSaveScreenshot)) return; Render->Render (); } void CMainMenu::OnRenderPPUI_main () { if(!IsActive()) return; if(m_Flags.test(flGameSaveScreenshot)) return; UI()->pp_start(); DoRenderDialogs(); UI()->RenderFont(); UI()->pp_stop(); } void CMainMenu::OnRenderPPUI_PP () { if ( !IsActive() ) return; UI()->pp_start(); xr_vector<CUIWindow*>::iterator it = m_pp_draw_wnds.begin(); for(; it!=m_pp_draw_wnds.end();++it) { (*it)->Draw(); } UI()->pp_stop(); } void CMainMenu::StartStopMenu(CUIDialogWnd* pDialog, bool bDoHideIndicators) { pDialog->m_bWorkInPause = true; CDialogHolder::StartStopMenu(pDialog, bDoHideIndicators); } //pureFrame void CMainMenu::OnFrame() { if(!IsActive() && m_startDialog) { //. xr_delete (m_startDialog); } if (m_Flags.test(flNeedChangeCapture)) { m_Flags.set (flNeedChangeCapture,FALSE); if (m_Flags.test(flActive)) IR_Capture(); else IR_Release(); } CDialogHolder::OnFrame (); //screenshot stuff if(m_Flags.test(flGameSaveScreenshot) && Device.dwFrame > m_screenshotFrame ) { m_Flags.set (flGameSaveScreenshot,FALSE); ::Render->Screenshot (IRender_interface::SM_FOR_GAMESAVE, m_screenshot_name); if(g_pGameLevel && m_Flags.test(flActive)) { Device.seqFrame.Remove (g_pGameLevel); Device.seqRender.Remove (g_pGameLevel); }; if(m_Flags.test(flRestoreConsole)) Console->Show (); } } void CMainMenu::OnDeviceCreate() { } void CMainMenu::Screenshot(IRender_interface::ScreenshotMode mode, LPCSTR name) { if(mode != IRender_interface::SM_FOR_GAMESAVE) { ::Render->Screenshot (mode,name); }else{ m_Flags.set (flGameSaveScreenshot, TRUE); strcpy(m_screenshot_name,name); if(g_pGameLevel && m_Flags.test(flActive)){ Device.seqFrame.Add (g_pGameLevel); Device.seqRender.Add (g_pGameLevel); }; m_screenshotFrame = Device.dwFrame+1; m_Flags.set (flRestoreConsole, Console->bVisible); Console->Hide (); } } void CMainMenu::RegisterPPDraw(CUIWindow* w) { UnregisterPPDraw (w); m_pp_draw_wnds.push_back (w); } void CMainMenu::UnregisterPPDraw (CUIWindow* w) { xr_vector<CUIWindow*>::iterator it = remove( m_pp_draw_wnds.begin(), m_pp_draw_wnds.end(), w); m_pp_draw_wnds.erase(it, m_pp_draw_wnds.end()); } void CMainMenu::OnInvalidHost() { if (!m_pMessageBox) { m_pMessageBox = xr_new<CUIMessageBoxEx>(); } m_pMessageBox->Init("message_box_invalid_host"); StartStopMenu(m_pMessageBox, false); } void CMainMenu::OnInvalidPass() { if (!m_pMessageBox) { m_pMessageBox = xr_new<CUIMessageBoxEx>(); } m_pMessageBox->Init("message_box_invalid_pass"); StartStopMenu(m_pMessageBox, false); } void CMainMenu::OnSessionFull() { if (!m_pMessageBox) { m_pMessageBox = xr_new<CUIMessageBoxEx>(); } m_pMessageBox->Init("message_box_session_full"); StartStopMenu(m_pMessageBox, false); } void CMainMenu::OnServerReject() { if (!m_pMessageBox) { m_pMessageBox = xr_new<CUIMessageBoxEx>(); } m_pMessageBox->Init("message_box_server_reject"); StartStopMenu(m_pMessageBox, false); } void CMainMenu::DestroyInternal() { if(m_startDialog && m_deactivated_frame < Device.dwFrame+4) xr_delete (m_startDialog); }
// ----------------- BEGIN LICENSE BLOCK --------------------------------- // // Copyright (c) 2018 Intel Corporation // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, // OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // ----------------- END LICENSE BLOCK ----------------------------------- /** * @file * */ #pragma once #include <limits> #include "rss/situation/Speed.hpp" /*! * @brief namespace rss */ namespace rss { /*! * @brief namespace situation */ namespace situation { struct Velocity { ::rss::situation::Speed speedLon{0.0}; ::rss::situation::Speed speedLat{0.0}; }; } // namespace situation } // namespace rss
// Copyright 2009-2018 NTESS. Under the terms // of Contract DE-NA0003525 with NTESS, the U.S. // Government retains certain rights in this software. // // Copyright (c) 2009-2018, NTESS // All rights reserved. // // Portions are copyright of other developers: // See the file CONTRIBUTORS.TXT in the top level directory // the distribution for more information. // // This file is part of the SST software package. For license // information, see the LICENSE file in the top level directory of the // distribution. #include "generator.h" void Generator::generateOutput(){ sc_out_.write(count); native_out_.write(count); count++; }
/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/xla/array2d.h" #include "tensorflow/compiler/xla/client/xla_builder.h" #include "tensorflow/compiler/xla/reference_util.h" #include "tensorflow/compiler/xla/shape_util.h" #include "tensorflow/compiler/xla/tests/client_library_test_base.h" #include "tensorflow/compiler/xla/tests/test_macros.h" // This test suite should be run with // --//third_party/tensorflow/compiler/xla/service/gpu:enable_bef_executable=true // to test the BEF-mode GpuExecutable. namespace xla { namespace gpu { XLA_TEST_F(ClientLibraryTestBase, GemmOnly) { Array2D<float> lhs({{1.0f, 2.0f}, {3.0f, 4.0f}}); Array2D<float> rhs({{10.0f, 11.0f}, {12.0f, 13.0f}}); auto prim_type = primitive_util::NativeToPrimitiveType<float>(); Shape lhs_shape = ShapeUtil::MakeShape(prim_type, {lhs.height(), lhs.width()}); Shape rhs_shape = ShapeUtil::MakeShape(prim_type, {rhs.height(), rhs.width()}); TF_ASSERT_OK_AND_ASSIGN(auto lhs_handle, client_->TransferToServer( LiteralUtil::CreateR2FromArray2DWithLayout<float>( lhs, LayoutUtil::MakeLayout({0, 1})))); TF_ASSERT_OK_AND_ASSIGN(auto rhs_handle, client_->TransferToServer( LiteralUtil::CreateR2FromArray2DWithLayout<float>( rhs, LayoutUtil::MakeLayout({0, 1})))); XlaBuilder builder(TestName()); auto lhs_arg = Parameter(&builder, 0, lhs_shape, "lhs"); auto rhs_arg = Parameter(&builder, 1, rhs_shape, "rhs"); Dot(lhs_arg, rhs_arg); Array2D<float> expected = Array2D<float>({{34.0f, 37.0f}, {78.0f, 85.0f}}); ComputeAndCompareR2<float>(&builder, expected, {lhs_handle.get(), rhs_handle.get()}, ErrorSpec(1e-6)); }; XLA_TEST_F(ClientLibraryTestBase, GemmBiasOnly) { execution_options_.mutable_debug_options()->add_xla_disable_hlo_passes( "layout-assignment"); execution_options_.mutable_debug_options()->add_xla_disable_hlo_passes( "tiling-assignment"); // Disable algebraic simplification because the pass may replace a dot // instruction with a layout-changing multiplication instruction. execution_options_.mutable_debug_options()->add_xla_disable_hlo_passes( "algsimp"); const int m = 1; const int k = 290; const int n = 130; auto dot_lhs_data = MakeLinspaceArray2D<Eigen::half>(0.0, 1.0, m, k); auto dot_rhs_data = MakeLinspaceArray2D<Eigen::half>(0.0, 1.0, k, n); auto addend_data = MakeLinspaceArray2D<Eigen::half>(0.0, 1.0, m, n); auto transfer_to_server = [&](const Array2D<Eigen::half>& data) -> std::unique_ptr<GlobalData> { Literal literal = LiteralUtil::CreateR2FromArray2DWithLayout( data, LayoutUtil::MakeLayout({1, 0})); return client_->TransferToServer(literal).ConsumeValueOrDie(); }; auto dot_lhs_handle = transfer_to_server(*dot_lhs_data); auto dot_rhs_handle = transfer_to_server(*dot_rhs_data); auto addend_handle = transfer_to_server(*addend_data); XlaBuilder builder(TestName()); auto prim_type = primitive_util::NativeToPrimitiveType<Eigen::half>(); auto result = Dot(Parameter(&builder, 0, ShapeUtil::MakeShapeWithLayout(prim_type, {m, k}, {1, 0}), "dot_lhs"), Parameter(&builder, 1, ShapeUtil::MakeShapeWithLayout(prim_type, {k, n}, {1, 0}), "dot_rhs")); result = Add(result, Parameter(&builder, 2, ShapeUtil::MakeShapeWithLayout(prim_type, {m, n}, {1, 0}), "addend")); std::unique_ptr<Array2D<Eigen::half>> expected = ReferenceUtil::ApplyElementwise2D( std::plus<Eigen::half>(), *ReferenceUtil::MatmulArray2D(*dot_lhs_data, *dot_rhs_data), *addend_data); std::vector<GlobalData*> args = {dot_lhs_handle.get(), dot_rhs_handle.get(), addend_handle.get()}; ComputeAndCompareR2<Eigen::half>(&builder, *expected, args, ErrorSpec(0.3, 7e-3)); } } // namespace gpu } // namespace xla
// // Created by phoenixflower on 9/6/21. // #ifndef LANDESSDEVCORE_ISSHAREDLOCK_HPP #define LANDESSDEVCORE_ISSHAREDLOCK_HPP namespace LD { namespace CT { template<typename T> constexpr bool IsSharedLock(LD::Type<T> ) noexcept { return false; } } } #endif //LANDESSDEVCORE_ISSHAREDLOCK_HPP
#include "BaseMedialMesh.h" #include "Commom\FileIO.h" #include "Commom\GeometryComputation.h" void BaseMedialMeshBuffer::copyMedialPointsToBuffer(qeal* buffer, int size) { if(size == 0) std::copy(medialPoints.buffer, medialPoints.buffer + medialPoints.span, buffer); else std::copy(medialPoints.buffer, medialPoints.buffer + size, buffer); } void BaseMedialMeshBuffer::copyBufferToMedialPoints(qeal* buffer, int size) { if (size == 0) std::copy(buffer, buffer + medialPoints.span, medialPoints.buffer); else std::copy(buffer, buffer + size, medialPoints.buffer); } void BaseMedialMeshBuffer::copyMedialRadiusToBuffer(qeal * buffer, int size) { if (size == 0) std::copy(medialRadius.buffer, medialRadius.buffer + medialRadius.span, buffer); else std::copy(medialRadius.buffer, medialRadius.buffer + size, buffer); } void BaseMedialMeshBuffer::copyBufferToMedialRadius(qeal * buffer, int size) { if (size == 0) std::copy(buffer, buffer + medialRadius.span, medialRadius.buffer); else std::copy(buffer, buffer + size, medialRadius.buffer); } Vector3 BaseMedialMeshBuffer::getMedialPoint(int nid) { return Vector3(medialPoints.buffer[3 * nid], medialPoints.buffer[3 * nid + 1], medialPoints.buffer[3 * nid + 2]); } void BaseMedialMeshBuffer::setMedialPoint(int nid, qeal* p) { medialPoints.buffer[3 * nid] = p[0]; medialPoints.buffer[3 * nid + 1] = p[1]; medialPoints.buffer[3 * nid + 2] = p[2]; } qeal BaseMedialMeshBuffer::getMedialRadius(int nid) { return medialRadius.buffer[nid]; } void BaseMedialMeshBuffer::setMedialRadius(int nid, qeal& r) { medialRadius.buffer[nid] = r; } Vector3i BaseMedialMeshBuffer::getMedialPrimitive(int pid) { return Vector3i(medialPrimitives.buffer[3 * pid], medialPrimitives.buffer[3 * pid + 1], medialPrimitives.buffer[3 * pid + 2]); } Vector2i BaseMedialMeshBuffer::getMedialCone(int cid) { int pid = cid; return Vector2i(medialPrimitives.buffer[3 * pid], medialPrimitives.buffer[3 * pid + 1]); } Vector3i BaseMedialMeshBuffer::getMedialSlab(int sid) { int pid = sid + medialConesNum; return Vector3i(medialPrimitives.buffer[3 * pid], medialPrimitives.buffer[3 * pid + 1], medialPrimitives.buffer[3 * pid + 2]); } int BaseMedialMeshBuffer::getMedialPointOverallId(int id) { return id + medialPointIdOffset; } int BaseMedialMeshBuffer::getMedialPrimitiveOverallId(int pid) { return pid + medialPrimitiveIdOffset; } bool BaseMedialMesh::readMeshFromMatFormat(const std::string filename, BaseMedialMeshBufferPool * pool) { std::string dir, name, format; getFilenameInfo(filename, dir, name, format); if (format == std::string("mat")) { std::ifstream fin(filename.c_str()); if (!fin.is_open()) return false; std::string line; std::stringstream sstream; int pointsNum, conesNum, slabsNum; std::getline(fin, line); sstream << line; sstream >> pointsNum >> conesNum >> slabsNum; std::vector<qeal> points(3 * pointsNum); std::vector<qeal> radius(pointsNum); int primitivesNum = conesNum + slabsNum; medialPointsNum = pointsNum; medialConesNum = conesNum; medialSlabsNum = slabsNum; medialPrimitivesNum = primitivesNum; std::vector<int> primitives(3 * (conesNum + slabsNum)); std::vector<std::vector<int>> medialPointsNeighborList(pointsNum); std::vector<std::vector<int>> medialPointsCones(pointsNum); std::vector<std::vector<int>> medialPointsSlabs(pointsNum); bindedTM.resize(pointsNum, -1); setBindedTetMesh(true); for (size_t i = 0; i < pointsNum; i++) { sstream.clear(); std::getline(fin, line); char ch; qeal x, y, z, r; int b; sstream << line; sstream >> ch >> x >> y >> z >> r >> b; assert(ch == 'v'); points.data()[3 * i + 0] = x; points.data()[3 * i + 1] = y; points.data()[3 * i + 2] = z; radius.data()[i] = r; bindedTM[i] = b; if(b < 0) setBindedTetMesh(false); } for (size_t i = 0; i < conesNum; i++) { sstream.clear(); std::getline(fin, line); char ch; int x, y; sstream << line; sstream >> ch >> x >> y; assert(ch == 'c'); primitives[3 * i + 0] = x; primitives[3 * i + 1] = y; if (radius[x] < radius[y]) { primitives[3 * i + 0] = y; primitives[3 * i + 1] = x; } primitives[3 * i + 2] = -1; medialPointsCones[x].push_back(i); medialPointsCones[y].push_back(i); medialPointsNeighborList[x].push_back(y); medialPointsNeighborList[y].push_back(x); } for (size_t i = 0; i < slabsNum; i++) { sstream.clear(); std::getline(fin, line); char ch; int x, y, z; sstream << line; sstream >> ch >> x >> y >> z; assert(ch == 's'); int max = x, mid = y, min = z; qeal maxr = radius[x]; qeal midr = radius[y]; qeal minr = radius[z]; if (maxr < midr) { qeal tempr = maxr; maxr = midr; midr = tempr; int temp = max; max = mid; mid = temp; } if (maxr < minr) { qeal tempr = maxr; maxr = minr; minr = tempr; int temp = max; max = min; min = temp; } if (midr < minr) { qeal tempr = midr; midr = minr; minr = tempr; int temp = mid; mid = min; min = temp; } primitives[3 * (i + conesNum) + 0] = max; primitives[3 * (i + conesNum) + 1] = mid; primitives[3 * (i + conesNum) + 2] = min; medialPointsSlabs[x].push_back(i); medialPointsSlabs[y].push_back(i); medialPointsSlabs[z].push_back(i); medialPointsNeighborList[x].push_back(y); medialPointsNeighborList[x].push_back(z); medialPointsNeighborList[y].push_back(x); medialPointsNeighborList[y].push_back(z); medialPointsNeighborList[z].push_back(x); medialPointsNeighborList[z].push_back(y); } sstream.clear(); fin.close(); for (size_t i = 0; i < pointsNum; i++) { std::sort(medialPointsNeighborList[i].begin(), medialPointsNeighborList[i].end()); medialPointsNeighborList[i].erase(std::unique(medialPointsNeighborList[i].begin(), medialPointsNeighborList[i].end()), medialPointsNeighborList[i].end()); } registerToOverallBuffer<qeal>(points, pool->medialPointsBuffer, this->medialPoints); registerToOverallBuffer<qeal>(radius, pool->medialRadiusBuffer, this->medialRadius); pool->totalMedialPoinsNum += pointsNum; registerToOverallBuffer<int>(primitives, pool->medialPrimitiveIndicesBuffer, this->medialPrimitives); pool->totalMedialConesNum += conesNum; pool->totalMedialSlabsNum += slabsNum; pool->totalMedialPrimitivesNum += primitivesNum; registerToOverallBuffer<int>(medialPointsNeighborList, pool->medialPointsNeighborListBuffer, this->medialPointsNeighborList); registerToOverallBuffer<int>(medialPointsCones, pool->medialPointsConesBuffer, this->medialPointsCones); registerToOverallBuffer<int>(medialPointsCones, pool->medialPointsSlabsBuffer, this->medialPointsSlabs); _valid = true; } else if (format == std::string("ma")) { std::ifstream fin(filename.c_str()); if (!fin.is_open()) return false; std::string line; std::stringstream sstream; int pointsNum, edgesNum, facesNum; std::getline(fin, line); sstream << line; sstream >> pointsNum >> edgesNum >> facesNum; std::vector<qeal> points(3 * pointsNum); std::vector<qeal> radius(pointsNum); medialPointsNum = pointsNum; for (size_t i = 0; i < pointsNum; i++) { sstream.clear(); std::getline(fin, line); char ch; qeal x, y, z, r; sstream << line; sstream >> ch >> x >> y >> z >> r; assert(ch == 'v'); points.data()[3 * i + 0] = x; points.data()[3 * i + 1] = y; points.data()[3 * i + 2] = z; radius.data()[i] = r; } bindedTM.resize(pointsNum, -1); setBindedTetMesh(false); std::vector<std::pair<bool, Vector2i>> edgeIndices(edgesNum); for (size_t i = 0; i < edgesNum; i++) { sstream.clear(); std::getline(fin, line); char ch; int x, y; sstream << line; sstream >> ch >> x >> y; assert(ch == 'e'); if (radius[x] >= radius[y]) edgeIndices[i] = std::pair<bool, Vector2i>(true, Vector2i(x, y)); else edgeIndices[i] = std::pair<bool, Vector2i>(true, Vector2i(y, x)); } std::vector<int> faceIndices(3 * facesNum); for (size_t i = 0; i < facesNum; i++) { sstream.clear(); std::getline(fin, line); char ch; int x, y, z; sstream << line; sstream >> ch >> x >> y >> z; assert(ch == 'f'); faceIndices[3 * i + 0] = x; faceIndices[3 * i + 1] = y; faceIndices[3 * i + 2] = z; std::vector<std::pair<bool, Vector2i>>::iterator it; it = std::find(edgeIndices.begin(), edgeIndices.end(), std::pair<bool, Vector2i>(true, Vector2i(x, y))); if (it != edgeIndices.end()) it->first = false; it = std::find(edgeIndices.begin(), edgeIndices.end(), std::pair<bool, Vector2i>(true, Vector2i(y, x))); if (it != edgeIndices.end()) it->first = false; it = std::find(edgeIndices.begin(), edgeIndices.end(), std::pair<bool, Vector2i>(true, Vector2i(x, z))); if (it != edgeIndices.end()) it->first = false; it = std::find(edgeIndices.begin(), edgeIndices.end(), std::pair<bool, Vector2i>(true, Vector2i(z, x))); if (it != edgeIndices.end()) it->first = false; it = std::find(edgeIndices.begin(), edgeIndices.end(), std::pair<bool, Vector2i>(true, Vector2i(y, z))); if (it != edgeIndices.end()) it->first = false; it = std::find(edgeIndices.begin(), edgeIndices.end(), std::pair<bool, Vector2i>(true, Vector2i(z, y))); if (it != edgeIndices.end()) it->first = false; } medialConesNum = 0; std::vector<int> primitives; std::vector<std::vector<int>> medialPointsNeighborList(pointsNum); std::vector<std::vector<int>> medialPointsCones(pointsNum); std::vector<std::vector<int>> medialPointsSlabs(pointsNum); for (size_t i = 0; i < edgesNum; i++) { if (edgeIndices[i].first) { int x = edgeIndices[i].second.data()[0]; int y = edgeIndices[i].second.data()[1]; primitives.push_back(x); primitives.push_back(y); primitives.push_back(-1); medialPointsCones[x].push_back(medialConesNum); medialPointsCones[y].push_back(medialConesNum); medialConesNum++; medialPointsNeighborList[x].push_back(y); medialPointsNeighborList[y].push_back(x); } } medialSlabsNum = facesNum; for (size_t i = 0; i < facesNum; i++) { int x = faceIndices[3 * i + 0]; int y = faceIndices[3 * i + 1]; int z = faceIndices[3 * i + 2]; int max = x, mid = y, min = z; qeal maxr = radius[x]; qeal midr = radius[y]; qeal minr = radius[z]; if (maxr < midr) { qeal tempr = maxr; maxr = midr; midr = tempr; int temp = max; max = mid; mid = temp; } if (maxr < minr) { qeal tempr = maxr; maxr = minr; minr = tempr; int temp = max; max = min; min = temp; } if (midr < minr) { qeal tempr = midr; midr = minr; minr = tempr; int temp = mid; mid = min; min = temp; } primitives.push_back(max); primitives.push_back(mid); primitives.push_back(min); medialPointsSlabs[x].push_back(i); medialPointsSlabs[y].push_back(i); medialPointsSlabs[x].push_back(i); medialPointsNeighborList[x].push_back(y); medialPointsNeighborList[x].push_back(z); medialPointsNeighborList[y].push_back(x); medialPointsNeighborList[y].push_back(z); medialPointsNeighborList[z].push_back(x); medialPointsNeighborList[z].push_back(y); } medialPrimitivesNum = medialConesNum + medialSlabsNum; sstream.clear(); fin.close(); for (size_t i = 0; i < pointsNum; i++) { std::sort(medialPointsNeighborList[i].begin(), medialPointsNeighborList[i].end()); medialPointsNeighborList[i].erase(std::unique(medialPointsNeighborList[i].begin(), medialPointsNeighborList[i].end()), medialPointsNeighborList[i].end()); } registerToOverallBuffer<qeal>(points, pool->medialPointsBuffer, this->medialPoints); registerToOverallBuffer<qeal>(radius, pool->medialRadiusBuffer, this->medialRadius); pool->totalMedialPoinsNum += pointsNum; registerToOverallBuffer<int>(primitives, pool->medialPrimitiveIndicesBuffer, this->medialPrimitives); pool->totalMedialConesNum += medialConesNum; pool->totalMedialSlabsNum += medialSlabsNum; pool->totalMedialPrimitivesNum += medialPrimitivesNum; registerToOverallBuffer<int>(medialPointsNeighborList, pool->medialPointsNeighborListBuffer, this->medialPointsNeighborList); registerToOverallBuffer<int>(medialPointsCones, pool->medialPointsConesBuffer, this->medialPointsCones); registerToOverallBuffer<int>(medialPointsSlabs, pool->medialPointsSlabsBuffer, this->medialPointsSlabs); _valid = writeMeshToMatFormat(dir + name + ".mat"); } medialPointIdOffset = medialPoints.offset / 3; medialPrimitiveIdOffset = medialPrimitives.offset / 3; faceList.resize(medialSlabsNum); for (int i = 0; i < medialSlabsNum; i++) { Vector3i face = getMedialSlab(i); faceList[i] = face; } std::set<Vector2i> edgeSet; for (int i = 0; i < medialConesNum; i++) { Vector2i edge = getMedialCone(i); bool has = false; for (int j = 0; j < edgeList.size(); j++) { if ((edgeList[j][0] == edge[0] && edgeList[j][1] == edge[1]) || (edgeList[j][1] == edge[0] && edgeList[j][0] == edge[1])) { has = true; break; } } if(!has) edgeList.push_back(edge); } for (int i = 0; i < medialSlabsNum; i++) { Vector3i face = getMedialSlab(i); Vector2i edge[3]; edge[0] = Vector2i(face[0], face[1]); edge[1] = Vector2i(face[0], face[2]); edge[2] = Vector2i(face[1], face[2]); for (int k = 0; k < 3; k++) { bool has = false; for (int j = 0; j < edgeList.size(); j++) { if ((edgeList[j][0] == edge[k][0] && edgeList[j][1] == edge[k][1]) || (edgeList[j][1] == edge[k][0] && edgeList[j][0] == edge[k][1])) { has = true; break; } } if (!has)edgeList.push_back(edge[k]); } } return _valid; } bool BaseMedialMesh::writeMeshToMatFormat(const std::string filename) { std::string dir, name, format; getFilenameInfo(filename, dir, name, format); if (format == std::string("mat") || format == std::string("ma")) { std::ofstream fout(filename.c_str()); fout << medialPointsNum << " " << medialConesNum << " " << medialSlabsNum << std::endl; for (size_t i = 0; i < medialPointsNum; i++) { fout << "v"; for (size_t j = 0; j < 3; j++) fout << " " << medialPoints.buffer[3 * i + j]; fout << " " << medialRadius.buffer[i]; fout << " " << bindedTM[i]; fout << std::endl; } for (size_t i = 0; i < medialConesNum; i++) { Vector2i cone = getMedialCone(i); fout << "c " << cone.data()[0] <<" " << cone.data()[1] << std::endl; } for (size_t i = 0; i < medialSlabsNum; i++) { Vector3i slab = getMedialSlab(i); fout << "s " << slab.data()[0] << " " << slab.data()[1] <<" " << slab.data()[2] << std::endl; } fout.close(); return true; } return false; } void BaseMedialMesh::uniform(const qeal div) { for (int i = 0; i < medialPointsNum; i++) { medialPoints.buffer[3 * i] /= div; medialPoints.buffer[3 * i + 1] /= div; medialPoints.buffer[3 * i + 2] /= div; medialRadius.buffer[i] /= div; } } void BaseMedialMesh::translateMesh(const qeal x, const qeal y, const qeal z) { for (int i = 0; i < medialPointsNum; i++) { medialPoints.buffer[3 * i] += x; medialPoints.buffer[3 * i + 1] += y; medialPoints.buffer[3 * i + 2] += z; } } void BaseMedialMesh::scaleMesh(qeal s, const qeal cx, const qeal cy, const qeal cz) { for (int i = 0; i < medialPointsNum; i++) { medialPoints.buffer[3 * i] = (medialPoints.buffer[3 * i] - cx) * s + cx; medialPoints.buffer[3 * i + 1] = (medialPoints.buffer[3 * i + 1] - cy) * s + cy; medialPoints.buffer[3 * i + 2] = (medialPoints.buffer[3 * i + 2] - cz) * s + cz; medialRadius.buffer[i] *= s; } } void BaseMedialMesh::rotateMesh(const qglviewer::Quaternion oldR, const qglviewer::Quaternion R, const qeal cx, const qeal cy, const qeal cz) { for (int i = 0; i < medialPointsNum; i++) { qglviewer::Vec pos(medialPoints.buffer[3 * i] - cx, medialPoints.buffer[3 * i + 1] - cy, medialPoints.buffer[3 * i + 2] - cz); pos = oldR.inverseRotate(pos); pos = R.rotate(pos); medialPoints.buffer[3 * i] = pos.x + cx; medialPoints.buffer[3 * i + 1] = pos.y + cy; medialPoints.buffer[3 * i + 2] = pos.z + cz; } } void BaseMedialMesh::encloseObject(qeal * objPos, int dim) { int num = dim / 3; std::vector<qeal> dr(medialPointsNum, 0); for (int i = 0; i < num; i++) { Vector3 p = Vector3(objPos[3 * i], objPos[3 * i + 1], objPos[3 * i + 2]); qeal pr = 0.0; qeal minDist = QEAL_MAX; int minPrimitiveId = -1; for (int c = 0; c < medialConesNum; c++) { Vector2i cone = getMedialCone(c); Vector3 c11 = getMedialPoint(cone[0]); Vector3 c12 = getMedialPoint(cone[1]); qeal r11 = getMedialRadius(cone[0]); qeal r12 = getMedialRadius(cone[1]); qeal t, dist; getNearestSphereOnMedialCone(p, pr, c11, r11, c12, r12, t, dist); if (dist < minDist) { minDist = dist; minPrimitiveId = c; } } for (int s = 0; s < medialSlabsNum; s++) { Vector3i slab = getMedialSlab(s); Vector3 c11 = getMedialPoint(slab[0]); Vector3 c12 = getMedialPoint(slab[1]); Vector3 c13 = getMedialPoint(slab[2]); qeal r11 = getMedialRadius(slab[0]); qeal r12 = getMedialRadius(slab[1]); qeal r13 = getMedialRadius(slab[2]); qeal t0, t1, dist; getNearestSphereOnMedialSlab(p, pr, c11, r11, c12, r12, c13, r13, t0, t1, dist); if (dist < minDist) { minDist = dist; minPrimitiveId = medialConesNum + s; } } if (minDist <= 0) continue; Vector3i primitive = getMedialPrimitive(minPrimitiveId); for (int j = 0; j < 3; j++) { int mi = primitive[j]; if (mi == -1) continue; qeal r = minDist * 1.00005; if (dr[mi] < r) dr[mi] = r; } } for (int i = 0; i < medialPointsNum; i++) { qeal r = getMedialRadius(i) + dr[i]; setMedialRadius(i, r); } }
/* +----------------------------------------------------------------------+ | Swoole | +----------------------------------------------------------------------+ | This source file is subject to version 2.0 of the Apache license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.apache.org/licenses/LICENSE-2.0.html | | If you did not receive a copy of the Apache2.0 license and are unable| | to obtain it through the world-wide-web, please send a note to | | license@swoole.com so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Tianfeng Han <mikan.tenny@gmail.com> | +----------------------------------------------------------------------+ */ #include "php_swoole_http_server.h" #ifdef SW_USE_HTTP2 #include "swoole_static_handler.h" #include "main/php_variables.h" using namespace swoole; using std::string; using swoole::coroutine::System; using swoole::http_server::StaticHandler; namespace Http2 = swoole::http2; using HttpContext = swoole::http::Context; using Http2Stream = Http2::Stream; using Http2Session = Http2::Session; static std::unordered_map<SessionId, Http2Session *> http2_sessions; extern String *swoole_http_buffer; static bool swoole_http2_server_respond(HttpContext *ctx, String *body); Http2Stream::Stream(Http2Session *client, uint32_t _id) { ctx = swoole_http_context_new(client->fd); ctx->copy(client->default_ctx); ctx->http2 = true; ctx->stream = this; ctx->keepalive = true; id = _id; send_window = SW_HTTP2_DEFAULT_WINDOW_SIZE; recv_window = SW_HTTP2_DEFAULT_WINDOW_SIZE; } Http2Stream::~Stream() { ctx->stream = nullptr; ctx->end_ = true; ctx->free(); } void Http2Stream::reset(uint32_t error_code) { char frame[SW_HTTP2_FRAME_HEADER_SIZE + SW_HTTP2_RST_STREAM_SIZE]; swoole_trace_log(SW_TRACE_HTTP2, "send [" SW_ECHO_YELLOW "] stream_id=%u, error_code=%u", "RST_STREAM", id, error_code); *(uint32_t *) ((char *) frame + SW_HTTP2_FRAME_HEADER_SIZE) = htonl(error_code); http2::set_frame_header(frame, SW_HTTP2_TYPE_RST_STREAM, SW_HTTP2_RST_STREAM_SIZE, 0, id); ctx->send(ctx, frame, SW_HTTP2_FRAME_HEADER_SIZE + SW_HTTP2_RST_STREAM_SIZE); } Http2Session::Session(SessionId _fd) { fd = _fd; header_table_size = SW_HTTP2_DEFAULT_HEADER_TABLE_SIZE; send_window = SW_HTTP2_DEFAULT_WINDOW_SIZE; recv_window = SW_HTTP2_DEFAULT_WINDOW_SIZE; max_concurrent_streams = SW_HTTP2_MAX_MAX_CONCURRENT_STREAMS; max_frame_size = SW_HTTP2_MAX_MAX_FRAME_SIZE; last_stream_id = 0; shutting_down = false; is_coro = false; http2_sessions[_fd] = this; } Http2Session::~Session() { for (auto iter = streams.begin(); iter != streams.end(); iter++) { delete iter->second; } if (inflater) { nghttp2_hd_inflate_del(inflater); } if (deflater) { nghttp2_hd_deflate_del(deflater); } if (default_ctx) { delete default_ctx; } http2_sessions.erase(fd); } static void http2_server_send_window_update(HttpContext *ctx, uint32_t stream_id, uint32_t size) { char frame[SW_HTTP2_FRAME_HEADER_SIZE + SW_HTTP2_WINDOW_UPDATE_SIZE]; swoole_trace_log(SW_TRACE_HTTP2, "send [" SW_ECHO_YELLOW "] stream_id=%u, size=%u", "WINDOW_UPDATE", stream_id, size); *(uint32_t *) ((char *) frame + SW_HTTP2_FRAME_HEADER_SIZE) = htonl(size); Http2::set_frame_header(frame, SW_HTTP2_TYPE_WINDOW_UPDATE, SW_HTTP2_WINDOW_UPDATE_SIZE, 0, stream_id); ctx->send(ctx, frame, SW_HTTP2_FRAME_HEADER_SIZE + SW_HTTP2_WINDOW_UPDATE_SIZE); } static ssize_t http2_build_trailer(HttpContext *ctx, uchar *buffer) { zval *ztrailer = sw_zend_read_property_ex(swoole_http_response_ce, ctx->response.zobject, SW_ZSTR_KNOWN(SW_ZEND_STR_TRAILER), 0); uint32_t size = php_swoole_array_length_safe(ztrailer); if (size > 0) { Http2::HeaderSet trailer(size); zend_string *key; zval *zvalue; ZEND_HASH_FOREACH_STR_KEY_VAL(Z_ARRVAL_P(ztrailer), key, zvalue) { if (UNEXPECTED(!key || ZVAL_IS_NULL(zvalue))) { continue; } zend::String str_value(zvalue); trailer.add(ZSTR_VAL(key), ZSTR_LEN(key), str_value.val(), str_value.len()); } ZEND_HASH_FOREACH_END(); ssize_t rv; size_t buflen; Http2Session *client = http2_sessions[ctx->fd]; nghttp2_hd_deflater *deflater = client->deflater; if (!deflater) { int ret = nghttp2_hd_deflate_new2(&deflater, SW_HTTP2_DEFAULT_HEADER_TABLE_SIZE, php_nghttp2_mem()); if (ret != 0) { swoole_warning("nghttp2_hd_deflate_new2() failed with error: %s", nghttp2_strerror(ret)); return -1; } client->deflater = deflater; } buflen = nghttp2_hd_deflate_bound(deflater, trailer.get(), trailer.len()); /* if (buflen > SW_HTTP2_DEFAULT_MAX_HEADER_LIST_SIZE) { php_swoole_error(E_WARNING, "header cannot bigger than remote max_header_list_size %u", SW_HTTP2_DEFAULT_MAX_HEADER_LIST_SIZE); return -1; } */ rv = nghttp2_hd_deflate_hd(deflater, (uchar *) buffer, buflen, trailer.get(), trailer.len()); if (rv < 0) { swoole_warning("nghttp2_hd_deflate_hd() failed with error: %s", nghttp2_strerror((int) rv)); return -1; } return rv; } return 0; } static bool swoole_http2_is_static_file(Server *serv, HttpContext *ctx) { zval *zserver = ctx->request.zserver; zval *zrequest_uri = zend_hash_str_find(Z_ARR_P(zserver), ZEND_STRL("request_uri")); if (zrequest_uri && Z_TYPE_P(zrequest_uri) == IS_STRING) { StaticHandler handler(serv, Z_STRVAL_P(zrequest_uri), Z_STRLEN_P(zrequest_uri)); if (!handler.hit()) { return false; } if (handler.status_code == SW_HTTP_NOT_FOUND) { String null_body = {}; ctx->response.status = SW_HTTP_NOT_FOUND; swoole_http2_server_respond(ctx, &null_body); return true; } auto date_str = handler.get_date(); auto date_str_last_modified = handler.get_date_last_modified(); zval *zheader = ctx->request.zserver; ctx->set_header(ZEND_STRL("Last-Modified"), date_str.c_str(), date_str.length(), 0); zval *zdate_if_modified_since = zend_hash_str_find(Z_ARR_P(zheader), ZEND_STRL("if-modified-since")); if (zdate_if_modified_since) { string date_if_modified_since(Z_STRVAL_P(zdate_if_modified_since), Z_STRLEN_P(zdate_if_modified_since)); if (!date_if_modified_since.empty() && handler.is_modified(date_if_modified_since)) { ctx->response.status = SW_HTTP_NOT_MODIFIED; return true; } } zend::String _filename(handler.get_filename_std_string()); zval zfilename; ZVAL_STR(&zfilename, _filename.get()); zval retval; /* do not care the retval (the connection will be closed if failed) */ sw_zend_call_method_with_1_params( ctx->response.zobject, swoole_http_response_ce, nullptr, "sendfile", &retval, &zfilename); return true; } return false; } static void swoole_http2_onRequest(Http2Session *client, Http2Stream *stream) { HttpContext *ctx = stream->ctx; zval *zserver = ctx->request.zserver; Server *serv = (Server *) ctx->private_data; Connection *conn = serv->get_connection_by_session_id(ctx->fd); int server_fd = conn->server_fd; Connection *serv_sock = serv->get_connection(server_fd); ctx->request.version = SW_HTTP_OK; if (serv->enable_static_handler && swoole_http2_is_static_file(serv, ctx)) { zval_ptr_dtor(ctx->request.zobject); zval_ptr_dtor(ctx->response.zobject); return; } add_assoc_long(zserver, "request_time", time(nullptr)); add_assoc_double(zserver, "request_time_float", microtime()); if (serv_sock) { add_assoc_long(zserver, "server_port", serv_sock->info.get_port()); } add_assoc_long(zserver, "remote_port", conn->info.get_port()); add_assoc_string(zserver, "remote_addr", (char *) conn->info.get_ip()); add_assoc_long(zserver, "master_time", conn->last_recv_time); add_assoc_string(zserver, "server_protocol", (char *) "HTTP/2"); zend_fcall_info_cache *fci_cache = php_swoole_server_get_fci_cache(serv, server_fd, SW_SERVER_CB_onRequest); zval args[2] = {*ctx->request.zobject, *ctx->response.zobject}; if (UNEXPECTED(!zend::function::call(fci_cache, 2, args, nullptr, serv->is_enable_coroutine()))) { stream->reset(SW_HTTP2_ERROR_INTERNAL_ERROR); php_swoole_error(E_WARNING, "%s->onRequest[v2] handler error", ZSTR_VAL(swoole_http_server_ce->name)); } zval_ptr_dtor(&args[0]); zval_ptr_dtor(&args[1]); } static ssize_t http2_build_header(HttpContext *ctx, uchar *buffer, size_t body_length) { zval *zheader = sw_zend_read_property_ex(swoole_http_response_ce, ctx->response.zobject, SW_ZSTR_KNOWN(SW_ZEND_STR_HEADER), 0); zval *zcookie = sw_zend_read_property_ex(swoole_http_response_ce, ctx->response.zobject, SW_ZSTR_KNOWN(SW_ZEND_STR_COOKIE), 0); Http2::HeaderSet headers(32 + php_swoole_array_length_safe(zheader) + php_swoole_array_length_safe(zcookie)); char *date_str = nullptr; char intbuf[2][16]; int ret; assert(ctx->send_header_ == 0); // status code if (ctx->response.status == 0) { ctx->response.status = SW_HTTP_OK; } ret = swoole_itoa(intbuf[0], ctx->response.status); headers.add(ZEND_STRL(":status"), intbuf[0], ret); uint32_t header_flags = 0x0; // headers if (ZVAL_IS_ARRAY(zheader)) { const char *key; uint32_t keylen; zval *zvalue; int type; auto add_header = [](Http2::HeaderSet &headers, const char *key, size_t l_key, zval *value, uint32_t &header_flags) { if (ZVAL_IS_NULL(value)) { return; } zend::String str_value(value); str_value.rtrim(); if (swoole_http_has_crlf(str_value.val(), str_value.len())) { return; } if (SW_STREQ(key, l_key, "server")) { header_flags |= HTTP_HEADER_SERVER; } else if (SW_STREQ(key, l_key, "content-length")) { return; // ignore } else if (SW_STREQ(key, l_key, "date")) { header_flags |= HTTP_HEADER_DATE; } else if (SW_STREQ(key, l_key, "content-type")) { header_flags |= HTTP_HEADER_CONTENT_TYPE; } headers.add(key, l_key, str_value.val(), str_value.len()); }; SW_HASHTABLE_FOREACH_START2(Z_ARRVAL_P(zheader), key, keylen, type, zvalue) { if (UNEXPECTED(!key || ZVAL_IS_NULL(zvalue))) { continue; } if (ZVAL_IS_ARRAY(zvalue)) { zval *zvalue_2; SW_HASHTABLE_FOREACH_START(Z_ARRVAL_P(zvalue), zvalue_2) { add_header(headers, key, keylen, zvalue_2, header_flags); } SW_HASHTABLE_FOREACH_END(); } else { add_header(headers, key, keylen, zvalue, header_flags); } } SW_HASHTABLE_FOREACH_END(); (void) type; } if (!(header_flags & HTTP_HEADER_SERVER)) { headers.add(ZEND_STRL("server"), ZEND_STRL(SW_HTTP_SERVER_SOFTWARE)); } if (!(header_flags & HTTP_HEADER_DATE)) { date_str = php_swoole_format_date((char *) ZEND_STRL(SW_HTTP_DATE_FORMAT), time(nullptr), 0); headers.add(ZEND_STRL("date"), date_str, strlen(date_str)); } if (!(header_flags & HTTP_HEADER_CONTENT_TYPE)) { headers.add(ZEND_STRL("content-type"), ZEND_STRL("text/html")); } if (date_str) { efree(date_str); } // cookies if (ZVAL_IS_ARRAY(zcookie)) { zval *zvalue; SW_HASHTABLE_FOREACH_START(Z_ARRVAL_P(zcookie), zvalue) { if (Z_TYPE_P(zvalue) != IS_STRING) { continue; } headers.add(ZEND_STRL("set-cookie"), Z_STRVAL_P(zvalue), Z_STRLEN_P(zvalue)); } SW_HASHTABLE_FOREACH_END(); } // content encoding #ifdef SW_HAVE_COMPRESSION if (ctx->accept_compression) { const char *content_encoding = ctx->get_content_encoding(); headers.add(ZEND_STRL("content-encoding"), (char *) content_encoding, strlen(content_encoding)); } #endif // content length #ifdef SW_HAVE_COMPRESSION if (ctx->accept_compression) { body_length = swoole_zlib_buffer->length; } #endif ret = swoole_itoa(intbuf[1], body_length); headers.add(ZEND_STRL("content-length"), intbuf[1], ret); Http2Session *client = http2_sessions[ctx->fd]; nghttp2_hd_deflater *deflater = client->deflater; if (!deflater) { ret = nghttp2_hd_deflate_new2(&deflater, client->header_table_size, php_nghttp2_mem()); if (ret != 0) { swoole_warning("nghttp2_hd_deflate_new2() failed with error: %s", nghttp2_strerror(ret)); return -1; } client->deflater = deflater; } size_t buflen = nghttp2_hd_deflate_bound(deflater, headers.get(), headers.len()); /* if (buflen > SW_HTTP2_DEFAULT_MAX_HEADER_LIST_SIZE) { php_swoole_error(E_WARNING, "header cannot bigger than remote max_header_list_size %u", SW_HTTP2_DEFAULT_MAX_HEADER_LIST_SIZE); return -1; } */ ssize_t rv = nghttp2_hd_deflate_hd(deflater, (uchar *) buffer, buflen, headers.get(), headers.len()); if (rv < 0) { swoole_warning("nghttp2_hd_deflate_hd() failed with error: %s", nghttp2_strerror((int) rv)); return -1; } ctx->send_header_ = 1; return rv; } int swoole_http2_server_ping(HttpContext *ctx) { char frame[SW_HTTP2_FRAME_HEADER_SIZE + SW_HTTP2_FRAME_PING_PAYLOAD_SIZE]; Http2::set_frame_header(frame, SW_HTTP2_TYPE_PING, SW_HTTP2_FRAME_PING_PAYLOAD_SIZE, SW_HTTP2_FLAG_NONE, 0); return ctx->send(ctx, frame, SW_HTTP2_FRAME_HEADER_SIZE + SW_HTTP2_FRAME_PING_PAYLOAD_SIZE) ? SW_OK : SW_ERR; } int swoole_http2_server_goaway(HttpContext *ctx, zend_long error_code, const char *debug_data, size_t debug_data_len) { size_t length = SW_HTTP2_FRAME_HEADER_SIZE + SW_HTTP2_GOAWAY_SIZE + debug_data_len; char *frame = (char *) ecalloc(1, length); bool ret; Http2Session *client = http2_sessions[ctx->fd]; uint32_t last_stream_id = client->last_stream_id; Http2::set_frame_header(frame, SW_HTTP2_TYPE_GOAWAY, SW_HTTP2_GOAWAY_SIZE + debug_data_len, error_code, 0); *(uint32_t *) (frame + SW_HTTP2_FRAME_HEADER_SIZE) = htonl(last_stream_id); *(uint32_t *) (frame + SW_HTTP2_FRAME_HEADER_SIZE + 4) = htonl(error_code); if (debug_data_len > 0) { memcpy(frame + SW_HTTP2_FRAME_HEADER_SIZE + SW_HTTP2_GOAWAY_SIZE, debug_data, debug_data_len); } ret = ctx->send(ctx, frame, length); efree(frame); client->shutting_down = true; return ret; } bool Http2Stream::send_header(size_t body_length, bool end_stream) { char header_buffer[SW_BUFFER_SIZE_STD]; ssize_t bytes = http2_build_header(ctx, (uchar *) header_buffer, body_length); if (bytes < 0) { return false; } swoole_http_buffer->clear(); /** +---------------+ |Pad Length? (8)| +-+-------------+-----------------------------------------------+ |E| Stream Dependency? (31) | +-+-------------+-----------------------------------------------+ | Weight? (8) | +-+-------------+-----------------------------------------------+ | Header Block Fragment (*) ... +---------------------------------------------------------------+ | Padding (*) ... +---------------------------------------------------------------+ */ char frame_header[SW_HTTP2_FRAME_HEADER_SIZE]; if (end_stream && body_length == 0) { http2::set_frame_header( frame_header, SW_HTTP2_TYPE_HEADERS, bytes, SW_HTTP2_FLAG_END_HEADERS | SW_HTTP2_FLAG_END_STREAM, id); } else { http2::set_frame_header(frame_header, SW_HTTP2_TYPE_HEADERS, bytes, SW_HTTP2_FLAG_END_HEADERS, id); } swoole_http_buffer->append(frame_header, SW_HTTP2_FRAME_HEADER_SIZE); swoole_http_buffer->append(header_buffer, bytes); if (!ctx->send(ctx, swoole_http_buffer->str, swoole_http_buffer->length)) { ctx->send_header_ = 0; return false; } return true; } bool Http2Stream::send_body(String *body, bool end_stream, size_t max_frame_size, off_t offset, size_t length) { char frame_header[SW_HTTP2_FRAME_HEADER_SIZE]; char *p = body->str + offset; size_t l = length == 0 ? body->length : length; int flag = end_stream ? SW_HTTP2_FLAG_END_STREAM : SW_HTTP2_FLAG_NONE; while (l > 0) { size_t send_n; int _send_flag; swoole_http_buffer->clear(); if (l > max_frame_size) { send_n = max_frame_size; _send_flag = 0; } else { send_n = l; _send_flag = flag; } http2::set_frame_header(frame_header, SW_HTTP2_TYPE_DATA, send_n, _send_flag, id); swoole_http_buffer->append(frame_header, SW_HTTP2_FRAME_HEADER_SIZE); swoole_http_buffer->append(p, send_n); if (!ctx->send(ctx, swoole_http_buffer->str, swoole_http_buffer->length)) { return false; } else { l -= send_n; p += send_n; } } return true; } bool Http2Stream::send_trailer() { char header_buffer[SW_BUFFER_SIZE_STD] = {}; char frame_header[SW_HTTP2_FRAME_HEADER_SIZE]; swoole_http_buffer->clear(); ssize_t bytes = http2_build_trailer(ctx, (uchar *) header_buffer); if (bytes > 0) { http2::set_frame_header( frame_header, SW_HTTP2_TYPE_HEADERS, bytes, SW_HTTP2_FLAG_END_HEADERS | SW_HTTP2_FLAG_END_STREAM, id); swoole_http_buffer->append(frame_header, SW_HTTP2_FRAME_HEADER_SIZE); swoole_http_buffer->append(header_buffer, bytes); if (!ctx->send(ctx, swoole_http_buffer->str, swoole_http_buffer->length)) { return false; } } return true; } static bool swoole_http2_server_respond(HttpContext *ctx, String *body) { Http2Session *client = http2_sessions[ctx->fd]; Http2Stream *stream = ctx->stream; #ifdef SW_HAVE_COMPRESSION if (ctx->accept_compression) { if (body->length == 0 || swoole_http_response_compress(body->str, body->length, ctx->compression_method, ctx->compression_level) != SW_OK) { ctx->accept_compression = 0; } else { body = swoole_zlib_buffer; } } #endif zval *ztrailer = sw_zend_read_property_ex(swoole_http_response_ce, ctx->response.zobject, SW_ZSTR_KNOWN(SW_ZEND_STR_TRAILER), 0); if (php_swoole_array_length_safe(ztrailer) == 0) { ztrailer = nullptr; } bool end_stream = (ztrailer == nullptr); if (!stream->send_header(body->length, end_stream)) { return false; } // The headers has already been sent, retries are no longer allowed (even if send body failed) ctx->end_ = 1; bool error = false; // If send_yield is not supported, ignore flow control if (ctx->co_socket || !((Server *) ctx->private_data)->send_yield) { if (body->length > client->send_window) { swoole_warning("The data sent exceeded send_window"); } if (!stream->send_body(body, end_stream, client->max_frame_size)) { error = true; } } else { while (true) { size_t send_len = body->length - body->offset; if (send_len == 0) { break; } if (stream->send_window == 0) { stream->waiting_coroutine = Coroutine::get_current(); stream->waiting_coroutine->yield(); stream->waiting_coroutine = nullptr; continue; } else if (send_len <= stream->send_window) { error = !stream->send_body(body, true && end_stream, client->max_frame_size, body->offset, send_len); break; } else { send_len = client->max_frame_size; error = !stream->send_body(body, false, client->max_frame_size, body->offset, send_len); } if (!error) { swoole_trace_log(SW_TRACE_HTTP2, "body: send length=%zu", send_len); body->offset += send_len; if (send_len > stream->send_window) { stream->send_window = 0; } else { stream->send_window -= send_len; } } } } if (!error && ztrailer && !stream->send_trailer()) { error = true; } if (error) { ctx->close(ctx); } else { client->streams.erase(stream->id); delete stream; } if (client->shutting_down && client->streams.size() == 0) { ctx->close(ctx); } return !error; } static bool http2_context_sendfile(HttpContext *ctx, const char *file, uint32_t l_file, off_t offset, size_t length) { Http2Session *client = http2_sessions[ctx->fd]; Http2Stream *stream = (Http2Stream *) ctx->stream; std::shared_ptr<String> body; #ifdef SW_HAVE_COMPRESSION ctx->accept_compression = 0; #endif if (swoole_coroutine_is_in()) { body = System::read_file(file, false); if (!body) { return false; } if (!ctx->stream) { /* closed */ return false; } } else { File fp(file, O_RDONLY); if (!fp.ready()) { return false; } body = fp.read_content(); if (body->empty()) { return false; } } body->length = SW_MIN(length, body->length); zval *ztrailer = sw_zend_read_property_ex(swoole_http_response_ce, ctx->response.zobject, SW_ZSTR_KNOWN(SW_ZEND_STR_TRAILER), 0); if (php_swoole_array_length_safe(ztrailer) == 0) { ztrailer = nullptr; } const char *mimetype = swoole::mime_type::get(file).c_str(); ctx->set_header(ZEND_STRL("content-type"), mimetype, strlen(mimetype), 0); bool end_stream = (ztrailer == nullptr); if (!stream->send_header(length, end_stream)) { return false; } /* headers has already been sent, retries are no longer allowed (even if send body failed) */ ctx->end_ = 1; bool error = false; if (body->length > 0) { if (!stream->send_body(body.get(), end_stream, client->max_frame_size, offset, length)) { error = true; } else { client->send_window -= length; // TODO: flow control? } } if (!error && ztrailer) { if (!stream->send_trailer()) { error = true; } } if (error) { ctx->close(ctx); } else { client->streams.erase(stream->id); delete stream; } return true; } static int http2_parse_header(Http2Session *client, HttpContext *ctx, int flags, const char *in, size_t inlen) { nghttp2_hd_inflater *inflater = client->inflater; if (!inflater) { int ret = nghttp2_hd_inflate_new2(&inflater, php_nghttp2_mem()); if (ret != 0) { swoole_warning("nghttp2_hd_inflate_new2() failed, Error: %s[%d]", nghttp2_strerror(ret), ret); return SW_ERR; } client->inflater = inflater; } if (flags & SW_HTTP2_FLAG_PRIORITY) { // int stream_deps = ntohl(*(int *) (in)); // uint8_t weight = in[4]; in += 5; inlen -= 5; } zval *zheader = ctx->request.zheader; zval *zserver = ctx->request.zserver; ssize_t rv; for (;;) { nghttp2_nv nv; int inflate_flags = 0; size_t proclen; rv = nghttp2_hd_inflate_hd(inflater, &nv, &inflate_flags, (uchar *) in, inlen, 1); if (rv < 0) { swoole_warning("inflate failed, Error: %s[%zd]", nghttp2_strerror(rv), rv); return SW_ERR; } proclen = (size_t) rv; in += proclen; inlen -= proclen; if (inflate_flags & NGHTTP2_HD_INFLATE_EMIT) { swoole_trace_log( SW_TRACE_HTTP2, "Header: " SW_ECHO_BLUE "[%zu]: %s[%zu]", nv.name, nv.namelen, nv.value, nv.valuelen); if (nv.name[0] == ':') { if (SW_STRCASEEQ((char *) nv.name + 1, nv.namelen - 1, "method")) { add_assoc_stringl_ex(zserver, ZEND_STRL("request_method"), (char *) nv.value, nv.valuelen); } else if (SW_STRCASEEQ((char *) nv.name + 1, nv.namelen - 1, "path")) { char *pathbuf = sw_tg_buffer()->str; char *v_str = strchr((char *) nv.value, '?'); zend_string *zstr_path; if (v_str) { v_str++; int k_len = v_str - (char *) nv.value - 1; int v_len = nv.valuelen - k_len - 1; memcpy(pathbuf, nv.value, k_len); pathbuf[k_len] = 0; add_assoc_stringl_ex(zserver, ZEND_STRL("query_string"), v_str, v_len); zstr_path = zend_string_init(pathbuf, k_len, 0); // parse url params sapi_module.treat_data( PARSE_STRING, estrndup(v_str, v_len), // it will be freed by treat_data swoole_http_init_and_read_property( swoole_http_request_ce, ctx->request.zobject, &ctx->request.zget, ZEND_STRL("get"))); } else { zstr_path = zend_string_init((char *) nv.value, nv.valuelen, 0); } ctx->request.path = (char *) estrndup((char *) nv.value, nv.valuelen); ctx->request.path_len = nv.valuelen; add_assoc_str_ex(zserver, ZEND_STRL("request_uri"), zstr_path); // path_info should be decoded zstr_path = zend_string_dup(zstr_path, 0); ZSTR_LEN(zstr_path) = php_url_decode(ZSTR_VAL(zstr_path), ZSTR_LEN(zstr_path)); add_assoc_str_ex(zserver, ZEND_STRL("path_info"), zstr_path); } else if (SW_STRCASEEQ((char *) nv.name + 1, nv.namelen - 1, "authority")) { add_assoc_stringl_ex(zheader, ZEND_STRL("host"), (char *) nv.value, nv.valuelen); } } else { if (SW_STRCASEEQ((char *) nv.name, nv.namelen, "content-type")) { if (SW_STRCASECT((char *) nv.value, nv.valuelen, "application/x-www-form-urlencoded")) { ctx->request.post_form_urlencoded = 1; } else if (SW_STRCASECT((char *) nv.value, nv.valuelen, "multipart/form-data")) { int boundary_len = nv.valuelen - (sizeof("multipart/form-data; boundary=") - 1); if (boundary_len <= 0) { swoole_warning("invalid multipart/form-data body fd:%ld", ctx->fd); return SW_ERR; } ctx->parse_form_data((char *) nv.value + nv.valuelen - boundary_len, boundary_len); ctx->parser.data = ctx; } } else if (SW_STRCASEEQ((char *) nv.name, nv.namelen, "cookie")) { swoole_http_parse_cookie( swoole_http_init_and_read_property( swoole_http_request_ce, ctx->request.zobject, &ctx->request.zcookie, ZEND_STRL("cookie")), (const char *) nv.value, nv.valuelen); continue; } #ifdef SW_HAVE_COMPRESSION else if (ctx->enable_compression && SW_STRCASEEQ((char *) nv.name, nv.namelen, "accept-encoding")) { ctx->set_compression_method((char *) nv.value, nv.valuelen); } #endif add_assoc_stringl_ex(zheader, (char *) nv.name, nv.namelen, (char *) nv.value, nv.valuelen); } } if (inflate_flags & NGHTTP2_HD_INFLATE_FINAL) { nghttp2_hd_inflate_end_headers(inflater); break; } if ((inflate_flags & NGHTTP2_HD_INFLATE_EMIT) == 0 && inlen == 0) { break; } } return SW_OK; } int swoole_http2_server_parse(Http2Session *client, const char *buf) { Http2Stream *stream = nullptr; int type = buf[3]; int flags = buf[4]; int retval = SW_ERR; uint32_t stream_id = ntohl((*(int *) (buf + 5))) & 0x7fffffff; if (stream_id > client->last_stream_id) { client->last_stream_id = stream_id; } if (client->shutting_down) { swoole_error_log( SW_LOG_WARNING, SW_ERROR_HTTP2_STREAM_IGNORE, "ignore http2 stream#%d after sending goaway", stream_id); return retval; } ssize_t length = Http2::get_length(buf); buf += SW_HTTP2_FRAME_HEADER_SIZE; uint16_t id = 0; uint32_t value = 0; switch (type) { case SW_HTTP2_TYPE_SETTINGS: { if (flags & SW_HTTP2_FLAG_ACK) { swHttp2FrameTraceLog(recv, "ACK"); break; } while (length > 0) { id = ntohs(*(uint16_t *) (buf)); value = ntohl(*(uint32_t *) (buf + sizeof(uint16_t))); swHttp2FrameTraceLog(recv, "id=%d, value=%d", id, value); switch (id) { case SW_HTTP2_SETTING_HEADER_TABLE_SIZE: if (value != client->header_table_size) { client->header_table_size = value; if (client->deflater) { int ret = nghttp2_hd_deflate_change_table_size(client->deflater, value); if (ret != 0) { swoole_warning("nghttp2_hd_deflate_change_table_size() failed, errno=%d, errmsg=%s", ret, nghttp2_strerror(ret)); return SW_ERR; } } } swoole_trace_log(SW_TRACE_HTTP2, "setting: header_table_size=%u", value); break; case SW_HTTP2_SETTINGS_MAX_CONCURRENT_STREAMS: client->max_concurrent_streams = value; swoole_trace_log(SW_TRACE_HTTP2, "setting: max_concurrent_streams=%u", value); break; case SW_HTTP2_SETTINGS_INIT_WINDOW_SIZE: client->send_window = value; swoole_trace_log(SW_TRACE_HTTP2, "setting: init_send_window=%u", value); break; case SW_HTTP2_SETTINGS_MAX_FRAME_SIZE: client->max_frame_size = value; swoole_trace_log(SW_TRACE_HTTP2, "setting: max_frame_size=%u", value); break; case SW_HTTP2_SETTINGS_MAX_HEADER_LIST_SIZE: // client->max_header_list_size = value; // useless now swoole_trace_log(SW_TRACE_HTTP2, "setting: max_header_list_size=%u", value); break; default: // disable warning and ignore it because some websites are not following http2 protocol totally // swoole_warning("unknown option[%d]: %d", id, value); break; } buf += sizeof(id) + sizeof(value); length -= sizeof(id) + sizeof(value); } break; } case SW_HTTP2_TYPE_HEADERS: { stream = client->streams[stream_id]; swHttp2FrameTraceLog(recv, "%s", (stream ? "exist stream" : "new stream")); HttpContext *ctx; if (!stream) { stream = new Http2Stream(client, stream_id); if (sw_unlikely(!stream->ctx)) { swoole_error_log( SW_LOG_WARNING, SW_ERROR_HTTP2_STREAM_NO_HEADER, "http2 create stream#%d context error", stream_id); return SW_ERR; } ctx = stream->ctx; client->streams[stream_id] = stream; zend_update_property_long( swoole_http_request_ce, SW_Z8_OBJ_P(ctx->request.zobject), ZEND_STRL("streamId"), stream_id); } else { ctx = stream->ctx; } if (http2_parse_header(client, ctx, flags, buf, length) < 0) { return SW_ERR; } if (flags & SW_HTTP2_FLAG_END_STREAM) { client->handle(client, stream); } else { // need continue frame } break; } case SW_HTTP2_TYPE_DATA: { swHttp2FrameTraceLog(recv, "data"); auto stream_iterator = client->streams.find(stream_id); if (stream_iterator == client->streams.end()) { swoole_error_log(SW_LOG_WARNING, SW_ERROR_HTTP2_STREAM_NOT_FOUND, "http2 stream#%d not found", stream_id); return SW_ERR; } stream = stream_iterator->second; HttpContext *ctx = stream->ctx; zend_update_property_long( swoole_http_request_ce, SW_Z8_OBJ_P(ctx->request.zobject), ZEND_STRL("streamId"), stream_id); String *buffer = ctx->request.h2_data_buffer; if (!buffer) { buffer = new String(SW_HTTP2_DATA_BUFFER_SIZE); ctx->request.h2_data_buffer = buffer; } buffer->append(buf, length); // flow control client->recv_window -= length; stream->recv_window -= length; if (length > 0) { if (client->recv_window < (SW_HTTP2_MAX_WINDOW_SIZE / 4)) { http2_server_send_window_update(ctx, 0, SW_HTTP2_MAX_WINDOW_SIZE - client->recv_window); client->recv_window = SW_HTTP2_MAX_WINDOW_SIZE; } if (stream->recv_window < (SW_HTTP2_MAX_WINDOW_SIZE / 4)) { http2_server_send_window_update(ctx, stream_id, SW_HTTP2_MAX_WINDOW_SIZE - stream->recv_window); stream->recv_window = SW_HTTP2_MAX_WINDOW_SIZE; } } if (flags & SW_HTTP2_FLAG_END_STREAM) { if (ctx->parse_body && ctx->request.post_form_urlencoded) { sapi_module.treat_data( PARSE_STRING, estrndup(buffer->str, buffer->length), // it will be freed by treat_data swoole_http_init_and_read_property( swoole_http_request_ce, ctx->request.zobject, &ctx->request.zpost, ZEND_STRL("post"))); } else if (ctx->mt_parser != nullptr) { multipart_parser *multipart_parser = ctx->mt_parser; size_t n = multipart_parser_execute(multipart_parser, buffer->str, buffer->length); if (n != (size_t) length) { swoole_error_log( SW_LOG_WARNING, SW_ERROR_SERVER_INVALID_REQUEST, "parse multipart body failed, n=%zu", n); } } if (!client->is_coro) { retval = SW_OK; } client->handle(client, stream); } break; } case SW_HTTP2_TYPE_PING: { swHttp2FrameTraceLog(recv, "ping"); if (!(flags & SW_HTTP2_FLAG_ACK)) { char ping_frame[SW_HTTP2_FRAME_HEADER_SIZE + SW_HTTP2_FRAME_PING_PAYLOAD_SIZE]; Http2::set_frame_header( ping_frame, SW_HTTP2_TYPE_PING, SW_HTTP2_FRAME_PING_PAYLOAD_SIZE, SW_HTTP2_FLAG_ACK, stream_id); memcpy(ping_frame + SW_HTTP2_FRAME_HEADER_SIZE, buf, SW_HTTP2_FRAME_PING_PAYLOAD_SIZE); client->default_ctx->send( client->default_ctx, ping_frame, SW_HTTP2_FRAME_HEADER_SIZE + SW_HTTP2_FRAME_PING_PAYLOAD_SIZE); } break; } case SW_HTTP2_TYPE_WINDOW_UPDATE: { value = ntohl(*(uint32_t *) buf); if (stream_id == 0) { client->send_window += value; } else if (client->streams.find(stream_id) != client->streams.end()) { stream = client->streams[stream_id]; Server *serv = (Server *) stream->ctx->private_data; stream->send_window += value; if (serv->send_yield && stream->waiting_coroutine) { stream->waiting_coroutine->resume(); } } swHttp2FrameTraceLog(recv, "window_size_increment=%d", value); break; } case SW_HTTP2_TYPE_RST_STREAM: { value = ntohl(*(int *) (buf)); swHttp2FrameTraceLog(recv, "error_code=%d", value); if (client->streams.find(stream_id) != client->streams.end()) { // TODO: i onRequest and use request->recv // stream exist stream = client->streams[stream_id]; client->streams.erase(stream_id); delete stream; } break; } case SW_HTTP2_TYPE_GOAWAY: { uint32_t server_last_stream_id = ntohl(*(uint32_t *) (buf)); buf += 4; value = ntohl(*(uint32_t *) (buf)); buf += 4; swHttp2FrameTraceLog(recv, "last_stream_id=%d, error_code=%d, opaque_data=[%.*s]", server_last_stream_id, value, (int) (length - SW_HTTP2_GOAWAY_SIZE), buf); // TODO: onRequest (void) server_last_stream_id; break; } default: { swHttp2FrameTraceLog(recv, ""); } } return retval; } /** * Http2 */ int swoole_http2_server_onFrame(Server *serv, Connection *conn, RecvData *req) { int session_id = req->info.fd; Http2Session *client = http2_sessions[session_id]; if (client == nullptr) { client = new Http2Session(session_id); } client->handle = swoole_http2_onRequest; if (!client->default_ctx) { client->default_ctx = new HttpContext(); client->default_ctx->init(serv); client->default_ctx->fd = session_id; client->default_ctx->http2 = true; client->default_ctx->stream = (Http2Stream *) -1; client->default_ctx->keepalive = true; client->default_ctx->sendfile = http2_context_sendfile; } zval zdata; php_swoole_get_recv_data(serv, &zdata, req); int retval = swoole_http2_server_parse(client, Z_STRVAL(zdata)); zval_ptr_dtor(&zdata); return retval; } void swoole_http2_server_session_free(Connection *conn) { auto session_iterator = http2_sessions.find(conn->session_id); if (session_iterator == http2_sessions.end()) { return; } Http2Session *client = session_iterator->second; delete client; } void HttpContext::http2_end(zval *zdata, zval *return_value) { String http_body = {}; if (zdata) { http_body.length = php_swoole_get_send_data(zdata, &http_body.str); } else { http_body.length = 0; http_body.str = nullptr; } RETURN_BOOL(swoole_http2_server_respond(this, &http_body)); } #endif
#include "headers.h" /** * @brief * https://leetcode-cn.com/problems/longest-palindromic-substring/ * * 给你一个字符串 s,找到 s 中最长的回文子串。 */ class Solution { public: /** * @brief pan duan reverse str substring * * @param words * @return true * @return false */ bool huiWen(string words) { if (words.size() == 0) { return false; } int len = words.size(); int left = 0; int right = len - 1; bool ans = true; while (left < right) { if (words[left] != words[right]) { ans = false; break; } left++; right--; } return ans; } /** * @brief bao li pass some testcases. * * @param s * @return string */ string longestPalindrome(string s) { int n = s.size(); if (n < 2) { return s; } int left = 0; int right = 0; string ans = ""; int ansMaxLen = 0; for (int i = 0; i < n; i++) { for (int j = i + 1; j <= n; j++) { string subStr = s.substr(i, j - i); int tmpLen = subStr.length(); string revStr = subStr; std::reverse(revStr.begin(), revStr.end()); // if (!huiWen(subStr)) { if (subStr != revStr) { continue; } if (tmpLen >= ansMaxLen) { ans = subStr; } ansMaxLen = max(ansMaxLen, tmpLen); } } return ans; } private: /** * @brief * nothing */ }; TEST(T5_Longest_Palindromic_Substring, test_is_huiwen_true) { Solution s; string abcba = "abcba"; EXPECT_EQ(s.huiWen(abcba), true); string a = "a"; bool retA = s.huiWen(a); EXPECT_EQ(retA, true); } TEST(T5_Longest_Palindromic_Substring, test_is_huiwen_false) { Solution s; string abcbb = "abcbb"; bool ret1 = s.huiWen(abcbb); EXPECT_EQ(ret1, false); string abdca = "abdca"; bool ret2 = s.huiWen(abdca); EXPECT_EQ(ret2, false); } TEST(T5_Longest_Palindromic_Substring, test_longestPalindrome) { Solution s; string babad = "babad"; string ret1 = s.longestPalindrome(babad); EXPECT_EQ(ret1, "aba"); // aba is also the right answer. } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
#include <iostream> #include <string> #include <fstream> #include <cstring> using namespace std; //function to do big mod int mod(int base,int exponential,int modd) { int ans = 1; int counter = 0; while(counter < exponential) { ans = (ans * base) % modd; counter++; } return ans; } //where all the magic happens int main() { //all my input variable string filename; int base; int exponent; int modd; //rest of the needed variables string line; //take in all my inputs first cout << "What file are we trying to encrypt?" << endl; cin >> filename; cout << "Please enter the public key m" << endl; cin >> modd; cout << "Please enter the public key k" << endl; cin >> exponent; //ifstream.open() takes in char[] input, //following code converts string to char[] char nameArray[filename.size()]; strcpy(nameArray, filename.c_str()); //open our file ifstream myfile; myfile.open(nameArray); //create a new .txt file ofstream newfile; newfile.open("encryptedfile.txt"); //loop through each line of file while(getline(myfile,line)) { //variables in the loop int length = line.size(); char array[length]; strcpy(array,line.c_str()); int encryptArray[length]; int counter = 0; char ascii; int numeric; //loop through each line which are now char[]s //turn each char to ascii and encrypt with key while(counter < length) { ascii = (int) array[counter]; encryptArray[counter] = mod(ascii,exponent,modd); newfile << encryptArray[counter]; counter++; if(counter <= length) { newfile << " "; } } newfile << mod(10,exponent,modd) << "\n"; } }
// Copyright 2015-2021 Tier IV, Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <openscenario_interpreter/procedure.hpp> #include <openscenario_interpreter/syntax/time_headway_condition.hpp> #include <openscenario_interpreter/utility/print.hpp> namespace openscenario_interpreter { inline namespace syntax { TimeHeadwayCondition::TimeHeadwayCondition( const pugi::xml_node & node, Scope & scope, const TriggeringEntities & triggering_entities) : entity_ref(readAttribute<String>("entityRef", node, scope)), value(readAttribute<Double>("value", node, scope)), freespace(readAttribute<Boolean>("freespace", node, scope)), along_route(readAttribute<Boolean>("alongRoute", node, scope)), compare(readAttribute<Rule>("rule", node, scope)), triggering_entities(triggering_entities), results(triggering_entities.entity_refs.size(), Double::nan()) { } auto TimeHeadwayCondition::description() const -> String { std::stringstream description; description << triggering_entities.description() << "'s headway time between each and the referenced entity " << entity_ref << " = "; print_to(description, results); description << " " << compare << " " << value << "?"; return description.str(); } auto TimeHeadwayCondition::evaluate() -> Object { results.clear(); return asBoolean(triggering_entities.apply([&](auto && triggering_entity) { results.push_back(getTimeHeadway(triggering_entity, entity_ref)); return compare(results.back(), value); })); } } // namespace syntax } // namespace openscenario_interpreter
#include <iostream> #include <string> #include <fstream> #include <sstream> #include <map> int isNotAlphaNum(char c) { return !std::isalnum(c); } void countWords(std::istream& in, std::map<std::string, int>& words) { std::string line; std::string word; while (std::getline(in, line)) { std::replace_if(line.begin(), line.end(), isNotAlphaNum, ' '); std::istringstream iss(line); while (iss >> word) { words[word]++; } } } int main(int argc, char* argv[]) { if (argc < 3) { std::cerr << "No filename?" << std::endl; return -1; } std::ifstream in(argv[1]); if (!in) { std::cerr << "No data?" << std::endl; return -1; } std::map<std::string, int> words; countWords(in, words); std::ofstream out(argv[2]); for (std::map<std::string, int>::iterator p = words.begin(); p != words.end(); p++) { out << " " << " " << " " << p->second << " " << p->first << "\n"; } return 0; }
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/indexed_db/indexed_db_connection.h" namespace content { IndexedDBConnection::IndexedDBConnection( scoped_refptr<IndexedDBDatabase> database, scoped_refptr<IndexedDBDatabaseCallbacks> callbacks) : database_(database), callbacks_(callbacks), weak_factory_(this) {} IndexedDBConnection::~IndexedDBConnection() {} void IndexedDBConnection::Close() { if (!callbacks_.get()) return; base::WeakPtr<IndexedDBConnection> this_obj = weak_factory_.GetWeakPtr(); database_->Close(this, false /* forced */); if (this_obj) { database_ = nullptr; callbacks_ = nullptr; } } void IndexedDBConnection::ForceClose() { if (!callbacks_.get()) return; // IndexedDBDatabase::Close() can delete this instance. base::WeakPtr<IndexedDBConnection> this_obj = weak_factory_.GetWeakPtr(); scoped_refptr<IndexedDBDatabaseCallbacks> callbacks(callbacks_); database_->Close(this, true /* forced */); if (this_obj) { database_ = nullptr; callbacks_ = nullptr; } callbacks->OnForcedClose(); } void IndexedDBConnection::VersionChangeIgnored() { if (!database_.get()) return; database_->VersionChangeIgnored(); } bool IndexedDBConnection::IsConnected() { return database_.get() != NULL; } } // namespace content
/* * Copyright (c) 2016-2019 * Viktor Gubin * * Use, modification and distribution are subject to the * Boost Software License, Version 1.0. (See accompanying file * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) * */ #ifndef __IO_CONSTSTRING_HPP_INCLUDED__ #define __IO_CONSTSTRING_HPP_INCLUDED__ #include "config.hpp" #ifdef HAS_PRAGMA_ONCE #pragma once #endif // HAS_PRAGMA_ONCE #include "text.hpp" #include "hashing.hpp" #include <cstring> #include <cctype> #include <functional> #include <iosfwd> #include <string> #if defined(__HAS_CPP_17) # include <string_view> #endif namespace io { namespace detail { #if defined(__HAS_CPP_17) && defined(__cpp_char8_t) typedef char8_t utf8char; #else typedef uint8_t utf8char; #endif // defined struct long_char_buf_t { // considering size would never be larger then SSIZE_MAX // since most systems have much less memory then CPU can address // so use signbit as align for sso boolean std::size_t sso: 1; std::size_t size: (sizeof(std::size_t)*CHAR_BIT) - 1; // layout for string is {reference_counter:size_t}{char_data}{'\0'} utf8char* char_buf; }; // two bytes reserver to SSO flag and size static constexpr std::size_t SSO_MAX = sizeof(long_char_buf_t) - 2; struct short_char_buf_t { bool sso: 1; // assuming MAX_SIZE string length is not possible, uint8_t size: CHAR_BIT - 1; // max val + zero ending char char char_buf[ SSO_MAX+1 ]; }; // Packs small strings into char array instead of allocating heap value // whenever possible // 16 bytes for most known 64-bit or 8 bytes for 32-bit target architecture union sso_variant_t { long_char_buf_t long_buf; short_char_buf_t short_buf; }; constexpr bool is_short(const sso_variant_t& v) noexcept { return v.short_buf.sso; } constexpr std::size_t short_size(const sso_variant_t& v) noexcept { return v.short_buf.size; } constexpr const char* short_str(const sso_variant_t& v) noexcept { return v.short_buf.char_buf; } inline const char* long_str(const sso_variant_t& v) noexcept { return reinterpret_cast<char*>(v.long_buf.char_buf) + sizeof(std::size_t); } } // namespace detail /// \brief Immutable zero ending C style string wrapper class IO_PUBLIC_SYMBOL const_string final { private: static void long_buf_add_ref(detail::sso_variant_t& var) noexcept { std::size_t volatile *p = reinterpret_cast<std::size_t volatile*>(var.long_buf.char_buf); // increment string intrusive reference counter, with relaxed memory order detail::atomic_traits::inc(p); } static inline bool carr_empty(const char* rhs, std::size_t len) noexcept { return 0 == len || nullptr == rhs || '\0' == *rhs; } static void long_buf_release(detail::sso_variant_t& var) noexcept; void init_short(detail::sso_variant_t& dst, const char* str, std::size_t length) noexcept; void init_long(detail::sso_variant_t& dst,std::size_t size,const char* str, std::size_t length) noexcept; public: typedef std::char_traits<char> traits_type; /// Creates empty constant string object constexpr const_string() noexcept: data_( {false, 0, nullptr} ) {} const_string(const const_string& other) noexcept: data_(other.data_) { // increase reference count if needed // for long buffer if( !empty() && !sso() ) long_buf_add_ref(data_); } const_string& operator=(const const_string& rhs) noexcept { const_string(rhs).swap( *this ); return *this; } /// Movement constructor, default movement semantic const_string(const_string&& other) noexcept: data_(other.data_) { other.data_ = {false,0,nullptr}; } /// Movement assignment operator, default movement semantic const_string& operator=(const_string&& other) noexcept { const_string( std::forward<const_string>(other) ).swap( *this ); return *this; } /// Constructs constant string object by deep copying a character array /// \param str pointer to character array begin /// \param length count of bytes to copy from array /// \throw never throws, constructs empty string if no free memory left const_string(const char* str, std::size_t length) noexcept; ~const_string() noexcept; /// Deep copy a continues memory block (character array) /// \param first pointer on memory block begin /// \param last pointer on block end const_string(const char* first, const char* last) noexcept: const_string( first, memory_traits::distance(first,last) ) {} /// Deep copies a zero ending C string const_string(const char* str) noexcept: const_string(str, traits_type::length(str) ) {} /// Swaps this object with another one /// \param with object to swap with this inline void swap(const_string& with) noexcept { std::swap(data_, with.data_); } /// Check this sting is short string optimized version /// \return whether short string optimized inline bool sso() const noexcept { return detail::is_short(data_); } /// Returns whether this string is pointing on nullptr /// \return whether nullptr string inline bool empty() const noexcept { return !sso() && 0 == data_.long_buf.size; } /// Checks whether this string empty or contains only whitespace characters /// \return whether this string is blank inline bool blank() const noexcept { constexpr const char* WS = "\t\n\v\f\r "; return empty() ? true : size() == io_strspn(data(), WS); } /// Returns raw C-style zero ending string /// \return C-style string, "" if string is empty const char* data() const noexcept { return empty() ? "" : sso() ? detail::short_str(data_) : detail::long_str(data_); } /// Returns mutable std::string by deep copying underlying character array inline std::string get_mutable() const { return empty() ? std::string() : std::string( data(), size() ); } #ifdef __HAS_CPP_17 inline std::string_view get_view() const { return std::string_view( data(), size() ); } #endif // __HAS_CPP_17 /// Converts this string to system UCS-2 ( UTF-16 LE or BE) inline std::u16string convert_to_u16() const { return empty() ? std::u16string() : transcode_to_u16( data(), size() ); } /// Converts this string to system UCS-4 ( UTF-32 LE or BE) inline std::u32string convert_to_u32() const { return empty() ? std::u32string() : transcode_to_u32( data(), size() ); } /// Converts this string to system wide UNICODE (UTF-16/32 LE/BE OS and CPU byte order depends) representation inline std::wstring convert_to_ucs() const { return empty() ? std::wstring() : transcode_to_ucs( data(), size() ); } ///Returns string length in UNICODE characters /// \return string length in characters inline std::size_t length() const noexcept { return empty() ? 0 : utf8::strlength( data() ); } /// Returns string size in bytes /// \return string size in bytes inline std::size_t size() const noexcept { return empty() ? 0 : sso() ? detail::short_size(data_) : data_.long_buf.size; } /// Hash this string bytes (murmur3 for 32bit, Cityhash for 64 bit) /// \return string content hash inline std::size_t hash() const noexcept { return empty() ? 0 : io::hash_bytes( data(), size() ); } /// Lexicographically compare the string with another /// \param rhs a string to compare with /// \return whether strings equals bool operator==(const const_string& rhs) const noexcept { return 0 == compare( rhs ); } bool operator<(const const_string& rhs) const noexcept { return compare( rhs ) < 0; } bool operator>(const const_string& rhs) const noexcept { return compare( rhs ) > 0; } inline bool equal(const char* rhs) const noexcept { return equal( rhs, nullptr != rhs ? traits_type::length(rhs) : 0 ); } bool equal(const char* rhs, const std::size_t len) const noexcept { if(carr_empty(rhs, len) && empty() ) return true; else if( !empty() && !carr_empty(rhs, len) && len == size() ) return 0 == traits_type::compare( data(), rhs, len ); else return false; } private: inline bool ptr_equal(const const_string& rhs) const noexcept { return (this == std::addressof(rhs)) || ( !sso() && (data_.long_buf.char_buf == rhs.data_.long_buf.char_buf) ); } int compare(const const_string& rhs) const noexcept { if( ( empty() && rhs.empty() ) || ptr_equal(rhs) ) { return 0; } else { std::size_t byte_size = size(); if( byte_size < rhs.size() ) return -1; return traits_type::compare( data(), rhs.data(), byte_size ); } return 1; } private: detail::sso_variant_t data_; }; #ifndef _MSC_VER class const_string_hash: public std::unary_function<std::size_t,io::const_string> { public: inline std::size_t operator()(const io::const_string& str) const noexcept { return str.hash(); } }; #else class const_string_hash { public: typedef io::const_string argument_type; typedef std::size_t result_type; inline std::size_t operator()(const io::const_string& str) const noexcept { return str.hash(); } }; #endif inline std::ostream& operator<<(std::ostream& os, const const_string& cstr) { os.write( cstr.data(), cstr.size() ); return os; } inline std::wostream& operator<<(std::wostream& os, const const_string& cstr) { std::wstring conv = cstr.convert_to_ucs(); os.write(conv.data(), conv.size() ); return os; } inline std::basic_ostream<char16_t>& operator<<(std::basic_ostream<char16_t>& os, const const_string& cstr) { std::u16string conv = cstr.convert_to_u16(); os.write( conv.data(), conv.size() ); return os; } inline std::basic_ostream<char32_t>& operator<<(std::basic_ostream<char32_t>& os, const const_string& cstr) { std::u32string conv = cstr.convert_to_u32(); os.write( conv.data(), conv.size() ); return os; } } // namespace io #endif // __IO_CONSTSTRING_HPP_INCLUDED__
/* Copyright (c) 2003-2019 by Mike Jarvis * * TreeCorr is free software: redistribution and use in source and binary forms, * with or without modification, are permitted provided that the following * conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions, and the disclaimer given in the accompanying LICENSE * file. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions, and the disclaimer given in the documentation * and/or other materials provided with the distribution. */ // Uncomment this to enable xassert, usually more time-consuming assert statements // Also to turn on dbg<< messages. //#define DEBUGLOGGING #include "dbg.h" #include "BinnedCorr2.h" #include "Split.h" #include "ProjectHelper.h" #include "Metric.h" #include <vector> #include <set> #include <map> #ifdef _OPENMP #include "omp.h" #endif // When we need a compile-time max, use this rather than std::max, which only became valid // for compile-time constexpr in C++14, which we don't require. #define MAX(a,b) (a > b ? a : b) template <int D1, int D2, int B> BinnedCorr2<D1,D2,B>::BinnedCorr2( double minsep, double maxsep, int nbins, double binsize, double b, double minrpar, double maxrpar, double xp, double yp, double zp, double* xi0, double* xi1, double* xi2, double* xi3, double* meanr, double* meanlogr, double* weight, double* npairs) : _minsep(minsep), _maxsep(maxsep), _nbins(nbins), _binsize(binsize), _b(b), _minrpar(minrpar), _maxrpar(maxrpar), _xp(xp), _yp(yp), _zp(zp), _coords(-1), _owns_data(false), _xi(xi0,xi1,xi2,xi3), _meanr(meanr), _meanlogr(meanlogr), _weight(weight), _npairs(npairs) { dbg<<"BinnedCorr2 constructor\n"; // Some helpful variables we can calculate once here. _logminsep = log(_minsep); _halfminsep = 0.5*_minsep; _minsepsq = _minsep*_minsep; _maxsepsq = _maxsep*_maxsep; _bsq = _b * _b; _fullmaxsep = BinTypeHelper<B>::calculateFullMaxSep(minsep, maxsep, nbins, binsize); _fullmaxsepsq = _fullmaxsep*_fullmaxsep; dbg<<"minsep, maxsep = "<<_minsep<<" "<<_maxsep<<std::endl; dbg<<"nbins = "<<_nbins<<std::endl; dbg<<"binsize = "<<_binsize<<std::endl; dbg<<"b = "<<_b<<std::endl; dbg<<"minrpar, maxrpar = "<<_minrpar<<" "<<_maxrpar<<std::endl; dbg<<"period = "<<_xp<<" "<<_yp<<" "<<_zp<<std::endl; } template <int D1, int D2, int B> BinnedCorr2<D1,D2,B>::BinnedCorr2(const BinnedCorr2<D1,D2,B>& rhs, bool copy_data) : _minsep(rhs._minsep), _maxsep(rhs._maxsep), _nbins(rhs._nbins), _binsize(rhs._binsize), _b(rhs._b), _minrpar(rhs._minrpar), _maxrpar(rhs._maxrpar), _xp(rhs._xp), _yp(rhs._yp), _zp(rhs._zp), _logminsep(rhs._logminsep), _halfminsep(rhs._halfminsep), _minsepsq(rhs._minsepsq), _maxsepsq(rhs._maxsepsq), _bsq(rhs._bsq), _fullmaxsep(rhs._fullmaxsep), _fullmaxsepsq(rhs._fullmaxsepsq), _coords(rhs._coords), _owns_data(true), _xi(0,0,0,0), _weight(0) { dbg<<"BinnedCorr2 copy constructor\n"; _xi.new_data(_nbins); _meanr = new double[_nbins]; _meanlogr = new double[_nbins]; _weight = new double[_nbins]; _npairs = new double[_nbins]; if (copy_data) *this = rhs; else clear(); } template <int D1, int D2, int B> BinnedCorr2<D1,D2,B>::~BinnedCorr2() { dbg<<"BinnedCorr2 destructor\n"; if (_owns_data) { _xi.delete_data(_nbins); delete [] _meanr; _meanr = 0; delete [] _meanlogr; _meanlogr = 0; delete [] _weight; _weight = 0; delete [] _npairs; _npairs = 0; } } // BinnedCorr2::process2 is invalid if D1 != D2, so this helper struct lets us only call // process2 when D1 == D2. template <int D1, int D2, int B, int C, int M> struct ProcessHelper { static void process2(BinnedCorr2<D1,D2,B>& , const Cell<D1,C>&, const MetricHelper<M>& ) {} }; template <int D, int B, int C, int M> struct ProcessHelper<D,D,B,C,M> { static void process2(BinnedCorr2<D,D,B>& b, const Cell<D,C>& c12, const MetricHelper<M>& m) { b.template process2<C,M>(c12, m); } }; template <int D1, int D2, int B> void BinnedCorr2<D1,D2,B>::clear() { _xi.clear(_nbins); for (int i=0; i<_nbins; ++i) _meanr[i] = 0.; for (int i=0; i<_nbins; ++i) _meanlogr[i] = 0.; for (int i=0; i<_nbins; ++i) _weight[i] = 0.; for (int i=0; i<_nbins; ++i) _npairs[i] = 0.; _coords = -1; } template <int D1, int D2, int B> template <int C, int M> void BinnedCorr2<D1,D2,B>::process(const Field<D1,C>& field, bool dots) { xdbg<<"Start process (auto): M,C = "<<M<<" "<<C<<std::endl; Assert(D1 == D2); Assert(_coords == -1 || _coords == C); _coords = C; const long n1 = field.getNTopLevel(); dbg<<"field has "<<n1<<" top level nodes\n"; Assert(n1 > 0); #ifdef _OPENMP #pragma omp parallel { // Give each thread their own copy of the data vector to fill in. BinnedCorr2<D1,D2,B> bc2(*this,false); #else BinnedCorr2<D1,D2,B>& bc2 = *this; #endif // Inside the omp parallel, so each thread has its own MetricHelper. MetricHelper<M> metric(_minrpar, _maxrpar, _xp, _yp, _zp); #ifdef _OPENMP #pragma omp for schedule(dynamic) #endif for (int i=0;i<n1;++i) { #ifdef _OPENMP #pragma omp critical #endif { #ifdef _OPENMP xdbg<<omp_get_thread_num()<<" "<<i<<std::endl; #endif if (dots) std::cout<<'.'<<std::flush; } const Cell<D1,C>& c1 = *field.getCells()[i]; ProcessHelper<D1,D2,B,C,M>::process2(bc2, c1, metric); for (int j=i+1;j<n1;++j) { const Cell<D1,C>& c2 = *field.getCells()[j]; bc2.process11<C,M>(c1, c2, metric, BinTypeHelper<B>::doReverse()); } } #ifdef _OPENMP // Accumulate the results #pragma omp critical { *this += bc2; } } #endif if (dots) std::cout<<std::endl; } template <int D1, int D2, int B> template <int C, int M> void BinnedCorr2<D1,D2,B>::process(const Field<D1,C>& field1, const Field<D2,C>& field2, bool dots) { xdbg<<"Start process (cross): M,C = "<<M<<" "<<C<<std::endl; Assert(_coords == -1 || _coords == C); _coords = C; const long n1 = field1.getNTopLevel(); const long n2 = field2.getNTopLevel(); dbg<<"field1 has "<<n1<<" top level nodes\n"; dbg<<"field2 has "<<n2<<" top level nodes\n"; Assert(n1 > 0); Assert(n2 > 0); #ifdef _OPENMP #pragma omp parallel { // Give each thread their own copy of the data vector to fill in. BinnedCorr2<D1,D2,B> bc2(*this,false); #else BinnedCorr2<D1,D2,B>& bc2 = *this; #endif MetricHelper<M> metric(_minrpar, _maxrpar, _xp, _yp, _zp); #ifdef _OPENMP #pragma omp for schedule(dynamic) #endif for (int i=0;i<n1;++i) { #ifdef _OPENMP #pragma omp critical #endif { #ifdef _OPENMP xdbg<<omp_get_thread_num()<<" "<<i<<std::endl; #endif if (dots) std::cout<<'.'<<std::flush; } const Cell<D1,C>& c1 = *field1.getCells()[i]; for (int j=0;j<n2;++j) { const Cell<D2,C>& c2 = *field2.getCells()[j]; bc2.process11<C,M>(c1, c2, metric, false); } } #ifdef _OPENMP // Accumulate the results #pragma omp critical { *this += bc2; } } #endif if (dots) std::cout<<std::endl; } template <int D1, int D2, int B> template <int C, int M> void BinnedCorr2<D1,D2,B>::processPairwise( const SimpleField<D1,C>& field1, const SimpleField<D2,C>& field2, bool dots) { Assert(_coords == -1 || _coords == C); _coords = C; const long nobj = field1.getNObj(); const long nobj2 = field2.getNObj(); xdbg<<"field1 has "<<nobj<<" objects\n"; xdbg<<"field2 has "<<nobj2<<" objects\n"; Assert(nobj > 0); Assert(nobj == nobj2); const long sqrtn = long(sqrt(double(nobj))); #ifdef _OPENMP #pragma omp parallel { // Give each thread their own copy of the data vector to fill in. BinnedCorr2<D1,D2,B> bc2(*this,false); #else BinnedCorr2<D1,D2,B>& bc2 = *this; #endif MetricHelper<M> metric(_minrpar, _maxrpar, _xp, _yp, _zp); #ifdef _OPENMP #pragma omp for schedule(static) #endif for (long i=0;i<nobj;++i) { // Let the progress dots happen every sqrt(n) iterations. if (dots && (i % sqrtn == 0)) { #ifdef _OPENMP #pragma omp critical #endif { #ifdef _OPENMP xdbg<<omp_get_thread_num()<<" "<<i<<std::endl; #endif std::cout<<'.'<<std::flush; } } const Cell<D1,C>& c1 = *field1.getCells()[i]; const Cell<D2,C>& c2 = *field2.getCells()[i]; const Position<C>& p1 = c1.getPos(); const Position<C>& p2 = c2.getPos(); double s=0.; const double rsq = metric.DistSq(p1, p2, s, s); if (BinTypeHelper<B>::isRSqInRange(rsq, p1, p2, _minsep, _minsepsq, _maxsep, _maxsepsq)) { bc2.template directProcess11(c1,c2,rsq,false); } } #ifdef _OPENMP // Accumulate the results #pragma omp critical { *this += bc2; } } #endif if (dots) std::cout<<std::endl; } template <int D1, int D2, int B> template <int C, int M> void BinnedCorr2<D1,D2,B>::process2(const Cell<D1,C>& c12, const MetricHelper<M>& metric) { if (c12.getW() == 0.) return; if (c12.getSize() <= _halfminsep) return; Assert(c12.getLeft()); Assert(c12.getRight()); process2<C,M>(*c12.getLeft(), metric); process2<C,M>(*c12.getRight(), metric); process11<C,M>(*c12.getLeft(), *c12.getRight(), metric, BinTypeHelper<B>::doReverse()); } template <int D1, int D2, int B> template <int C, int M> void BinnedCorr2<D1,D2,B>::process11(const Cell<D1,C>& c1, const Cell<D2,C>& c2, const MetricHelper<M>& metric, bool do_reverse) { //set_verbose(2); xdbg<<"Start process11 for "<<c1.getPos()<<", "<<c2.getPos()<<" "; xdbg<<"w = "<<c1.getW()<<", "<<c2.getW()<<std::endl; if (c1.getW() == 0. || c2.getW() == 0.) return; const Position<C>& p1 = c1.getPos(); const Position<C>& p2 = c2.getPos(); double s1 = c1.getSize(); // May be modified by DistSq function. double s2 = c2.getSize(); // " xdbg<<"s1,s2 = "<<s1<<','<<s2<<std::endl; xdbg<<"M,C = "<<M<<" "<<C<<std::endl; const double rsq = metric.DistSq(p1,p2,s1,s2); xdbg<<"rsq = "<<rsq<<std::endl; xdbg<<"s1,s2 => "<<s1<<','<<s2<<std::endl; const double s1ps2 = s1+s2; double rpar = 0; // Gets set to correct value by this function if appropriate if (metric.isRParOutsideRange(p1, p2, s1ps2, rpar)) { return; } xdbg<<"RPar in range\n"; if (BinTypeHelper<B>::tooSmallDist(rsq, s1ps2, _minsep, _minsepsq) && metric.tooSmallDist(p1, p2, rsq, rpar, s1ps2, _minsep, _minsepsq)) { return; } xdbg<<"Not too small separation\n"; if (BinTypeHelper<B>::tooLargeDist(rsq, s1ps2, _maxsep, _maxsepsq) && metric.tooLargeDist(p1, p2, rsq, rpar, s1ps2, _fullmaxsep, _fullmaxsepsq)) { return; } xdbg<<"Not too large separation\n"; // Now check if these cells are small enough that it is ok to drop into a single bin. int k=-1; double r=0,logr=0; // If singleBin is true, these values are set for use by directProcess11 if (metric.isRParInsideRange(p1, p2, s1ps2, rpar) && BinTypeHelper<B>::singleBin(rsq, s1ps2, p1, p2, _binsize, _b, _bsq, _minsep, _maxsep, _logminsep, k, r, logr)) { xdbg<<"Drop into single bin.\n"; if (BinTypeHelper<B>::isRSqInRange(rsq, p1, p2, _minsep, _minsepsq, _maxsep, _maxsepsq)) { directProcess11(c1,c2,rsq,do_reverse,k,r,logr); } } else { xdbg<<"Need to split.\n"; bool split1=false, split2=false; double bsq_eff = BinTypeHelper<B>::getEffectiveBSq(rsq,_bsq); xdbg<<"bsq_eff = "<<bsq_eff<<std::endl; CalcSplitSq(split1,split2,s1,s2,s1ps2,bsq_eff); xdbg<<"rsq = "<<rsq<<", s1ps2 = "<<s1ps2<<" "; xdbg<<"s1ps2 / r = "<<s1ps2 / sqrt(rsq)<<", b = "<<_b<<" "; xdbg<<"split = "<<split1<<','<<split2<<std::endl; if (split1 && split2) { Assert(c1.getLeft()); Assert(c1.getRight()); Assert(c2.getLeft()); Assert(c2.getRight()); process11<C,M>(*c1.getLeft(),*c2.getLeft(),metric,do_reverse); process11<C,M>(*c1.getLeft(),*c2.getRight(),metric,do_reverse); process11<C,M>(*c1.getRight(),*c2.getLeft(),metric,do_reverse); process11<C,M>(*c1.getRight(),*c2.getRight(),metric,do_reverse); } else if (split1) { Assert(c1.getLeft()); Assert(c1.getRight()); process11<C,M>(*c1.getLeft(),c2,metric,do_reverse); process11<C,M>(*c1.getRight(),c2,metric,do_reverse); } else { Assert(split2); Assert(c2.getLeft()); Assert(c2.getRight()); process11<C,M>(c1,*c2.getLeft(),metric,do_reverse); process11<C,M>(c1,*c2.getRight(),metric,do_reverse); } } } // We also set up a helper class for doing the direct processing template <int D1, int D2> struct DirectHelper; template <> struct DirectHelper<NData,NData> { template <int C> static void ProcessXi( const Cell<NData,C>& , const Cell<NData,C>& , const double , XiData<NData,NData>& , int, int ) {} }; template <> struct DirectHelper<NData,KData> { template <int C> static void ProcessXi( const Cell<NData,C>& c1, const Cell<KData,C>& c2, const double , XiData<NData,KData>& xi, int k, int ) { xi.xi[k] += c1.getW() * c2.getData().getWK(); } }; template <> struct DirectHelper<NData,GData> { template <int C> static void ProcessXi( const Cell<NData,C>& c1, const Cell<GData,C>& c2, const double rsq, XiData<NData,GData>& xi, int k, int ) { std::complex<double> g2; ProjectHelper<C>::ProjectShear(c1,c2,g2); // The minus sign here is to make it accumulate tangential shear, rather than radial. // g2 from the above ProjectShear is measured along the connecting line, not tangent. g2 *= -c1.getW(); xi.xi[k] += real(g2); xi.xi_im[k] += imag(g2); } }; template <> struct DirectHelper<KData,KData> { template <int C> static void ProcessXi( const Cell<KData,C>& c1, const Cell<KData,C>& c2, const double , XiData<KData,KData>& xi, int k, int k2) { double wkk = c1.getData().getWK() * c2.getData().getWK(); xi.xi[k] += wkk; if (k2 != -1) xi.xi[k2] += wkk; } }; template <> struct DirectHelper<KData,GData> { template <int C> static void ProcessXi( const Cell<KData,C>& c1, const Cell<GData,C>& c2, const double rsq, XiData<KData,GData>& xi, int k, int ) { std::complex<double> g2; ProjectHelper<C>::ProjectShear(c1,c2,g2); // The minus sign here is to make it accumulate tangential shear, rather than radial. // g2 from the above ProjectShear is measured along the connecting line, not tangent. g2 *= -c1.getData().getWK(); xi.xi[k] += real(g2); xi.xi_im[k] += imag(g2); } }; template <> struct DirectHelper<GData,GData> { template <int C> static void ProcessXi( const Cell<GData,C>& c1, const Cell<GData,C>& c2, const double rsq, XiData<GData,GData>& xi, int k, int k2) { std::complex<double> g1, g2; ProjectHelper<C>::ProjectShears(c1,c2,g1,g2); // The complex products g1 g2 and g1 g2* share most of the calculations, // so faster to do this manually. double g1rg2r = g1.real() * g2.real(); double g1rg2i = g1.real() * g2.imag(); double g1ig2r = g1.imag() * g2.real(); double g1ig2i = g1.imag() * g2.imag(); xi.xip[k] += g1rg2r + g1ig2i; // g1 * conj(g2) xi.xip_im[k] += g1ig2r - g1rg2i; xi.xim[k] += g1rg2r - g1ig2i; // g1 * g2 xi.xim_im[k] += g1ig2r + g1rg2i; if (k2 != -1) { xi.xip[k2] += g1rg2r + g1ig2i; // g1 * conj(g2) xi.xip_im[k2] += g1ig2r - g1rg2i; xi.xim[k2] += g1rg2r - g1ig2i; // g1 * g2 xi.xim_im[k2] += g1ig2r + g1rg2i; } } }; template <int D1, int D2, int B> template <int C> void BinnedCorr2<D1,D2,B>::directProcess11( const Cell<D1,C>& c1, const Cell<D2,C>& c2, const double rsq, bool do_reverse, int k, double r, double logr) { xdbg<<"DirectProcess11: rsq = "<<rsq<<std::endl; XAssert(rsq >= _minsepsq); XAssert(rsq < _fullmaxsepsq); // Note that most of these XAsserts around are still hardcoded for Log binning and Euclidean // metric. If turning on verbose>=3, these could fail. XAssert(c1.getSize()+c2.getSize() < sqrt(rsq)*_b + 0.0001); XAssert(_binsize != 0.); const Position<C>& p1 = c1.getPos(); const Position<C>& p2 = c2.getPos(); if (k < 0) { r = sqrt(rsq); logr = log(r); Assert(logr >= _logminsep); k = BinTypeHelper<B>::calculateBinK(p1, p2, r, logr, _binsize, _minsep, _maxsep, _logminsep); } else { XAssert(std::abs(r - sqrt(rsq)) < 1.e-10*r); XAssert(std::abs(logr - 0.5*log(rsq)) < 1.e-10); XAssert(k == BinTypeHelper<B>::calculateBinK(p1, p2, r, logr, _binsize, _minsep, _maxsep, _logminsep)); } Assert(k >= 0); Assert(k < _nbins); xdbg<<"r,logr,k = "<<r<<','<<logr<<','<<k<<std::endl; double nn = double(c1.getN()) * double(c2.getN()); _npairs[k] += nn; double ww = double(c1.getW()) * double(c2.getW()); _meanr[k] += ww * r; _meanlogr[k] += ww * logr; _weight[k] += ww; xdbg<<"n,w = "<<nn<<','<<ww<<" ==> "<<_npairs[k]<<','<<_weight[k]<<std::endl; int k2 = -1; if (do_reverse) { k2 = BinTypeHelper<B>::calculateBinK(p2, p1, r, logr, _binsize, _minsep, _maxsep, _logminsep); Assert(k2 >= 0); Assert(k2 < _nbins); _npairs[k2] += nn; _meanr[k2] += ww * r; _meanlogr[k2] += ww * logr; _weight[k2] += ww; } DirectHelper<D1,D2>::template ProcessXi<C>(c1,c2,rsq,_xi,k,k2); } template <int D1, int D2, int B> void BinnedCorr2<D1,D2,B>::operator=(const BinnedCorr2<D1,D2,B>& rhs) { Assert(rhs._nbins == _nbins); _xi.copy(rhs._xi,_nbins); for (int i=0; i<_nbins; ++i) _meanr[i] = rhs._meanr[i]; for (int i=0; i<_nbins; ++i) _meanlogr[i] = rhs._meanlogr[i]; for (int i=0; i<_nbins; ++i) _weight[i] = rhs._weight[i]; for (int i=0; i<_nbins; ++i) _npairs[i] = rhs._npairs[i]; } template <int D1, int D2, int B> void BinnedCorr2<D1,D2,B>::operator+=(const BinnedCorr2<D1,D2,B>& rhs) { Assert(rhs._nbins == _nbins); _xi.add(rhs._xi,_nbins); for (int i=0; i<_nbins; ++i) _meanr[i] += rhs._meanr[i]; for (int i=0; i<_nbins; ++i) _meanlogr[i] += rhs._meanlogr[i]; for (int i=0; i<_nbins; ++i) _weight[i] += rhs._weight[i]; for (int i=0; i<_nbins; ++i) _npairs[i] += rhs._npairs[i]; } template <int D1, int D2, int B> template <int C, int M> long BinnedCorr2<D1,D2,B>::samplePairs( const Field<D1, C>& field1, const Field<D2, C>& field2, double minsep, double maxsep, long* i1, long* i2, double* sep, int n) { Assert(_coords == -1 || _coords == C); _coords = C; const long n1 = field1.getNTopLevel(); const long n2 = field2.getNTopLevel(); dbg<<"field1 has "<<n1<<" top level nodes\n"; dbg<<"field2 has "<<n2<<" top level nodes\n"; Assert(n1 > 0); Assert(n2 > 0); MetricHelper<M> metric(_minrpar, _maxrpar, _xp, _yp, _zp); double minsepsq = minsep*minsep; double maxsepsq = maxsep*maxsep; long k=0; for (int i=0;i<n1;++i) { const Cell<D1,C>& c1 = *field1.getCells()[i]; for (int j=0;j<n2;++j) { const Cell<D2,C>& c2 = *field2.getCells()[j]; samplePairs(c1, c2, metric, minsep, minsepsq, maxsep, maxsepsq, i1, i2, sep, n, k); } } return k; } template <int D1, int D2, int B> template <int C, int M> void BinnedCorr2<D1,D2,B>::samplePairs( const Cell<D1, C>& c1, const Cell<D2, C>& c2, const MetricHelper<M>& metric, double minsep, double minsepsq, double maxsep, double maxsepsq, long* i1, long* i2, double* sep, int n, long& k) { // This tracks process11, but we only select pairs at the end, not call directProcess11 xdbg<<"Start samplePairs for "<<c1.getPos()<<", "<<c2.getPos()<<" "; xdbg<<"w = "<<c1.getW()<<", "<<c2.getW()<<std::endl; if (c1.getW() == 0. || c2.getW() == 0.) return; const Position<C>& p1 = c1.getPos(); const Position<C>& p2 = c2.getPos(); double s1 = c1.getSize(); // May be modified by DistSq function. double s2 = c2.getSize(); // " xdbg<<"s1,s2 = "<<s1<<','<<s2<<std::endl; xdbg<<"M,C = "<<M<<" "<<C<<std::endl; const double rsq = metric.DistSq(p1, p2, s1, s2); xdbg<<"rsq = "<<rsq<<std::endl; xdbg<<"s1,s2 => "<<s1<<','<<s2<<std::endl; const double s1ps2 = s1+s2; double rpar = 0; // Gets set to correct value by this function if appropriate if (metric.isRParOutsideRange(p1, p2, s1ps2, rpar)) { return; } xdbg<<"RPar in range\n"; if (BinTypeHelper<B>::tooSmallDist(rsq, s1ps2, minsep, minsepsq) && metric.tooSmallDist(p1, p2, rsq, rpar, s1ps2, minsep, minsepsq)) { return; } xdbg<<"Not too small separation\n"; if (BinTypeHelper<B>::tooLargeDist(rsq, s1ps2, maxsep, maxsepsq) && metric.tooLargeDist(p1, p2, rsq, rpar, s1ps2, maxsep, maxsepsq)) { return; } xdbg<<"Not too large separation\n"; // Now check if these cells are small enough that it is ok to drop into a single bin. int kk=-1; double r=0,logr=0; // If singleBin is true, these values are set for use by directProcess11 if (metric.isRParInsideRange(p1, p2, s1ps2, rpar) && BinTypeHelper<B>::singleBin(rsq, s1ps2, p1, p2, _binsize, _b, _bsq, _minsep, _maxsep, _logminsep, kk, r, logr)) { xdbg<<"Drop into single bin.\n"; xdbg<<"rsq = "<<rsq<<std::endl; xdbg<<"minsepsq = "<<minsepsq<<std::endl; xdbg<<"maxsepsq = "<<maxsepsq<<std::endl; if (BinTypeHelper<B>::isRSqInRange(rsq, p1, p2, minsep, minsepsq, maxsep, maxsepsq)) { sampleFrom(c1,c2,rsq,r,i1,i2,sep,n,k); } } else { xdbg<<"Need to split.\n"; bool split1=false, split2=false; double bsq_eff = BinTypeHelper<B>::getEffectiveBSq(rsq,_bsq); CalcSplitSq(split1,split2,s1,s2,s1ps2,bsq_eff); xdbg<<"rsq = "<<rsq<<", s1ps2 = "<<s1ps2<<" "; xdbg<<"s1ps2 / r = "<<s1ps2 / sqrt(rsq)<<", b = "<<_b<<" "; xdbg<<"split = "<<split1<<','<<split2<<std::endl; if (split1 && split2) { Assert(c1.getLeft()); Assert(c1.getRight()); Assert(c2.getLeft()); Assert(c2.getRight()); samplePairs<C,M>(*c1.getLeft(), *c2.getLeft(), metric, minsep, minsepsq, maxsep, maxsepsq, i1, i2, sep, n, k); samplePairs<C,M>(*c1.getLeft(), *c2.getRight(), metric, minsep, minsepsq, maxsep, maxsepsq, i1, i2, sep, n, k); samplePairs<C,M>(*c1.getRight(), *c2.getLeft(), metric, minsep, minsepsq, maxsep, maxsepsq, i1, i2, sep, n, k); samplePairs<C,M>(*c1.getRight(), *c2.getRight(), metric, minsep, minsepsq, maxsep, maxsepsq, i1, i2, sep, n, k); } else if (split1) { Assert(c1.getLeft()); Assert(c1.getRight()); samplePairs<C,M>(*c1.getLeft(), c2, metric, minsep, minsepsq, maxsep, maxsepsq, i1, i2, sep, n, k); samplePairs<C,M>(*c1.getRight(), c2, metric, minsep, minsepsq, maxsep, maxsepsq, i1, i2, sep, n, k); } else { Assert(split2); Assert(c2.getLeft()); Assert(c2.getRight()); samplePairs<C,M>(c1, *c2.getLeft(), metric, minsep, minsepsq, maxsep, maxsepsq, i1, i2, sep, n, k); samplePairs<C,M>(c1, *c2.getRight(), metric, minsep, minsepsq, maxsep, maxsepsq, i1, i2, sep, n, k); } } } void SelectRandomFrom(long m, std::vector<long>& selection) { xdbg<<"SelectRandomFrom("<<m<<", "<<selection.size()<<")\n"; long n = selection.size(); // There are two algorithms here. // Floyd's algorithm is efficient for m >> n. // Fisher-Yates is efficient for m not much > n. // I don't know exactly the transition for when Floyd's becomes the better choice. // So I'm somewhat arbitrarily picking 3*n. if (m > 3*n) { dbg<<"Floyd's algorithm\n"; // Floyd's algorithm // O(n) in memory, but slightly more than O(n) in time, especially as m ~ n. std::set<long> selected; while (long(selected.size()) < n) { double urd = rand(); urd /= RAND_MAX; // 0 < urd < 1 long j = long(urd * m); // 0 <= j < m if (j == m) j = m-1; // Just in case. std::pair<std::set<long>::iterator,bool> ret = selected.insert(j); if (ret.second) { // Then insertion happened. I.e. not already present. // Also write it to the end of the selection list selection[selected.size()-1] = j; } } } else { dbg<<"Fisher-Yates\n"; // Fisher-Yates shuffle up through n elements // O(n) in time, but O(m) in memory. std::vector<long> full(m); for (long i=0; i<m; ++i) full[i] = i; for (long i=0; i<n; ++i) { double urd = rand(); urd /= RAND_MAX; // 0 < urd < 1 long j = long(urd * (m-i)); // 0 <= j < m-i j += i; // i <= j < m if (j == m) j = m-1; // Just in case. std::swap(full[i], full[j]); } std::copy(full.begin(), full.begin()+n, selection.begin()); } } template <int D1, int D2, int B> template <int C> void BinnedCorr2<D1,D2,B>::sampleFrom( const Cell<D1, C>& c1, const Cell<D2, C>& c2, double rsq, double r, long* i1, long* i2, double* sep, int n, long& k) { // At the start, k pairs will already have been considered for selection. // Of these min(k,n) will have been selected for inclusion in the lists. // If we consider each pair one at a time, then the algorithm to end up with a // uniform probability that any given pair is selected is as follows. // 1. When k < n, always select the next pair. // 2. When k >= n, select the next pair with probability n/(k+1). // 3. If selected, replace a random pair currently in the list with the new pair. // Proof that for all k >= n, all pairs fromm i=1..k have P(selected) = n/k: // // 1. If k==n, then all items are selected with probability 1 = n/k. // 2. If true for some k>=n, then for step k+1: // - probability for i=k+1 is n/(k+1) // - probability for i<=k is // P(already selected) * P(remains in list | alread selected) // = n/k * (P(i=k+1 not selected) + P(i=k+1 is selected, but given pair is not replaced)) // = n/k * ( (1 - n/(k+1)) + n/(k+1) * (n-1)/n ) // = n/k * ( (k+1 - n + n-1)/(k+1) ) // = n/k * ( k/(k+1) ) // = n/(k+1) // QED // In practice, we usually have many pairs to add, not just one at a time. So we want to // try to do the net result of m passes of the above algorithm. // Consider 3 cases: // 1. k+m<=n: Take all m pairs // 2. m<=n: Just do m passes of the above algorithm. // 3. k+m>n and m>n: Choose n pairs randomly without replacement from full k+m set. // For the selected pairs with k<=i<k+m, either place in the next spot // (if k<n) or randomly replace one of the ones that was already there. long n1 = c1.getN(); long n2 = c2.getN(); long m = n1 * n2; std::vector<const Cell<D1,C>*> leaf1 = c1.getAllLeaves(); std::vector<const Cell<D2,C>*> leaf2 = c2.getAllLeaves(); if (r == 0.) { r = sqrt(rsq); } else { XAssert(std::abs(r - sqrt(rsq)) < 1.e-10*r); } xdbg<<"sampleFrom: "<<c1.getN()<<" "<<c2.getN()<<" "<<rsq<<" "<<r<<std::endl; xdbg<<" n1,n2,k,n,m = "<<n1<<','<<n2<<','<<k<<','<<n<<','<<m<<std::endl; if (k + m <= n) { // Case 1 xdbg<<"Case 1: take all pairs\n"; for (size_t p1=0; p1<leaf1.size(); ++p1) { int nn1 = leaf1[p1]->getN(); for (int q1=0; q1<nn1; ++q1) { int index1; if (nn1 == 1) index1 = leaf1[p1]->getInfo().index; else index1 = (*leaf1[p1]->getListInfo().indices)[q1]; for (size_t p2=0; p2<leaf2.size(); ++p2) { int nn2 = leaf2[p2]->getN(); for (int q2=0; q2<nn2; ++q2) { int index2; if (nn2 == 1) index2 = leaf2[p2]->getInfo().index; else index2 = (*leaf2[p2]->getListInfo().indices)[q2]; i1[k] = index1; i2[k] = index2; sep[k] = r; ++k; } } } } } else if (m <= n) { // Case 2 xdbg<<"Case 2: Check one at a time.\n"; for (size_t p1=0; p1<leaf1.size(); ++p1) { int nn1 = leaf1[p1]->getN(); for (int q1=0; q1<nn1; ++q1) { int index1; if (nn1 == 1) index1 = leaf1[p1]->getInfo().index; else index1 = (*leaf1[p1]->getListInfo().indices)[q1]; for (size_t p2=0; p2<leaf2.size(); ++p2) { int nn2 = leaf2[p2]->getN(); for (int q2=0; q2<nn2; ++q2) { int index2; if (nn2 == 1) index2 = leaf2[p2]->getInfo().index; else index2 = (*leaf2[p2]->getListInfo().indices)[q2]; int j = k; // j is where in the lists we will place this if (k >= n) { double urd = rand(); urd /= RAND_MAX; // 0 < urd < 1 j = int(urd * (k+1)); // 0 <= j < k+1 } if (j < n) { i1[j] = index1; i2[j] = index2; sep[j] = r; } ++k; } } } } } else { // Case 3 xdbg<<"Case 3: Select n without replacement\n"; std::vector<long> selection(n); SelectRandomFrom(k+m, selection); // If any items in k<=i<n are from the original set, put them in their original place. for(int i=k;i<n;++i) { int j = selection[i]; if (j < n) std::swap(selection[i], selection[j]); } // Now any items with j >= k can replace the value at their i in this list. std::map<long, long> places; for(int i=0;i<n;++i) { int j = selection[i]; if (j >= k) places[j] = i; } if (places.size() == 0) { // If nothing selected from the new set, then we're done. k += m; return; } std::map<long, long>::iterator next = places.begin(); int i=k; // When i is in the map, place it at places[i] for (size_t p1=0; p1<leaf1.size(); ++p1) { int nn1 = leaf1[p1]->getN(); for (int q1=0; q1<nn1; ++q1) { xdbg<<"i = "<<i<<", next = "<<next->first<<" "<<next->second<<std::endl; Assert(i <= next->first); if (next->first > i + n2) { // Then skip this loop through the second vector i += n2; continue; } int index1; if (nn1 == 1) index1 = leaf1[p1]->getInfo().index; else index1 = (*leaf1[p1]->getListInfo().indices)[q1]; for (size_t p2=0; p2<leaf2.size(); ++p2) { int nn2 = leaf2[p2]->getN(); for (int q2=0; q2<nn2; ++q2,++i) { if (i == next->first) { xdbg<<"Use i = "<<i<<std::endl; int index2; if (nn2 == 1) index2 = leaf2[p2]->getInfo().index; else index2 = (*leaf2[p2]->getListInfo().indices)[q2]; long j = next->second; i1[j] = index1; i2[j] = index2; sep[j] = r; ++next; } if (next == places.end()) break; } if (next == places.end()) break; } if (next == places.end()) break; } if (next == places.end()) break; } xdbg<<"Done: i = "<<i<<", k+m = "<<k+m<<std::endl; k += m; } } // // // The C interface for python // // extern "C" { #include "BinnedCorr2_C.h" } template <int D1, int D2> void* BuildCorr2b(int bin_type, double minsep, double maxsep, int nbins, double binsize, double b, double minrpar, double maxrpar, double xp, double yp, double zp, double* xi0, double* xi1, double* xi2, double* xi3, double* meanr, double* meanlogr, double* weight, double* npairs) { switch(bin_type) { case Log: return static_cast<void*>(new BinnedCorr2<D1,D2,Log>( minsep, maxsep, nbins, binsize, b, minrpar, maxrpar, xp, yp, zp, xi0, xi1, xi2, xi3, meanr, meanlogr, weight, npairs)); break; case Linear: return static_cast<void*>(new BinnedCorr2<D1,D2,Linear>( minsep, maxsep, nbins, binsize, b, minrpar, maxrpar, xp, yp, zp, xi0, xi1, xi2, xi3, meanr, meanlogr, weight, npairs)); break; case TwoD: return static_cast<void*>(new BinnedCorr2<D1,D2,TwoD>( minsep, maxsep, nbins, binsize, b, minrpar, maxrpar, xp, yp, zp, xi0, xi1, xi2, xi3, meanr, meanlogr, weight, npairs)); break; default: Assert(false); } return 0; } template <int D1> void* BuildCorr2a(int d2, int bin_type, double minsep, double maxsep, int nbins, double binsize, double b, double minrpar, double maxrpar, double xp, double yp, double zp, double* xi0, double* xi1, double* xi2, double* xi3, double* meanr, double* meanlogr, double* weight, double* npairs) { // Note: we only ever call this with d2 >= d1, so the MAX bit below is equivalent to // just using d2 for the cases that actually get called, but doing this saves some // compile time and some size in the final library from not instantiating templates // that aren't needed. switch(d2) { case NData: return BuildCorr2b<D1,MAX(D1,NData)>(bin_type, minsep, maxsep, nbins, binsize, b, minrpar, maxrpar, xp, yp, zp, xi0, xi1, xi2, xi3, meanr, meanlogr, weight, npairs); break; case KData: return BuildCorr2b<D1,MAX(D1,KData)>(bin_type, minsep, maxsep, nbins, binsize, b, minrpar, maxrpar, xp, yp, zp, xi0, xi1, xi2, xi3, meanr, meanlogr, weight, npairs); break; case GData: return BuildCorr2b<D1,MAX(D1,GData)>(bin_type, minsep, maxsep, nbins, binsize, b, minrpar, maxrpar, xp, yp, zp, xi0, xi1, xi2, xi3, meanr, meanlogr, weight, npairs); break; default: Assert(false); } return 0; } void* BuildCorr2(int d1, int d2, int bin_type, double minsep, double maxsep, int nbins, double binsize, double b, double minrpar, double maxrpar, double xp, double yp, double zp, double* xi0, double* xi1, double* xi2, double* xi3, double* meanr, double* meanlogr, double* weight, double* npairs) { dbg<<"Start BuildCorr2: "<<d1<<" "<<d2<<" "<<bin_type<<std::endl; void* corr=0; switch(d1) { case NData: corr = BuildCorr2a<NData>(d2, bin_type, minsep, maxsep, nbins, binsize, b, minrpar, maxrpar, xp, yp, zp, xi0, xi1, xi2, xi3, meanr, meanlogr, weight, npairs); break; case KData: corr = BuildCorr2a<KData>(d2, bin_type, minsep, maxsep, nbins, binsize, b, minrpar, maxrpar, xp, yp, zp, xi0, xi1, xi2, xi3, meanr, meanlogr, weight, npairs); break; case GData: corr = BuildCorr2a<GData>(d2, bin_type, minsep, maxsep, nbins, binsize, b, minrpar, maxrpar, xp, yp, zp, xi0, xi1, xi2, xi3, meanr, meanlogr, weight, npairs); break; default: Assert(false); } xdbg<<"corr = "<<corr<<std::endl; return corr; } template <int D1, int D2> void DestroyCorr2b(void* corr, int bin_type) { switch(bin_type) { case Log: delete static_cast<BinnedCorr2<D1,D2,Log>*>(corr); break; case Linear: delete static_cast<BinnedCorr2<D1,D2,Linear>*>(corr); break; case TwoD: delete static_cast<BinnedCorr2<D1,D2,TwoD>*>(corr); break; default: Assert(false); } } template <int D1> void DestroyCorr2a(void* corr, int d2, int bin_type) { switch(d2) { case NData: DestroyCorr2b<D1,MAX(D1,NData)>(corr, bin_type); break; case KData: DestroyCorr2b<D1,MAX(D1,KData)>(corr, bin_type); break; case GData: DestroyCorr2b<D1,MAX(D1,GData)>(corr, bin_type); break; default: Assert(false); } } void DestroyCorr2(void* corr, int d1, int d2, int bin_type) { dbg<<"Start DestroyCorr2: "<<d1<<" "<<d2<<" "<<bin_type<<std::endl; xdbg<<"corr = "<<corr<<std::endl; switch(d1) { case NData: DestroyCorr2a<NData>(corr, d2, bin_type); break; case KData: DestroyCorr2a<KData>(corr, d2, bin_type); break; case GData: DestroyCorr2a<GData>(corr, d2, bin_type); break; default: Assert(false); } } template <int M, int D, int B> void ProcessAuto2d(BinnedCorr2<D,D,B>* corr, void* field, int dots, int coords) { switch(coords) { case Flat: Assert(MetricHelper<M>::_Flat == int(Flat)); corr->template process<MetricHelper<M>::_Flat, M>( *static_cast<Field<D,MetricHelper<M>::_Flat>*>(field), dots); break; case Sphere: Assert(MetricHelper<M>::_Sphere == int(Sphere)); corr->template process<MetricHelper<M>::_Sphere, M>( *static_cast<Field<D,MetricHelper<M>::_Sphere>*>(field), dots); break; case ThreeD: Assert(MetricHelper<M>::_ThreeD == int(ThreeD)); corr->template process<MetricHelper<M>::_ThreeD, M>( *static_cast<Field<D,MetricHelper<M>::_ThreeD>*>(field), dots); break; default: Assert(false); } } template <int D, int B> void ProcessAuto2c(BinnedCorr2<D,D,B>* corr, void* field, int dots, int coords, int metric) { switch(metric) { case Euclidean: ProcessAuto2d<Euclidean>(corr, field, dots, coords); break; case Rperp: ProcessAuto2d<Rperp>(corr, field, dots, coords); break; case OldRperp: ProcessAuto2d<OldRperp>(corr, field, dots, coords); break; case Rlens: ProcessAuto2d<Rlens>(corr, field, dots, coords); break; case Arc: ProcessAuto2d<Arc>(corr, field, dots, coords); break; case Periodic: ProcessAuto2d<Periodic>(corr, field, dots, coords); break; default: Assert(false); } } template <int D> void ProcessAuto2b(void* corr, void* field, int dots, int coords, int bin_type, int metric) { switch(bin_type) { case Log: ProcessAuto2c(static_cast<BinnedCorr2<D,D,Log>*>(corr), field, dots, coords, metric); break; case Linear: ProcessAuto2c(static_cast<BinnedCorr2<D,D,Linear>*>(corr), field, dots, coords, metric); break; case TwoD: ProcessAuto2c(static_cast<BinnedCorr2<D,D,TwoD>*>(corr), field, dots, coords, metric); break; default: Assert(false); } } void ProcessAuto2(void* corr, void* field, int dots, int d, int coords, int bin_type, int metric) { dbg<<"Start ProcessAuto2: "<<d<<" "<<coords<<" "<<bin_type<<" "<<metric<<std::endl; switch(d) { case NData: ProcessAuto2b<NData>(corr, field, dots, coords, bin_type, metric); break; case KData: ProcessAuto2b<KData>(corr, field, dots, coords, bin_type, metric); break; case GData: ProcessAuto2b<GData>(corr, field, dots, coords, bin_type, metric); break; default: Assert(false); } } template <int M, int D1, int D2, int B> void ProcessCross2d(BinnedCorr2<D1,D2,B>* corr, void* field1, void* field2, int dots, int coords) { switch(coords) { case Flat: Assert(MetricHelper<M>::_Flat == int(Flat)); corr->template process<MetricHelper<M>::_Flat, M>( *static_cast<Field<D1,MetricHelper<M>::_Flat>*>(field1), *static_cast<Field<D2,MetricHelper<M>::_Flat>*>(field2), dots); break; case Sphere: Assert(MetricHelper<M>::_Sphere == int(Sphere)); corr->template process<MetricHelper<M>::_Sphere, M>( *static_cast<Field<D1,MetricHelper<M>::_Sphere>*>(field1), *static_cast<Field<D2,MetricHelper<M>::_Sphere>*>(field2), dots); break; case ThreeD: Assert(MetricHelper<M>::_ThreeD == int(ThreeD)); corr->template process<MetricHelper<M>::_ThreeD, M>( *static_cast<Field<D1,MetricHelper<M>::_ThreeD>*>(field1), *static_cast<Field<D2,MetricHelper<M>::_ThreeD>*>(field2), dots); break; default: Assert(false); } } template <int D1, int D2, int B> void ProcessCross2c(BinnedCorr2<D1,D2,B>* corr, void* field1, void* field2, int dots, int coords, int metric) { switch(metric) { case Euclidean: ProcessCross2d<Euclidean>(corr, field1, field2, dots, coords); break; case Rperp: ProcessCross2d<Rperp>(corr, field1, field2, dots, coords); break; case OldRperp: ProcessCross2d<OldRperp>(corr, field1, field2, dots, coords); break; case Rlens: ProcessCross2d<Rlens>(corr, field1, field2, dots, coords); break; case Arc: ProcessCross2d<Arc>(corr, field1, field2, dots, coords); break; case Periodic: ProcessCross2d<Periodic>(corr, field1, field2, dots, coords); break; default: Assert(false); } } template <int D1, int D2> void ProcessCross2b(void* corr, void* field1, void* field2, int dots, int coords, int bin_type, int metric) { switch(bin_type) { case Log: ProcessCross2c(static_cast<BinnedCorr2<D1,D2,Log>*>(corr), field1, field2, dots, coords, metric); break; case Linear: ProcessCross2c(static_cast<BinnedCorr2<D1,D2,Linear>*>(corr), field1, field2, dots, coords, metric); break; case TwoD: ProcessCross2c(static_cast<BinnedCorr2<D1,D2,TwoD>*>(corr), field1, field2, dots, coords, metric); break; default: Assert(false); } } template <int D1> void ProcessCross2a(void* corr, void* field1, void* field2, int dots, int d2, int coords, int bin_type, int metric) { // Note: we only ever call this with d2 >= d1, so the MAX bit below is equivalent to // just using d2 for the cases that actually get called, but doing this saves some // compile time and some size in the final library from not instantiating templates // that aren't needed. Assert(d2 >= D1); switch(d2) { case NData: ProcessCross2b<D1,MAX(D1,NData)>(corr, field1, field2, dots, coords, bin_type, metric); break; case KData: ProcessCross2b<D1,MAX(D1,KData)>(corr, field1, field2, dots, coords, bin_type, metric); break; case GData: ProcessCross2b<D1,MAX(D1,GData)>(corr, field1, field2, dots, coords, bin_type, metric); break; default: Assert(false); } } void ProcessCross2(void* corr, void* field1, void* field2, int dots, int d1, int d2, int coords, int bin_type, int metric) { dbg<<"Start ProcessCross2: "<<d1<<" "<<d2<<" "<<coords<<" "<<bin_type<<" "<<metric<<std::endl; switch(d1) { case NData: ProcessCross2a<NData>(corr, field1, field2, dots, d2, coords, bin_type, metric); break; case KData: ProcessCross2a<KData>(corr, field1, field2, dots, d2, coords, bin_type, metric); break; case GData: ProcessCross2a<GData>(corr, field1, field2, dots, d2, coords, bin_type, metric); break; default: Assert(false); } } template <int M, int D1, int D2, int B> void ProcessPair2d(BinnedCorr2<D1,D2,B>* corr, void* field1, void* field2, int dots, int coords) { switch(coords) { case Flat: Assert(MetricHelper<M>::_Flat == int(Flat)); corr->template processPairwise<MetricHelper<M>::_Flat, M>( *static_cast<SimpleField<D1,MetricHelper<M>::_Flat>*>(field1), *static_cast<SimpleField<D2,MetricHelper<M>::_Flat>*>(field2), dots); break; case Sphere: Assert(MetricHelper<M>::_Sphere == int(Sphere)); corr->template processPairwise<MetricHelper<M>::_Sphere, M>( *static_cast<SimpleField<D1,MetricHelper<M>::_Sphere>*>(field1), *static_cast<SimpleField<D2,MetricHelper<M>::_Sphere>*>(field2), dots); break; case ThreeD: Assert(MetricHelper<M>::_ThreeD == int(ThreeD)); corr->template processPairwise<MetricHelper<M>::_ThreeD, M>( *static_cast<SimpleField<D1,MetricHelper<M>::_ThreeD>*>(field1), *static_cast<SimpleField<D2,MetricHelper<M>::_ThreeD>*>(field2), dots); break; default: Assert(false); } } template <int D1, int D2, int B> void ProcessPair2c(BinnedCorr2<D1,D2,B>* corr, void* field1, void* field2, int dots, int coords, int metric) { switch(metric) { case Euclidean: ProcessPair2d<Euclidean>(corr, field1, field2, dots, coords); break; case Rperp: ProcessPair2d<Rperp>(corr, field1, field2, dots, coords); break; case OldRperp: ProcessPair2d<OldRperp>(corr, field1, field2, dots, coords); break; case Rlens: ProcessPair2d<Rlens>(corr, field1, field2, dots, coords); break; case Arc: ProcessPair2d<Arc>(corr, field1, field2, dots, coords); break; case Periodic: ProcessPair2d<Periodic>(corr, field1, field2, dots, coords); break; default: Assert(false); } } template <int D1, int D2> void ProcessPair2b(void* corr, void* field1, void* field2, int dots, int coords, int bin_type, int metric) { switch(bin_type) { case Log: ProcessPair2c(static_cast<BinnedCorr2<D1,D2,Log>*>(corr), field1, field2, dots, coords, metric); break; case Linear: ProcessPair2c(static_cast<BinnedCorr2<D1,D2,Linear>*>(corr), field1, field2, dots, coords, metric); break; case TwoD: ProcessPair2c(static_cast<BinnedCorr2<D1,D2,TwoD>*>(corr), field1, field2, dots, coords, metric); break; default: Assert(false); } } template <int D1> void ProcessPair2a(void* corr, void* field1, void* field2, int dots, int d2, int coords, int bin_type, int metric) { Assert(d2 >= D1); switch(d2) { case NData: ProcessPair2b<D1,MAX(D1,NData)>(corr, field1, field2, dots, coords, bin_type, metric); break; case KData: ProcessPair2b<D1,MAX(D1,KData)>(corr, field1, field2, dots, coords, bin_type, metric); break; case GData: ProcessPair2b<D1,MAX(D1,GData)>(corr, field1, field2, dots, coords, bin_type, metric); break; default: Assert(false); } } void ProcessPair(void* corr, void* field1, void* field2, int dots, int d1, int d2, int coords, int bin_type, int metric) { dbg<<"Start ProcessPair: "<<d1<<" "<<d2<<" "<<coords<<" "<<bin_type<<" "<<metric<<std::endl; switch(d1) { case NData: ProcessPair2a<NData>(corr, field1, field2, dots, d2, coords, bin_type, metric); break; case KData: ProcessPair2a<KData>(corr, field1, field2, dots, d2, coords, bin_type, metric); break; case GData: ProcessPair2a<GData>(corr, field1, field2, dots, d2, coords, bin_type, metric); break; default: Assert(false); } } int SetOMPThreads(int num_threads) { #ifdef _OPENMP omp_set_num_threads(num_threads); return omp_get_max_threads(); #else return 1; #endif } template <int M, int D1, int D2, int B> long SamplePairs2d(BinnedCorr2<D1,D2,B>* corr, void* field1, void* field2, double minsep, double maxsep, int coords, long* i1, long* i2, double* sep, int n) { switch(coords) { case Flat: Assert(MetricHelper<M>::_Flat == int(Flat)); return corr->template samplePairs<MetricHelper<M>::_Flat, M>( *static_cast<Field<D1,MetricHelper<M>::_Flat>*>(field1), *static_cast<Field<D2,MetricHelper<M>::_Flat>*>(field2), minsep, maxsep, i1, i2, sep, n); break; case Sphere: Assert(MetricHelper<M>::_Sphere == int(Sphere)); return corr->template samplePairs<MetricHelper<M>::_Sphere, M>( *static_cast<Field<D1,MetricHelper<M>::_Sphere>*>(field1), *static_cast<Field<D2,MetricHelper<M>::_Sphere>*>(field2), minsep, maxsep, i1, i2, sep, n); break; case ThreeD: Assert(MetricHelper<M>::_ThreeD == int(ThreeD)); return corr->template samplePairs<MetricHelper<M>::_ThreeD, M>( *static_cast<Field<D1,MetricHelper<M>::_ThreeD>*>(field1), *static_cast<Field<D2,MetricHelper<M>::_ThreeD>*>(field2), minsep, maxsep, i1, i2, sep, n); break; default: Assert(false); } return 0; } template <int D1, int D2, int B> long SamplePairs2c(BinnedCorr2<D1,D2,B>* corr, void* field1, void* field2, double minsep, double maxsep, int coords, int metric, long* i1, long* i2, double* sep, int n) { switch(metric) { case Euclidean: return SamplePairs2d<Euclidean>(corr, field1, field2, minsep, maxsep, coords, i1, i2, sep, n); break; case Rperp: return SamplePairs2d<Rperp>(corr, field1, field2, minsep, maxsep, coords, i1, i2, sep, n); break; case OldRperp: return SamplePairs2d<OldRperp>(corr, field1, field2, minsep, maxsep, coords, i1, i2, sep, n); break; case Rlens: return SamplePairs2d<Rlens>(corr, field1, field2, minsep, maxsep, coords, i1, i2, sep, n); break; case Arc: return SamplePairs2d<Arc>(corr, field1, field2, minsep, maxsep, coords, i1, i2, sep, n); break; case Periodic: return SamplePairs2d<Periodic>(corr, field1, field2, minsep, maxsep, coords, i1, i2, sep, n); break; default: Assert(false); } return 0; } template <int D1, int D2> long SamplePairs2b(void* corr, void* field1, void* field2, double minsep, double maxsep, int coords, int bin_type, int metric, long* i1, long* i2, double* sep, int n) { switch(bin_type) { case Log: return SamplePairs2c(static_cast<BinnedCorr2<D1,D2,Log>*>(corr), field1, field2, minsep, maxsep, coords, metric, i1, i2, sep, n); break; case Linear: return SamplePairs2c(static_cast<BinnedCorr2<D1,D2,Linear>*>(corr), field1, field2, minsep, maxsep, coords, metric, i1, i2, sep, n); break; case TwoD: // TwoD not implemented. break; default: Assert(false); } return 0; } template <int D1> long SamplePairs2a(void* corr, void* field1, void* field2, double minsep, double maxsep, int d2, int coords, int bin_type, int metric, long* i1, long* i2, double* sep, int n) { Assert(d2 >= D1); switch(d2) { case NData: return SamplePairs2b<D1,MAX(D1,NData)>(corr, field1, field2, minsep, maxsep, coords, bin_type, metric, i1, i2, sep, n); break; case KData: return SamplePairs2b<D1,MAX(D1,KData)>(corr, field1, field2, minsep, maxsep, coords, bin_type, metric, i1, i2, sep, n); break; case GData: return SamplePairs2b<D1,MAX(D1,GData)>(corr, field1, field2, minsep, maxsep, coords, bin_type, metric, i1, i2, sep, n); break; default: Assert(false); } return 0; } long SamplePairs(void* corr, void* field1, void* field2, double minsep, double maxsep, int d1, int d2, int coords, int bin_type, int metric, long* i1, long* i2, double* sep, int n) { dbg<<"Start SamplePairs: "<<d1<<" "<<d2<<" "<<coords<<" "<<bin_type<<" "<<metric<<std::endl; switch(d1) { case NData: return SamplePairs2a<NData>(corr, field1, field2, minsep, maxsep, d2, coords, bin_type, metric, i1, i2, sep, n); break; case KData: return SamplePairs2a<KData>(corr, field1, field2, minsep, maxsep, d2, coords, bin_type, metric, i1, i2, sep, n); break; case GData: return SamplePairs2a<GData>(corr, field1, field2, minsep, maxsep, d2, coords, bin_type, metric, i1, i2, sep, n); break; default: Assert(false); } return 0; }
#include "win32_skip_error_registry.h" #include "solar/containers/container_helpers.h" namespace solar { win32_skip_error_registry::location::location() : _file_name("") , _line_number(0) { } win32_skip_error_registry::location::location(const char* file_name, int line_number) : _file_name(file_name) , _line_number(line_number) { } bool win32_skip_error_registry::location::operator==(const location& rhs) const { return (_file_name == rhs._file_name) && (_line_number == rhs._line_number); } win32_skip_error_registry::win32_skip_error_registry() { } bool win32_skip_error_registry::contains(const char* file_name, int line_number) const { return any(_locations, location(file_name, line_number)); } void win32_skip_error_registry::add(const char* file_name, int line_number) { _locations.push_back(location(file_name, line_number)); } }
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <memory> #include "base/cxx17_backports.h" #include "base/metrics/histogram_samples.h" #include "base/pickle.h" #include "base/strings/string_number_conversions.h" #include "base/test/metrics/histogram_tester.h" #include "base/time/time.h" #include "net/base/load_flags.h" #include "net/base/request_priority.h" #include "net/base/test_completion_callback.h" #include "net/test/test_with_task_environment.h" #include "net/traffic_annotation/network_traffic_annotation_test_helper.h" #include "net/url_request/url_request.h" #include "net/url_request/url_request_context.h" #include "net/url_request/url_request_test_util.h" #include "net/url_request/url_request_throttler_manager.h" #include "net/url_request/url_request_throttler_test_support.h" #include "testing/gtest/include/gtest/gtest.h" using base::TimeTicks; namespace net { namespace { const char kRequestThrottledHistogramName[] = "Throttling.RequestThrottled"; class MockURLRequestThrottlerEntry : public URLRequestThrottlerEntry { public: explicit MockURLRequestThrottlerEntry( URLRequestThrottlerManager* manager) : URLRequestThrottlerEntry(manager, std::string()), backoff_entry_(&backoff_policy_, &fake_clock_) { InitPolicy(); } MockURLRequestThrottlerEntry( URLRequestThrottlerManager* manager, const TimeTicks& exponential_backoff_release_time, const TimeTicks& sliding_window_release_time, const TimeTicks& fake_now) : URLRequestThrottlerEntry(manager, std::string()), fake_clock_(fake_now), backoff_entry_(&backoff_policy_, &fake_clock_) { InitPolicy(); set_exponential_backoff_release_time(exponential_backoff_release_time); set_sliding_window_release_time(sliding_window_release_time); } void InitPolicy() { // Some tests become flaky if we have jitter. backoff_policy_.jitter_factor = 0.0; // This lets us avoid having to make multiple failures initially (this // logic is already tested in the BackoffEntry unit tests). backoff_policy_.num_errors_to_ignore = 0; } const BackoffEntry* GetBackoffEntry() const override { return &backoff_entry_; } BackoffEntry* GetBackoffEntry() override { return &backoff_entry_; } void ResetToBlank(const TimeTicks& time_now) { fake_clock_.set_now(time_now); GetBackoffEntry()->Reset(); set_sliding_window_release_time(time_now); } // Overridden for tests. TimeTicks ImplGetTimeNow() const override { return fake_clock_.NowTicks(); } void set_fake_now(const TimeTicks& now) { fake_clock_.set_now(now); } void set_exponential_backoff_release_time(const TimeTicks& release_time) { GetBackoffEntry()->SetCustomReleaseTime(release_time); } TimeTicks sliding_window_release_time() const { return URLRequestThrottlerEntry::sliding_window_release_time(); } void set_sliding_window_release_time(const TimeTicks& release_time) { URLRequestThrottlerEntry::set_sliding_window_release_time(release_time); } protected: ~MockURLRequestThrottlerEntry() override = default; private: mutable TestTickClock fake_clock_; BackoffEntry backoff_entry_; }; class MockURLRequestThrottlerManager : public URLRequestThrottlerManager { public: MockURLRequestThrottlerManager() : create_entry_index_(0) {} // Method to process the URL using URLRequestThrottlerManager protected // method. std::string DoGetUrlIdFromUrl(const GURL& url) { return GetIdFromUrl(url); } // Method to use the garbage collecting method of URLRequestThrottlerManager. void DoGarbageCollectEntries() { GarbageCollectEntries(); } // Returns the number of entries in the map. int GetNumberOfEntries() const { return GetNumberOfEntriesForTests(); } void CreateEntry(bool is_outdated) { TimeTicks time = TimeTicks::Now(); if (is_outdated) { time -= base::Milliseconds( MockURLRequestThrottlerEntry::kDefaultEntryLifetimeMs + 1000); } std::string fake_url_string("http://www.fakeurl.com/"); fake_url_string.append(base::NumberToString(create_entry_index_++)); GURL fake_url(fake_url_string); OverrideEntryForTests( fake_url, new MockURLRequestThrottlerEntry(this, time, TimeTicks::Now(), TimeTicks::Now())); } private: int create_entry_index_; }; struct TimeAndBool { TimeAndBool(const TimeTicks& time_value, bool expected, int line_num) { time = time_value; result = expected; line = line_num; } TimeTicks time; bool result; int line; }; struct GurlAndString { GurlAndString(const GURL& url_value, const std::string& expected, int line_num) { url = url_value; result = expected; line = line_num; } GURL url; std::string result; int line; }; } // namespace class URLRequestThrottlerEntryTest : public TestWithTaskEnvironment { protected: URLRequestThrottlerEntryTest() : request_(context_.CreateRequest(GURL(), DEFAULT_PRIORITY, nullptr, TRAFFIC_ANNOTATION_FOR_TESTS)) {} void SetUp() override; TimeTicks now_; MockURLRequestThrottlerManager manager_; // Dummy object, not used. scoped_refptr<MockURLRequestThrottlerEntry> entry_; TestURLRequestContext context_; std::unique_ptr<URLRequest> request_; }; void URLRequestThrottlerEntryTest::SetUp() { request_->SetLoadFlags(0); now_ = TimeTicks::Now(); entry_ = new MockURLRequestThrottlerEntry(&manager_); entry_->ResetToBlank(now_); } std::ostream& operator<<(std::ostream& out, const base::TimeTicks& time) { return out << time.ToInternalValue(); } TEST_F(URLRequestThrottlerEntryTest, InterfaceDuringExponentialBackoff) { base::HistogramTester histogram_tester; entry_->set_exponential_backoff_release_time(entry_->ImplGetTimeNow() + base::Milliseconds(1)); EXPECT_TRUE(entry_->ShouldRejectRequest(*request_)); histogram_tester.ExpectBucketCount(kRequestThrottledHistogramName, 0, 0); histogram_tester.ExpectBucketCount(kRequestThrottledHistogramName, 1, 1); } TEST_F(URLRequestThrottlerEntryTest, InterfaceNotDuringExponentialBackoff) { base::HistogramTester histogram_tester; entry_->set_exponential_backoff_release_time(entry_->ImplGetTimeNow()); EXPECT_FALSE(entry_->ShouldRejectRequest(*request_)); entry_->set_exponential_backoff_release_time(entry_->ImplGetTimeNow() - base::Milliseconds(1)); EXPECT_FALSE(entry_->ShouldRejectRequest(*request_)); histogram_tester.ExpectBucketCount(kRequestThrottledHistogramName, 0, 2); histogram_tester.ExpectBucketCount(kRequestThrottledHistogramName, 1, 0); } TEST_F(URLRequestThrottlerEntryTest, InterfaceUpdateFailure) { entry_->UpdateWithResponse(503); EXPECT_GT(entry_->GetExponentialBackoffReleaseTime(), entry_->ImplGetTimeNow()) << "A failure should increase the release_time"; } TEST_F(URLRequestThrottlerEntryTest, InterfaceUpdateSuccess) { entry_->UpdateWithResponse(200); EXPECT_EQ(entry_->GetExponentialBackoffReleaseTime(), entry_->ImplGetTimeNow()) << "A success should not add any delay"; } TEST_F(URLRequestThrottlerEntryTest, InterfaceUpdateSuccessThenFailure) { entry_->UpdateWithResponse(200); entry_->UpdateWithResponse(503); EXPECT_GT(entry_->GetExponentialBackoffReleaseTime(), entry_->ImplGetTimeNow()) << "This scenario should add delay"; entry_->UpdateWithResponse(200); } TEST_F(URLRequestThrottlerEntryTest, IsEntryReallyOutdated) { base::TimeDelta lifetime = base::Milliseconds(MockURLRequestThrottlerEntry::kDefaultEntryLifetimeMs); const base::TimeDelta kFiveMs = base::Milliseconds(5); TimeAndBool test_values[] = { TimeAndBool(now_, false, __LINE__), TimeAndBool(now_ - kFiveMs, false, __LINE__), TimeAndBool(now_ + kFiveMs, false, __LINE__), TimeAndBool(now_ - (lifetime - kFiveMs), false, __LINE__), TimeAndBool(now_ - lifetime, true, __LINE__), TimeAndBool(now_ - (lifetime + kFiveMs), true, __LINE__)}; for (unsigned int i = 0; i < base::size(test_values); ++i) { entry_->set_exponential_backoff_release_time(test_values[i].time); EXPECT_EQ(entry_->IsEntryOutdated(), test_values[i].result) << "Test case #" << i << " line " << test_values[i].line << " failed"; } } TEST_F(URLRequestThrottlerEntryTest, MaxAllowedBackoff) { for (int i = 0; i < 30; ++i) { entry_->UpdateWithResponse(503); } base::TimeDelta delay = entry_->GetExponentialBackoffReleaseTime() - now_; EXPECT_EQ(delay.InMilliseconds(), MockURLRequestThrottlerEntry::kDefaultMaximumBackoffMs); } TEST_F(URLRequestThrottlerEntryTest, MalformedContent) { for (int i = 0; i < 5; ++i) entry_->UpdateWithResponse(503); TimeTicks release_after_failures = entry_->GetExponentialBackoffReleaseTime(); // Inform the entry that a response body was malformed, which is supposed to // increase the back-off time. Note that we also submit a successful // UpdateWithResponse to pair with ReceivedContentWasMalformed() since that // is what happens in practice (if a body is received, then a non-500 // response must also have been received). entry_->ReceivedContentWasMalformed(200); entry_->UpdateWithResponse(200); EXPECT_GT(entry_->GetExponentialBackoffReleaseTime(), release_after_failures); } TEST_F(URLRequestThrottlerEntryTest, SlidingWindow) { int max_send = URLRequestThrottlerEntry::kDefaultMaxSendThreshold; int sliding_window = URLRequestThrottlerEntry::kDefaultSlidingWindowPeriodMs; TimeTicks time_1 = entry_->ImplGetTimeNow() + base::Milliseconds(sliding_window / 3); TimeTicks time_2 = entry_->ImplGetTimeNow() + base::Milliseconds(2 * sliding_window / 3); TimeTicks time_3 = entry_->ImplGetTimeNow() + base::Milliseconds(sliding_window); TimeTicks time_4 = entry_->ImplGetTimeNow() + base::Milliseconds(sliding_window + 2 * sliding_window / 3); entry_->set_exponential_backoff_release_time(time_1); for (int i = 0; i < max_send / 2; ++i) { EXPECT_EQ(2 * sliding_window / 3, entry_->ReserveSendingTimeForNextRequest(time_2)); } EXPECT_EQ(time_2, entry_->sliding_window_release_time()); entry_->set_fake_now(time_3); for (int i = 0; i < (max_send + 1) / 2; ++i) EXPECT_EQ(0, entry_->ReserveSendingTimeForNextRequest(TimeTicks())); EXPECT_EQ(time_4, entry_->sliding_window_release_time()); } class URLRequestThrottlerManagerTest : public TestWithTaskEnvironment { protected: URLRequestThrottlerManagerTest() : request_(context_.CreateRequest(GURL(), DEFAULT_PRIORITY, nullptr, TRAFFIC_ANNOTATION_FOR_TESTS)) {} void SetUp() override { request_->SetLoadFlags(0); } // context_ must be declared before request_. TestURLRequestContext context_; std::unique_ptr<URLRequest> request_; }; TEST_F(URLRequestThrottlerManagerTest, IsUrlStandardised) { MockURLRequestThrottlerManager manager; GurlAndString test_values[] = { GurlAndString(GURL("http://www.example.com"), std::string("http://www.example.com/"), __LINE__), GurlAndString(GURL("http://www.Example.com"), std::string("http://www.example.com/"), __LINE__), GurlAndString(GURL("http://www.ex4mple.com/Pr4c71c41"), std::string("http://www.ex4mple.com/pr4c71c41"), __LINE__), GurlAndString(GURL("http://www.example.com/0/token/false"), std::string("http://www.example.com/0/token/false"), __LINE__), GurlAndString(GURL("http://www.example.com/index.php?code=javascript"), std::string("http://www.example.com/index.php"), __LINE__), GurlAndString(GURL("http://www.example.com/index.php?code=1#superEntry"), std::string("http://www.example.com/index.php"), __LINE__), GurlAndString(GURL("http://www.example.com/index.php#superEntry"), std::string("http://www.example.com/index.php"), __LINE__), GurlAndString(GURL("http://www.example.com:1234/"), std::string("http://www.example.com:1234/"), __LINE__)}; for (unsigned int i = 0; i < base::size(test_values); ++i) { std::string temp = manager.DoGetUrlIdFromUrl(test_values[i].url); EXPECT_EQ(temp, test_values[i].result) << "Test case #" << i << " line " << test_values[i].line << " failed"; } } TEST_F(URLRequestThrottlerManagerTest, AreEntriesBeingCollected) { MockURLRequestThrottlerManager manager; manager.CreateEntry(true); // true = Entry is outdated. manager.CreateEntry(true); manager.CreateEntry(true); manager.DoGarbageCollectEntries(); EXPECT_EQ(0, manager.GetNumberOfEntries()); manager.CreateEntry(false); manager.CreateEntry(false); manager.CreateEntry(false); manager.CreateEntry(true); manager.DoGarbageCollectEntries(); EXPECT_EQ(3, manager.GetNumberOfEntries()); } TEST_F(URLRequestThrottlerManagerTest, IsHostBeingRegistered) { MockURLRequestThrottlerManager manager; manager.RegisterRequestUrl(GURL("http://www.example.com/")); manager.RegisterRequestUrl(GURL("http://www.google.com/")); manager.RegisterRequestUrl(GURL("http://www.google.com/index/0")); manager.RegisterRequestUrl(GURL("http://www.google.com/index/0?code=1")); manager.RegisterRequestUrl(GURL("http://www.google.com/index/0#lolsaure")); EXPECT_EQ(3, manager.GetNumberOfEntries()); } TEST_F(URLRequestThrottlerManagerTest, LocalHostOptedOut) { MockURLRequestThrottlerManager manager; // A localhost entry should always be opted out. scoped_refptr<URLRequestThrottlerEntryInterface> localhost_entry = manager.RegisterRequestUrl(GURL("http://localhost/hello")); EXPECT_FALSE(localhost_entry->ShouldRejectRequest(*request_)); for (int i = 0; i < 10; ++i) { localhost_entry->UpdateWithResponse(503); } EXPECT_FALSE(localhost_entry->ShouldRejectRequest(*request_)); // We're not mocking out GetTimeNow() in this scenario // so add a 100 ms buffer to avoid flakiness (that should always // give enough time to get from the TimeTicks::Now() call here // to the TimeTicks::Now() call in the entry class). EXPECT_GT(TimeTicks::Now() + base::Milliseconds(100), localhost_entry->GetExponentialBackoffReleaseTime()); } TEST_F(URLRequestThrottlerManagerTest, ClearOnNetworkChange) { for (int i = 0; i < 3; ++i) { MockURLRequestThrottlerManager manager; scoped_refptr<URLRequestThrottlerEntryInterface> entry_before = manager.RegisterRequestUrl(GURL("http://www.example.com/")); for (int j = 0; j < 10; ++j) { entry_before->UpdateWithResponse(503); } EXPECT_TRUE(entry_before->ShouldRejectRequest(*request_)); switch (i) { case 0: manager.OnIPAddressChanged(); break; case 1: manager.OnConnectionTypeChanged( NetworkChangeNotifier::CONNECTION_UNKNOWN); break; case 2: manager.OnConnectionTypeChanged(NetworkChangeNotifier::CONNECTION_NONE); break; default: FAIL(); } scoped_refptr<URLRequestThrottlerEntryInterface> entry_after = manager.RegisterRequestUrl(GURL("http://www.example.com/")); EXPECT_FALSE(entry_after->ShouldRejectRequest(*request_)); } } } // namespace net
// Copyright (C) 2018-2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <string> #include <vector> #include <ngraph/op/experimental_detectron_detection_output.hpp> #include "ie_parallel.hpp" #include "experimental_detectron_detection_output.h" using namespace InferenceEngine; namespace ov { namespace intel_cpu { namespace node { struct Indexer { const std::vector<int> dims_; int total_{1}; explicit Indexer(const std::vector<int>& dims) : dims_(dims) { total_ = 1; for (size_t i = 0; i < dims_.size(); ++i) { total_ *= dims_[i]; } } int operator()(const std::vector<int>& idx) const { int flat_idx = 0; assert(idx.size() == dims_.size()); for (size_t i = 0; i < dims_.size(); ++i) { assert(0 <= idx[i] && idx[i] < dims_[i]); flat_idx = flat_idx * dims_[i] + idx[i]; } assert(flat_idx < total_); return flat_idx; } }; static void refine_boxes(const float* boxes, const float* deltas, const float* weights, const float* scores, float* refined_boxes, float* refined_boxes_areas, float* refined_scores, const int rois_num, const int classes_num, const float img_H, const float img_W, const float max_delta_log_wh, float coordinates_offset) { Indexer box_idx({rois_num, 4}); Indexer delta_idx({rois_num, classes_num, 4}); Indexer score_idx({rois_num, classes_num}); Indexer refined_box_idx({classes_num, rois_num, 4}); Indexer refined_score_idx({classes_num, rois_num}); for (int roi_idx = 0; roi_idx < rois_num; ++roi_idx) { float x0 = boxes[box_idx({roi_idx, 0})]; float y0 = boxes[box_idx({roi_idx, 1})]; float x1 = boxes[box_idx({roi_idx, 2})]; float y1 = boxes[box_idx({roi_idx, 3})]; if (x1 - x0 <= 0 || y1 - y0 <= 0) { continue; } // width & height of box const float ww = x1 - x0 + coordinates_offset; const float hh = y1 - y0 + coordinates_offset; // center location of box const float ctr_x = x0 + 0.5f * ww; const float ctr_y = y0 + 0.5f * hh; for (int class_idx = 1; class_idx < classes_num; ++class_idx) { const float dx = deltas[delta_idx({roi_idx, class_idx, 0})] / weights[0]; const float dy = deltas[delta_idx({roi_idx, class_idx, 1})] / weights[1]; const float d_log_w = deltas[delta_idx({roi_idx, class_idx, 2})] / weights[2]; const float d_log_h = deltas[delta_idx({roi_idx, class_idx, 3})] / weights[3]; // new center location according to deltas (dx, dy) const float pred_ctr_x = dx * ww + ctr_x; const float pred_ctr_y = dy * hh + ctr_y; // new width & height according to deltas d(log w), d(log h) const float pred_w = std::exp((std::min)(d_log_w, max_delta_log_wh)) * ww; const float pred_h = std::exp((std::min)(d_log_h, max_delta_log_wh)) * hh; // update upper-left corner location float x0_new = pred_ctr_x - 0.5f * pred_w; float y0_new = pred_ctr_y - 0.5f * pred_h; // update lower-right corner location float x1_new = pred_ctr_x + 0.5f * pred_w - coordinates_offset; float y1_new = pred_ctr_y + 0.5f * pred_h - coordinates_offset; // adjust new corner locations to be within the image region, x0_new = std::max<float>(0.0f, x0_new); y0_new = std::max<float>(0.0f, y0_new); x1_new = std::max<float>(0.0f, x1_new); y1_new = std::max<float>(0.0f, y1_new); // recompute new width & height const float box_w = x1_new - x0_new + coordinates_offset; const float box_h = y1_new - y0_new + coordinates_offset; refined_boxes[refined_box_idx({class_idx, roi_idx, 0})] = x0_new; refined_boxes[refined_box_idx({class_idx, roi_idx, 1})] = y0_new; refined_boxes[refined_box_idx({class_idx, roi_idx, 2})] = x1_new; refined_boxes[refined_box_idx({class_idx, roi_idx, 3})] = y1_new; refined_boxes_areas[refined_score_idx({class_idx, roi_idx})] = box_w * box_h; refined_scores[refined_score_idx({class_idx, roi_idx})] = scores[score_idx({roi_idx, class_idx})]; } } } template <typename T> static bool SortScorePairDescend(const std::pair<float, T>& pair1, const std::pair<float, T>& pair2) { return pair1.first > pair2.first; } struct ConfidenceComparator { explicit ConfidenceComparator(const float* conf_data) : _conf_data(conf_data) {} bool operator()(int idx1, int idx2) { if (_conf_data[idx1] > _conf_data[idx2]) return true; if (_conf_data[idx1] < _conf_data[idx2]) return false; return idx1 < idx2; } const float* _conf_data; }; static inline float JaccardOverlap(const float *decoded_bbox, const float *bbox_sizes, const int idx1, const int idx2, const float coordinates_offset = 1) { float xmin1 = decoded_bbox[idx1 * 4 + 0]; float ymin1 = decoded_bbox[idx1 * 4 + 1]; float xmax1 = decoded_bbox[idx1 * 4 + 2]; float ymax1 = decoded_bbox[idx1 * 4 + 3]; float xmin2 = decoded_bbox[idx2 * 4 + 0]; float ymin2 = decoded_bbox[idx2 * 4 + 1]; float ymax2 = decoded_bbox[idx2 * 4 + 3]; float xmax2 = decoded_bbox[idx2 * 4 + 2]; if (xmin2 > xmax1 || xmax2 < xmin1 || ymin2 > ymax1 || ymax2 < ymin1) { return 0.0f; } float intersect_xmin = (std::max)(xmin1, xmin2); float intersect_ymin = (std::max)(ymin1, ymin2); float intersect_xmax = (std::min)(xmax1, xmax2); float intersect_ymax = (std::min)(ymax1, ymax2); float intersect_width = intersect_xmax - intersect_xmin + coordinates_offset; float intersect_height = intersect_ymax - intersect_ymin + coordinates_offset; if (intersect_width <= 0 || intersect_height <= 0) { return 0.0f; } float intersect_size = intersect_width * intersect_height; float bbox1_size = bbox_sizes[idx1]; float bbox2_size = bbox_sizes[idx2]; return intersect_size / (bbox1_size + bbox2_size - intersect_size); } static void nms_cf(const float* conf_data, const float* bboxes, const float* sizes, int* buffer, int* indices, int& detections, const int boxes_num, const int pre_nms_topn, const int post_nms_topn, const float confidence_threshold, const float nms_threshold) { int count = 0; for (int i = 0; i < boxes_num; ++i) { if (conf_data[i] > confidence_threshold) { indices[count] = i; count++; } } int num_output_scores = (pre_nms_topn == -1 ? count : (std::min)(pre_nms_topn, count)); std::partial_sort_copy(indices, indices + count, buffer, buffer + num_output_scores, ConfidenceComparator(conf_data)); detections = 0; for (int i = 0; i < num_output_scores; ++i) { const int idx = buffer[i]; bool keep = true; for (int k = 0; k < detections; ++k) { const int kept_idx = indices[k]; float overlap = JaccardOverlap(bboxes, sizes, idx, kept_idx); if (overlap > nms_threshold) { keep = false; break; } } if (keep) { indices[detections] = idx; detections++; } } detections = (post_nms_topn == -1 ? detections : (std::min)(post_nms_topn, detections)); } bool ExperimentalDetectronDetectionOutput::needShapeInfer() const { return false; } bool ExperimentalDetectronDetectionOutput::needPrepareParams() const { return false; } bool ExperimentalDetectronDetectionOutput::isSupportedOperation(const std::shared_ptr<const ngraph::Node>& op, std::string& errorMessage) noexcept { try { const auto doOp = ngraph::as_type_ptr<const ngraph::op::v6::ExperimentalDetectronDetectionOutput>(op); if (!doOp) { errorMessage = "Node is not an instance of the ExperimentalDetectronDetectionOutput from the operations set v6."; return false; } } catch (...) { return false; } return true; } ExperimentalDetectronDetectionOutput::ExperimentalDetectronDetectionOutput (const std::shared_ptr<ngraph::Node>& op, const mkldnn::engine& eng, WeightsSharing::Ptr &cache) : Node(op, eng, cache) { std::string errorMessage; if (!isSupportedOperation(op, errorMessage)) { IE_THROW(NotImplemented) << errorMessage; } auto doOp = ngraph::as_type_ptr<const ngraph::op::v6::ExperimentalDetectronDetectionOutput>(op); auto attributes = doOp->get_attrs(); score_threshold_ = attributes.score_threshold; nms_threshold_ = attributes.nms_threshold; max_delta_log_wh_ = attributes.max_delta_log_wh; classes_num_ = attributes.num_classes; max_detections_per_class_ = attributes.post_nms_count; max_detections_per_image_ = attributes.max_detections_per_image; class_agnostic_box_regression_ = attributes.class_agnostic_box_regression; deltas_weights_ = attributes.deltas_weights; } void ExperimentalDetectronDetectionOutput::initSupportedPrimitiveDescriptors() { if (!supportedPrimitiveDescriptors.empty()) return; std::vector<PortConfigurator> inDataConf; inDataConf.reserve(inputShapes.size()); for (int i = 0; i < inputShapes.size(); ++i) inDataConf.emplace_back(LayoutType::ncsp, Precision::FP32); addSupportedPrimDesc(inDataConf, {{LayoutType::ncsp, Precision::FP32}, {LayoutType::ncsp, Precision::I32}, {LayoutType::ncsp, Precision::FP32}}, impl_desc_type::ref_any); } void ExperimentalDetectronDetectionOutput::execute(mkldnn::stream strm) { const int rois_num = getParentEdgeAt(INPUT_ROIS)->getMemory().getStaticDims()[0]; assert(classes_num_ == static_cast<int>(getParentEdgeAt(INPUT_SCORES)->getMemory().getStaticDims()[1])); assert(4 * classes_num_ == static_cast<int>(getParentEdgeAt(INPUT_DELTAS)->getMemory().getStaticDims()[1])); const auto* boxes = reinterpret_cast<const float *>(getParentEdgeAt(INPUT_ROIS)->getMemoryPtr()->GetPtr()); const auto* deltas = reinterpret_cast<const float *>(getParentEdgeAt(INPUT_DELTAS)->getMemoryPtr()->GetPtr()); const auto* scores = reinterpret_cast<const float *>(getParentEdgeAt(INPUT_SCORES)->getMemoryPtr()->GetPtr()); const auto* im_info = reinterpret_cast<const float *>(getParentEdgeAt(INPUT_IM_INFO)->getMemoryPtr()->GetPtr()); auto* output_boxes = reinterpret_cast<float *>(getChildEdgesAtPort(OUTPUT_BOXES)[0]->getMemoryPtr()->GetPtr()); auto* output_scores = reinterpret_cast<float *>(getChildEdgesAtPort(OUTPUT_SCORES)[0]->getMemoryPtr()->GetPtr()); auto* output_classes = reinterpret_cast<int32_t *>(getChildEdgesAtPort(OUTPUT_CLASSES)[0]->getMemoryPtr()->GetPtr()); const float img_H = im_info[0]; const float img_W = im_info[1]; // Apply deltas. std::vector<float> refined_boxes(classes_num_ * rois_num * 4, 0); std::vector<float> refined_scores(classes_num_ * rois_num, 0); std::vector<float> refined_boxes_areas(classes_num_ * rois_num, 0); Indexer refined_box_idx({classes_num_, rois_num, 4}); Indexer refined_score_idx({classes_num_, rois_num}); refine_boxes(boxes, deltas, &deltas_weights_[0], scores, &refined_boxes[0], &refined_boxes_areas[0], &refined_scores[0], rois_num, classes_num_, img_H, img_W, max_delta_log_wh_, 1.0f); // Apply NMS class-wise. std::vector<int> buffer(rois_num, 0); std::vector<int> indices(classes_num_ * rois_num, 0); std::vector<int> detections_per_class(classes_num_, 0); int total_detections_num = 0; for (int class_idx = 1; class_idx < classes_num_; ++class_idx) { nms_cf(&refined_scores[refined_score_idx({class_idx, 0})], &refined_boxes[refined_box_idx({class_idx, 0, 0})], &refined_boxes_areas[refined_score_idx({class_idx, 0})], &buffer[0], &indices[total_detections_num], detections_per_class[class_idx], rois_num, -1, max_detections_per_class_, score_threshold_, nms_threshold_); total_detections_num += detections_per_class[class_idx]; } // Leave only max_detections_per_image_ detections. // confidence, <class, index> std::vector<std::pair<float, std::pair<int, int>>> conf_index_class_map; int indices_offset = 0; for (int c = 0; c < classes_num_; ++c) { int n = detections_per_class[c]; for (int i = 0; i < n; ++i) { int idx = indices[indices_offset + i]; float score = refined_scores[refined_score_idx({c, idx})]; conf_index_class_map.push_back(std::make_pair(score, std::make_pair(c, idx))); } indices_offset += n; } assert(max_detections_per_image_ > 0); if (total_detections_num > max_detections_per_image_) { std::partial_sort(conf_index_class_map.begin(), conf_index_class_map.begin() + max_detections_per_image_, conf_index_class_map.end(), SortScorePairDescend<std::pair<int, int>>); conf_index_class_map.resize(max_detections_per_image_); total_detections_num = max_detections_per_image_; } // Fill outputs. memset(output_boxes, 0, max_detections_per_image_ * 4 * sizeof(output_boxes[0])); memset(output_scores, 0, max_detections_per_image_ * sizeof(output_scores[0])); memset(output_classes, 0, max_detections_per_image_ * sizeof(output_classes[0])); int i = 0; for (const auto & detection : conf_index_class_map) { float score = detection.first; int cls = detection.second.first; int idx = detection.second.second; output_boxes[4 * i + 0] = refined_boxes[refined_box_idx({cls, idx, 0})]; output_boxes[4 * i + 1] = refined_boxes[refined_box_idx({cls, idx, 1})]; output_boxes[4 * i + 2] = refined_boxes[refined_box_idx({cls, idx, 2})]; output_boxes[4 * i + 3] = refined_boxes[refined_box_idx({cls, idx, 3})]; output_scores[i] = score; output_classes[i] = cls; ++i; } } bool ExperimentalDetectronDetectionOutput::created() const { return getType() == Type::ExperimentalDetectronDetectionOutput; } } // namespace node } // namespace intel_cpu } // namespace ov
/* * * Copyright (C) 2003-2010, OFFIS e.V. * All rights reserved. See COPYRIGHT file for details. * * This software and supporting documentation were developed by * * OFFIS e.V. * R&D Division Health * Escherweg 2 * D-26121 Oldenburg, Germany * * * Module: dcmnet * * Author: Marco Eichelberg * * Purpose: * class DcmPresentationContextItem * class DcmPresentationContextMap * */ #include "dcmtk/config/osconfig.h" #include "dcmtk/dcmnet/dccfpcmp.h" /* for class DcmPresentationContextMap */ #include "dcmtk/dcmdata/dcerror.h" /* for EC_IllegalCall */ DcmPresentationContextItem::DcmPresentationContextItem( const DcmUIDHandler& abstractSyntax, const OFString& xferSyntaxGroup ) : uid_(abstractSyntax) , xferSyntaxGroup_(xferSyntaxGroup) { } DcmPresentationContextItem::DcmPresentationContextItem(const DcmPresentationContextItem& arg) : uid_(arg.uid_) , xferSyntaxGroup_(arg.xferSyntaxGroup_) { } DcmPresentationContextItem::~DcmPresentationContextItem() { } DcmPresentationContextItem& DcmPresentationContextItem::operator=(const DcmPresentationContextItem& arg) { uid_ = arg.uid_; xferSyntaxGroup_ = arg.xferSyntaxGroup_; return *this; } /* ========================================================= */ DcmPresentationContextMap::DcmPresentationContextMap() : map_() { } DcmPresentationContextMap::~DcmPresentationContextMap() { OFListIterator(DcmKeyValuePair<DcmPresentationContextList *> *) first = map_.begin(); OFListIterator(DcmKeyValuePair<DcmPresentationContextList *> *) last = map_.end(); while (first != last) { delete (*first)->value(); ++first; } } OFCondition DcmPresentationContextMap::add( const char *key, const char *abstractSyntaxUID, const char *transferSyntaxKey) { if ((!key)||(!abstractSyntaxUID)||(!transferSyntaxKey)) return EC_IllegalCall; // perform syntax check of UID DcmUIDHandler uid(abstractSyntaxUID); if (! uid.isValidUID()) { OFString s("not a valid abstract syntax UID: "); s += abstractSyntaxUID; return makeOFCondition(OFM_dcmnet, 1025, OF_error, s.c_str()); } OFString skey(key); DcmPresentationContextList * const *value = OFconst_cast(DcmPresentationContextList * const *, map_.lookup(skey)); if (value == NULL) { DcmPresentationContextList *newentry = new DcmPresentationContextList(); map_.add(skey, OFstatic_cast(DcmPresentationContextList *, newentry)); value = &newentry; } // make sure list does not get longer than 128 entries if (((*value)->size()) > 127) { OFString s("presentation context list too long (> 128 entries): "); s += key; return makeOFCondition(OFM_dcmnet, 1032, OF_error, s.c_str()); } // insert values into list. (*value)->push_back(DcmPresentationContextItem(uid, OFString(transferSyntaxKey))); return EC_Normal; } OFBool DcmPresentationContextMap::isKnownKey(const char *key) const { if (!key) return OFFalse; if (map_.lookup(OFString(key))) return OFTrue; return OFFalse; } OFBool DcmPresentationContextMap::isKnownAbstractSyntax( const char*key, const DcmUIDHandler& abstractSyntax) const { if (!key) return OFFalse; OFString skey(key); DcmPresentationContextList * const *value = OFconst_cast(DcmPresentationContextList * const *, map_.lookup(skey)); if (value) { // check if abstract syntax is in list OFListIterator(DcmPresentationContextItem) first = (*value)->begin(); OFListIterator(DcmPresentationContextItem) last = (*value)->end(); while (first != last) { if ((*first).matches(abstractSyntax)) return OFTrue; ++first; } } return OFFalse; } const DcmPresentationContextList *DcmPresentationContextMap::getPresentationContextList(const char *key) const { const DcmPresentationContextList *result = NULL; if (key) { DcmPresentationContextList * const *value = OFconst_cast(DcmPresentationContextList * const *, map_.lookup(OFString(key))); if (value) result = *value; } return result; }
/* mvxxx 2019 https://github.com/mvxxx */ #pragma once #include "../../external/SFML/include/SFML/Graphics/VertexArray.hpp" #include "../ecs/component/Visible.hpp" #include "../ecs/entity/Entity.hpp" #include "../scene/Scene.hpp" #include "../Utilities.hpp" /** * @brief Represents frame on the scene */ class Frame : public mv::Entity, public sf::Drawable { /* ===Objects=== */ public: /** * @brief Allows distinguishing two types */ enum class PointType { START, CURRENT }; protected: private: //Represents start point sf::Vector2f start; //Represents current point sf::Vector2f current; /* ===Methods=== */ public: /** * @brief Classic ctor * @param scene - pointer to scene */ Frame( const std::shared_ptr<Scene>& scene ); /** * @brief activates selection * @param coords - start position */ void activateSelection(const sf::Vector2f& coords); /** * @brief deactivates selection */ void deactivateSelection(); /** * @brief uptades selection * @param coords - current position */ void updateSelection(const sf::Vector2f& coords); /** * @brief returns frame * @param coords - start position */ const sf::VertexArray& getFrame(); /** * @brief sets point * @param coords - position * @param status - type of point * @see PointType enum class */ void setPoint(const sf::Vector2f& coords, const PointType& status); protected: private: /** * @brief inits frame, creates frame structure * @param scene - pointer to main scene */ void initFrame(const std::shared_ptr<Scene>& scene); /** * @brief configures frame * uptades frame's structure with current existing CURRENT and START point * @param coords - start position */ void configureFrame(); /** * @brief draw * @param target from SFML * @param states from SFML */ virtual void draw( sf::RenderTarget& target, sf::RenderStates states ) const; };
/* ** Copyright 2009-2011,2017 Centreon ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. ** ** For more information : contact@centreon.com */ #ifndef CCB_EXCEPTIONS_CORRUPTION_HH # define CCB_EXCEPTIONS_CORRUPTION_HH # include "com/centreon/broker/exceptions/msg.hh" # include "com/centreon/broker/namespace.hh" CCB_BEGIN() namespace exceptions { /** * @class corruption corruption.hh "com/centreon/broker/exceptions/corruption.hh" * @brief Shutdown exception class. * * This exception is thrown when someone attemps to read from a * stream that has been corruption. */ class corruption : public msg { public: corruption(); corruption(corruption const& other); ~corruption() throw (); corruption& operator=(corruption const& other); /** * Insert data in message. * * @param[in] t Data to insert. */ template <typename T> corruption& operator<<(T t) throw () { msg::operator<<(t); return (*this); } }; } CCB_END() #endif // !CCB_EXCEPTIONS_CORRUPTION_HH
#include "Texture_From_File.h" #include "loader.h" namespace texturing { unsigned char *Texture_From_File::generate(int &width, int &height) { return load_png(filename.c_str(), width, height); } }
// // Copyright (c) 2009-2010 Mikko Mononen memon@inside.org // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. // #include "DetourObstacleAvoidance.h" #include "DetourCommon.h" #include "DetourAlloc.h" #include "DetourAssert.h" #include <string.h> #include <math.h> #include <float.h> #include <new> static const float DT_PI = 3.14159265f; static int sweepCircleCircle(const float* c0, const float r0, const float* v, const float* c1, const float r1, float& tmin, float& tmax) { static const float EPS = 0.0001f; float s[3]; dtVsub(s,c1,c0); float r = r0+r1; float c = dtVdot2D(s,s) - r*r; float a = dtVdot2D(v,v); if (a < EPS) return 0; // not moving // Overlap, calc time to exit. float b = dtVdot2D(v,s); float d = b*b - a*c; if (d < 0.0f) return 0; // no intersection. a = 1.0f / a; const float rd = dtSqrt(d); tmin = (b - rd) * a; tmax = (b + rd) * a; return 1; } static int isectRaySeg(const float* ap, const float* u, const float* bp, const float* bq, float& t) { float v[3], w[3]; dtVsub(v,bq,bp); dtVsub(w,ap,bp); float d = dtVperp2D(u,v); if (fabsf(d) < 1e-6f) return 0; d = 1.0f/d; t = dtVperp2D(v,w) * d; if (t < 0 || t > 1) return 0; float s = dtVperp2D(u,w) * d; if (s < 0 || s > 1) return 0; return 1; } dtObstacleAvoidanceDebugData* dtAllocObstacleAvoidanceDebugData() { void* mem = dtAlloc(sizeof(dtObstacleAvoidanceDebugData), DT_ALLOC_PERM); if (!mem) return 0; return new(mem) dtObstacleAvoidanceDebugData; } void dtFreeObstacleAvoidanceDebugData(dtObstacleAvoidanceDebugData* ptr) { if (!ptr) return; ptr->~dtObstacleAvoidanceDebugData(); dtFree(ptr); } dtObstacleAvoidanceDebugData::dtObstacleAvoidanceDebugData() : m_nsamples(0), m_maxSamples(0), m_vel(0), m_ssize(0), m_pen(0), m_vpen(0), m_vcpen(0), m_spen(0), m_tpen(0) { } dtObstacleAvoidanceDebugData::~dtObstacleAvoidanceDebugData() { dtFree(m_vel); dtFree(m_ssize); dtFree(m_pen); dtFree(m_vpen); dtFree(m_vcpen); dtFree(m_spen); dtFree(m_tpen); } bool dtObstacleAvoidanceDebugData::init(const int maxSamples) { dtAssert(maxSamples); m_maxSamples = maxSamples; m_vel = (float*)dtAlloc(sizeof(float)*3*m_maxSamples, DT_ALLOC_PERM); if (!m_vel) return false; m_pen = (float*)dtAlloc(sizeof(float)*m_maxSamples, DT_ALLOC_PERM); if (!m_pen) return false; m_ssize = (float*)dtAlloc(sizeof(float)*m_maxSamples, DT_ALLOC_PERM); if (!m_ssize) return false; m_vpen = (float*)dtAlloc(sizeof(float)*m_maxSamples, DT_ALLOC_PERM); if (!m_vpen) return false; m_vcpen = (float*)dtAlloc(sizeof(float)*m_maxSamples, DT_ALLOC_PERM); if (!m_vcpen) return false; m_spen = (float*)dtAlloc(sizeof(float)*m_maxSamples, DT_ALLOC_PERM); if (!m_spen) return false; m_tpen = (float*)dtAlloc(sizeof(float)*m_maxSamples, DT_ALLOC_PERM); if (!m_tpen) return false; return true; } void dtObstacleAvoidanceDebugData::reset() { m_nsamples = 0; } void dtObstacleAvoidanceDebugData::addSample(const float* vel, const float ssize, const float pen, const float vpen, const float vcpen, const float spen, const float tpen) { if (m_nsamples >= m_maxSamples) return; dtAssert(m_vel); dtAssert(m_ssize); dtAssert(m_pen); dtAssert(m_vpen); dtAssert(m_vcpen); dtAssert(m_spen); dtAssert(m_tpen); dtVcopy(&m_vel[m_nsamples*3], vel); m_ssize[m_nsamples] = ssize; m_pen[m_nsamples] = pen; m_vpen[m_nsamples] = vpen; m_vcpen[m_nsamples] = vcpen; m_spen[m_nsamples] = spen; m_tpen[m_nsamples] = tpen; m_nsamples++; } static void normalizeArray(float* arr, const int n) { // Normalize penaly range. float minPen = FLT_MAX; float maxPen = -FLT_MAX; for (int i = 0; i < n; ++i) { minPen = dtMin(minPen, arr[i]); maxPen = dtMax(maxPen, arr[i]); } const float penRange = maxPen-minPen; const float s = penRange > 0.001f ? (1.0f / penRange) : 1; for (int i = 0; i < n; ++i) arr[i] = dtClamp((arr[i]-minPen)*s, 0.0f, 1.0f); } void dtObstacleAvoidanceDebugData::normalizeSamples() { normalizeArray(m_pen, m_nsamples); normalizeArray(m_vpen, m_nsamples); normalizeArray(m_vcpen, m_nsamples); normalizeArray(m_spen, m_nsamples); normalizeArray(m_tpen, m_nsamples); } dtObstacleAvoidanceQuery* dtAllocObstacleAvoidanceQuery() { void* mem = dtAlloc(sizeof(dtObstacleAvoidanceQuery), DT_ALLOC_PERM); if (!mem) return 0; return new(mem) dtObstacleAvoidanceQuery; } void dtFreeObstacleAvoidanceQuery(dtObstacleAvoidanceQuery* ptr) { if (!ptr) return; ptr->~dtObstacleAvoidanceQuery(); dtFree(ptr); } dtObstacleAvoidanceQuery::dtObstacleAvoidanceQuery() : m_maxCircles(0), m_circles(0), m_ncircles(0), m_maxSegments(0), m_segments(0), m_nsegments(0) { } dtObstacleAvoidanceQuery::~dtObstacleAvoidanceQuery() { dtFree(m_circles); dtFree(m_segments); } bool dtObstacleAvoidanceQuery::init(const int maxCircles, const int maxSegments) { m_maxCircles = maxCircles; m_ncircles = 0; m_circles = (dtObstacleCircle*)dtAlloc(sizeof(dtObstacleCircle)*m_maxCircles, DT_ALLOC_PERM); if (!m_circles) return false; memset(m_circles, 0, sizeof(dtObstacleCircle)*m_maxCircles); m_maxSegments = maxSegments; m_nsegments = 0; m_segments = (dtObstacleSegment*)dtAlloc(sizeof(dtObstacleSegment)*m_maxSegments, DT_ALLOC_PERM); if (!m_segments) return false; memset(m_segments, 0, sizeof(dtObstacleSegment)*m_maxSegments); return true; } void dtObstacleAvoidanceQuery::reset() { m_ncircles = 0; m_nsegments = 0; } void dtObstacleAvoidanceQuery::addCircle(const float* pos, const float rad, const float* vel, const float* dvel) { if (m_ncircles >= m_maxCircles) return; dtObstacleCircle* cir = &m_circles[m_ncircles++]; dtVcopy(cir->p, pos); cir->rad = rad; dtVcopy(cir->vel, vel); dtVcopy(cir->dvel, dvel); } void dtObstacleAvoidanceQuery::addSegment(const float* p, const float* q) { if (m_nsegments > m_maxSegments) return; dtObstacleSegment* seg = &m_segments[m_nsegments++]; dtVcopy(seg->p, p); dtVcopy(seg->q, q); } void dtObstacleAvoidanceQuery::prepare(const float* pos, const float* dvel) { // Prepare obstacles for (int i = 0; i < m_ncircles; ++i) { dtObstacleCircle* cir = &m_circles[i]; // Side const float* pa = pos; const float* pb = cir->p; const float orig[3] = {0,0}; float dv[3]; dtVsub(cir->dp,pb,pa); dtVnormalize(cir->dp); dtVsub(dv, cir->dvel, dvel); const float a = dtTriArea2D(orig, cir->dp,dv); if (a < 0.01f) { cir->np[0] = -cir->dp[2]; cir->np[2] = cir->dp[0]; } else { cir->np[0] = cir->dp[2]; cir->np[2] = -cir->dp[0]; } } for (int i = 0; i < m_nsegments; ++i) { dtObstacleSegment* seg = &m_segments[i]; // Precalc if the agent is really close to the segment. const float r = 0.01f; float t; seg->touch = dtDistancePtSegSqr2D(pos, seg->p, seg->q, t) < dtSqr(r); } } float dtObstacleAvoidanceQuery::processSample(const float* vcand, const float cs, const float* pos, const float rad, const float* vel, const float* dvel, dtObstacleAvoidanceDebugData* debug) { // Find min time of impact and exit amongst all obstacles. float tmin = m_params.horizTime; float side = 0; int nside = 0; for (int i = 0; i < m_ncircles; ++i) { const dtObstacleCircle* cir = &m_circles[i]; // RVO float vab[3]; dtVscale(vab, vcand, 2); dtVsub(vab, vab, vel); dtVsub(vab, vab, cir->vel); // Side side += dtClamp(dtMin(dtVdot2D(cir->dp,vab)*0.5f+0.5f, dtVdot2D(cir->np,vab)*2), 0.0f, 1.0f); nside++; float htmin = 0, htmax = 0; if (!sweepCircleCircle(pos,rad, vab, cir->p,cir->rad, htmin, htmax)) continue; // Handle overlapping obstacles. if (htmin < 0.0f && htmax > 0.0f) { // Avoid more when overlapped. htmin = -htmin * 0.5f; } if (htmin >= 0.0f) { // The closest obstacle is somewhere ahead of us, keep track of nearest obstacle. if (htmin < tmin) tmin = htmin; } } for (int i = 0; i < m_nsegments; ++i) { const dtObstacleSegment* seg = &m_segments[i]; float htmin = 0; if (seg->touch) { // Special case when the agent is very close to the segment. float sdir[3], snorm[3]; dtVsub(sdir, seg->q, seg->p); snorm[0] = -sdir[2]; snorm[2] = sdir[0]; // If the velocity is pointing towards the segment, no collision. if (dtVdot2D(snorm, vcand) < 0.0f) continue; // Else immediate collision. htmin = 0.0f; } else { if (!isectRaySeg(pos, vcand, seg->p, seg->q, htmin)) continue; } // Avoid less when facing walls. htmin *= 2.0f; // The closest obstacle is somewhere ahead of us, keep track of nearest obstacle. if (htmin < tmin) tmin = htmin; } // Normalize side bias, to prevent it dominating too much. if (nside) side /= nside; const float vpen = m_params.weightDesVel * (dtVdist2D(vcand, dvel) * m_invVmax); const float vcpen = m_params.weightCurVel * (dtVdist2D(vcand, vel) * m_invVmax); const float spen = m_params.weightSide * side; const float tpen = m_params.weightToi * (1.0f/(0.1f+tmin*m_invHorizTime)); const float penalty = vpen + vcpen + spen + tpen; // Store different penalties for debug viewing if (debug) debug->addSample(vcand, cs, penalty, vpen, vcpen, spen, tpen); return penalty; } int dtObstacleAvoidanceQuery::sampleVelocityGrid(const float* pos, const float rad, const float vmax, const float* vel, const float* dvel, float* nvel, const dtObstacleAvoidanceParams* params, dtObstacleAvoidanceDebugData* debug) { prepare(pos, dvel); memcpy(&m_params, params, sizeof(dtObstacleAvoidanceParams)); m_invHorizTime = 1.0f / m_params.horizTime; m_vmax = vmax; m_invVmax = 1.0f / vmax; dtVset(nvel, 0,0,0); if (debug) debug->reset(); const float cvx = dvel[0] * m_params.velBias; const float cvz = dvel[2] * m_params.velBias; const float cs = vmax * 2 * (1 - m_params.velBias) / (float)(m_params.gridSize-1); const float half = (m_params.gridSize-1)*cs*0.5f; float minPenalty = FLT_MAX; int ns = 0; for (int y = 0; y < m_params.gridSize; ++y) { for (int x = 0; x < m_params.gridSize; ++x) { float vcand[3]; vcand[0] = cvx + x*cs - half; vcand[1] = 0; vcand[2] = cvz + y*cs - half; if (dtSqr(vcand[0])+dtSqr(vcand[2]) > dtSqr(vmax+cs/2)) continue; const float penalty = processSample(vcand, cs, pos,rad,vel,dvel, debug); ns++; if (penalty < minPenalty) { minPenalty = penalty; dtVcopy(nvel, vcand); } } } return ns; } int dtObstacleAvoidanceQuery::sampleVelocityAdaptive(const float* pos, const float rad, const float vmax, const float* vel, const float* dvel, float* nvel, const dtObstacleAvoidanceParams* params, dtObstacleAvoidanceDebugData* debug) { prepare(pos, dvel); memcpy(&m_params, params, sizeof(dtObstacleAvoidanceParams)); m_invHorizTime = 1.0f / m_params.horizTime; m_vmax = vmax; m_invVmax = 1.0f / vmax; dtVset(nvel, 0,0,0); if (debug) debug->reset(); // Build sampling pattern aligned to desired velocity. float pat[(DT_MAX_PATTERN_DIVS*DT_MAX_PATTERN_RINGS+1)*2]; int npat = 0; const int ndivs = (int)m_params.adaptiveDivs; const int nrings= (int)m_params.adaptiveRings; const int depth = (int)m_params.adaptiveDepth; const int nd = dtClamp(ndivs, 1, DT_MAX_PATTERN_DIVS); const int nr = dtClamp(nrings, 1, DT_MAX_PATTERN_RINGS); const float da = (1.0f/nd) * DT_PI*2; const float dang = atan2f(dvel[2], dvel[0]); // Always add sample at zero pat[npat*2+0] = 0; pat[npat*2+1] = 0; npat++; for (int j = 0; j < nr; ++j) { const float r = (float)(nr-j)/(float)nr; float a = dang + (j&1)*0.5f*da; for (int i = 0; i < nd; ++i) { pat[npat*2+0] = cosf(a)*r; pat[npat*2+1] = sinf(a)*r; npat++; a += da; } } // Start sampling. float cr = vmax * (1.0f - m_params.velBias); float res[3]; dtVset(res, dvel[0] * m_params.velBias, 0, dvel[2] * m_params.velBias); int ns = 0; for (int k = 0; k < depth; ++k) { float minPenalty = FLT_MAX; float bvel[3]; dtVset(bvel, 0,0,0); for (int i = 0; i < npat; ++i) { float vcand[3]; vcand[0] = res[0] + pat[i*2+0]*cr; vcand[1] = 0; vcand[2] = res[2] + pat[i*2+1]*cr; if (dtSqr(vcand[0])+dtSqr(vcand[2]) > dtSqr(vmax+0.001f)) continue; const float penalty = processSample(vcand,cr/10, pos,rad,vel,dvel, debug); ns++; if (penalty < minPenalty) { minPenalty = penalty; dtVcopy(bvel, vcand); } } dtVcopy(res, bvel); cr *= 0.5f; } dtVcopy(nvel, res); return ns; }
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: System.Enum #include "System/Enum.hpp" // Completed includes // Type namespace: System namespace System { // Autogenerated type: System.UnescapeMode struct UnescapeMode : public System::Enum { public: // public System.Int32 value__ // Offset: 0x0 int value; // static field const value: static public System.UnescapeMode CopyOnly static constexpr const int CopyOnly = 0; // Get static field: static public System.UnescapeMode CopyOnly static System::UnescapeMode _get_CopyOnly(); // Set static field: static public System.UnescapeMode CopyOnly static void _set_CopyOnly(System::UnescapeMode value); // static field const value: static public System.UnescapeMode Escape static constexpr const int Escape = 1; // Get static field: static public System.UnescapeMode Escape static System::UnescapeMode _get_Escape(); // Set static field: static public System.UnescapeMode Escape static void _set_Escape(System::UnescapeMode value); // static field const value: static public System.UnescapeMode Unescape static constexpr const int Unescape = 2; // Get static field: static public System.UnescapeMode Unescape static System::UnescapeMode _get_Unescape(); // Set static field: static public System.UnescapeMode Unescape static void _set_Unescape(System::UnescapeMode value); // static field const value: static public System.UnescapeMode EscapeUnescape static constexpr const int EscapeUnescape = 3; // Get static field: static public System.UnescapeMode EscapeUnescape static System::UnescapeMode _get_EscapeUnescape(); // Set static field: static public System.UnescapeMode EscapeUnescape static void _set_EscapeUnescape(System::UnescapeMode value); // static field const value: static public System.UnescapeMode V1ToStringFlag static constexpr const int V1ToStringFlag = 4; // Get static field: static public System.UnescapeMode V1ToStringFlag static System::UnescapeMode _get_V1ToStringFlag(); // Set static field: static public System.UnescapeMode V1ToStringFlag static void _set_V1ToStringFlag(System::UnescapeMode value); // static field const value: static public System.UnescapeMode UnescapeAll static constexpr const int UnescapeAll = 8; // Get static field: static public System.UnescapeMode UnescapeAll static System::UnescapeMode _get_UnescapeAll(); // Set static field: static public System.UnescapeMode UnescapeAll static void _set_UnescapeAll(System::UnescapeMode value); // static field const value: static public System.UnescapeMode UnescapeAllOrThrow static constexpr const int UnescapeAllOrThrow = 24; // Get static field: static public System.UnescapeMode UnescapeAllOrThrow static System::UnescapeMode _get_UnescapeAllOrThrow(); // Set static field: static public System.UnescapeMode UnescapeAllOrThrow static void _set_UnescapeAllOrThrow(System::UnescapeMode value); // Creating value type constructor for type: UnescapeMode UnescapeMode(int value_ = {}) : value{value_} {} }; // System.UnescapeMode } #include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(System::UnescapeMode, "System", "UnescapeMode"); #pragma pack(pop)
// Copyright 2020 The Fuchsia Authors // // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file or at // https://opensource.org/licenses/MIT #include <stdio.h> #include <zircon/assert.h> #include <zircon/boot/image.h> #include <phys/frame-pointer.h> #include <phys/stack.h> #include <phys/symbolize.h> #include "test-main.h" namespace { // BackTrace() omits its immediate caller, so Collect* itself won't appear. [[gnu::noinline]] auto CollectFp() { return FramePointer::BackTrace(); } [[gnu::noinline]] auto CollectScs() { return boot_shadow_call_stack.BackTrace(); } [[gnu::noinline]] PHYS_SINGLETHREAD int Find() { constexpr auto bt_depth = [](auto&& bt) { int depth = 0; for ([[maybe_unused]] auto pc : bt) { ++depth; } return depth; }; printf("Collecting backtraces...\n"); gSymbolize->Context(); const auto fp_bt = CollectFp(); const int fp_depth = bt_depth(fp_bt); printf("Printing frame pointer backtrace, %d frames:\n", fp_depth); gSymbolize->BackTrace(fp_bt); const auto scs_bt = CollectScs(); const int scs_depth = bt_depth(scs_bt); if (BootShadowCallStack::kEnabled) { printf("Printing shadow call stack backtrace, %d frames:\n", scs_depth); gSymbolize->BackTrace(scs_bt); ZX_ASSERT(fp_depth == scs_depth); struct Both { decltype(fp_bt.begin()) fp; decltype(scs_bt.begin()) scs; bool first = true; }; for (auto [fp, scs, first] = Both{fp_bt.begin(), scs_bt.begin()}; fp != fp_bt.end(); ++fp, ++scs, first = false) { ZX_ASSERT(scs != scs_bt.end()); // The first PC is the collection call site above, which differs between // the two collections. The rest should match. if (first) { ZX_ASSERT(*scs != *fp); } else { ZX_ASSERT(*scs == *fp); } } } else { ZX_ASSERT(scs_bt.empty()); ZX_ASSERT(scs_depth == 0); } return fp_depth - 1; } [[gnu::noinline]] PHYS_SINGLETHREAD int Outer() { return Find() - 1; } [[gnu::noinline]] PHYS_SINGLETHREAD int Otter() { return Outer() - 1; } [[gnu::noinline]] PHYS_SINGLETHREAD int Foo() { return Otter() - 1; } } // namespace int TestMain(void* zbi, arch::EarlyTicks) { MainSymbolize symbolize("backtrace-test"); if (zbi && static_cast<zbi_header_t*>(zbi)->type == ZBI_TYPE_CONTAINER) { ZX_ASSERT(Foo() == 4); // _start -> PhysMain -> ZbiMain -> TestMain -> Foo } else { ZX_ASSERT(Foo() == 3); // _start -> PhysMain -> TestMain -> Foo... } return 0; }
#include <GL/glew.h> #include "imgui-SFML.h" #include "imgui.h" #include <SFML/OpenGL.hpp> #include <SFML/Window/Event.hpp> #include <SFML/Window/Window.hpp> #include <cstddef> // offsetof, NULL #include <cassert> // Supress warnings caused by converting from uint to void* in pCmd->TextureID #ifdef __clang__ #pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning : cast to 'void *' from smaller integer type 'int' #elif defined(__GNUC__) #pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size #endif static bool s_windowHasFocus = true; static bool s_mousePressed[3] = { false, false, false }; static GLuint g_FontTexture = 0; static int g_ShaderHandle = 0, g_VertHandle = 0, g_FragHandle = 0; static int g_AttribLocationTex = 0, g_AttribLocationProjMtx = 0; static int g_AttribLocationPosition = 0, g_AttribLocationUV = 0, g_AttribLocationColor = 0; static unsigned int g_VboHandle = 0, g_VaoHandle = 0, g_ElementsHandle = 0; namespace { void RenderDrawLists(ImDrawData* draw_data); // rendering callback function prototype } // anonymous namespace for helper / "private" functions namespace ImGui { namespace SFML { void Init(sf::Window& target) { ImGuiIO& io = ImGui::GetIO(); // init keyboard mapping io.KeyMap[ImGuiKey_Tab] = sf::Keyboard::Tab; io.KeyMap[ImGuiKey_LeftArrow] = sf::Keyboard::Left; io.KeyMap[ImGuiKey_RightArrow] = sf::Keyboard::Right; io.KeyMap[ImGuiKey_UpArrow] = sf::Keyboard::Up; io.KeyMap[ImGuiKey_DownArrow] = sf::Keyboard::Down; io.KeyMap[ImGuiKey_PageUp] = sf::Keyboard::PageUp; io.KeyMap[ImGuiKey_PageDown] = sf::Keyboard::PageDown; io.KeyMap[ImGuiKey_Home] = sf::Keyboard::Home; io.KeyMap[ImGuiKey_End] = sf::Keyboard::End; io.KeyMap[ImGuiKey_Delete] = sf::Keyboard::Delete; io.KeyMap[ImGuiKey_Backspace] = sf::Keyboard::BackSpace; io.KeyMap[ImGuiKey_Enter] = sf::Keyboard::Return; io.KeyMap[ImGuiKey_Escape] = sf::Keyboard::Escape; io.KeyMap[ImGuiKey_A] = sf::Keyboard::A; io.KeyMap[ImGuiKey_C] = sf::Keyboard::C; io.KeyMap[ImGuiKey_V] = sf::Keyboard::V; io.KeyMap[ImGuiKey_X] = sf::Keyboard::X; io.KeyMap[ImGuiKey_Y] = sf::Keyboard::Y; io.KeyMap[ImGuiKey_Z] = sf::Keyboard::Z; // init rendering io.DisplaySize = static_cast<sf::Vector2f>(target.getSize()); io.FontGlobalScale = 2.f; io.RenderDrawListsFn = RenderDrawLists; // set render callback } void ProcessEvent(const sf::Event& event) { ImGuiIO& io = ImGui::GetIO(); if (s_windowHasFocus) { switch (event.type) { case sf::Event::MouseButtonPressed: // fall-through case sf::Event::MouseButtonReleased: { int button = event.mouseButton.button; if (event.type == sf::Event::MouseButtonPressed && button >= 0 && button < 3) { s_mousePressed[event.mouseButton.button] = true; } } break; case sf::Event::MouseWheelMoved: io.MouseWheel += static_cast<float>(event.mouseWheel.delta); break; case sf::Event::KeyPressed: // fall-through case sf::Event::KeyReleased: io.KeysDown[event.key.code] = (event.type == sf::Event::KeyPressed); io.KeyCtrl = event.key.control; io.KeyShift = event.key.shift; io.KeyAlt = event.key.alt; break; case sf::Event::TextEntered: if (event.text.unicode > 0 && event.text.unicode < 0x10000) { io.AddInputCharacter(static_cast<ImWchar>(event.text.unicode)); } break; default: break; } } switch (event.type) { case sf::Event::LostFocus: s_windowHasFocus = false; break; case sf::Event::GainedFocus: s_windowHasFocus = true; break; default: break; } } void Update(sf::Window& window, sf::Time dt) { Update(sf::Mouse::getPosition(window), static_cast<sf::Vector2f>(window.getSize()), dt); window.setMouseCursorVisible(!ImGui::GetIO().MouseDrawCursor); // don't draw mouse cursor if ImGui draws it } void Update(const sf::Vector2i& mousePos, const sf::Vector2f& displaySize, sf::Time dt) { ImGuiIO& io = ImGui::GetIO(); io.DisplaySize = displaySize; io.DeltaTime = dt.asSeconds(); if (s_windowHasFocus) { io.MousePos = mousePos; for (int i = 0; i < 3; ++i) { io.MouseDown[i] = s_mousePressed[i] || sf::Mouse::isButtonPressed((sf::Mouse::Button)i); s_mousePressed[i] = false; } } if (!g_FontTexture) CreateDeviceObjects(); assert(io.Fonts->Fonts.Size > 0); // You forgot to create and set up font atlas (see createFontTexture) ImGui::NewFrame(); } void Shutdown() { ImGui::GetIO().Fonts->TexID = NULL; ImGui::Shutdown(); // need to specify namespace here, otherwise ImGui::SFML::Shutdown would be called } bool CreateDeviceObjects(){ // Backup GL state GLint last_texture, last_array_buffer, last_vertex_array; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer); glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array); const GLchar *vertex_shader = "#version 330\n" "uniform mat4 ProjMtx;\n" "in vec2 Position;\n" "in vec2 UV;\n" "in vec4 Color;\n" "out vec2 Frag_UV;\n" "out vec4 Frag_Color;\n" "void main()\n" "{\n" " Frag_UV = UV;\n" " Frag_Color = Color;\n" " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n" "}\n"; const GLchar* fragment_shader = "#version 330\n" "uniform sampler2D Texture;\n" "in vec2 Frag_UV;\n" "in vec4 Frag_Color;\n" "out vec4 Out_Color;\n" "void main()\n" "{\n" " Out_Color = Frag_Color * texture( Texture, Frag_UV.st);\n" "}\n"; g_ShaderHandle = glCreateProgram(); g_VertHandle = glCreateShader(GL_VERTEX_SHADER); g_FragHandle = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(g_VertHandle, 1, &vertex_shader, 0); glShaderSource(g_FragHandle, 1, &fragment_shader, 0); glCompileShader(g_VertHandle); glCompileShader(g_FragHandle); glAttachShader(g_ShaderHandle, g_VertHandle); glAttachShader(g_ShaderHandle, g_FragHandle); glLinkProgram(g_ShaderHandle); g_AttribLocationTex = glGetUniformLocation(g_ShaderHandle, "Texture"); g_AttribLocationProjMtx = glGetUniformLocation(g_ShaderHandle, "ProjMtx"); g_AttribLocationPosition = glGetAttribLocation(g_ShaderHandle, "Position"); g_AttribLocationUV = glGetAttribLocation(g_ShaderHandle, "UV"); g_AttribLocationColor = glGetAttribLocation(g_ShaderHandle, "Color"); glGenBuffers(1, &g_VboHandle); glGenBuffers(1, &g_ElementsHandle); glGenVertexArrays(1, &g_VaoHandle); glBindVertexArray(g_VaoHandle); glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle); glEnableVertexAttribArray(g_AttribLocationPosition); glEnableVertexAttribArray(g_AttribLocationUV); glEnableVertexAttribArray(g_AttribLocationColor); #define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT)) glVertexAttribPointer(g_AttribLocationPosition, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, pos)); glVertexAttribPointer(g_AttribLocationUV, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, uv)); glVertexAttribPointer(g_AttribLocationColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, col)); #undef OFFSETOF CreateFontsTexture(); // Restore modified GL state glBindTexture(GL_TEXTURE_2D, last_texture); glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer); glBindVertexArray(last_vertex_array); return true; } void CreateFontsTexture() { // Build texture atlas ImGuiIO& io = ImGui::GetIO(); unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Load as RGBA 32-bits for OpenGL3 demo because it is more likely to be compatible with user's existing shader. // Upload texture to graphics system GLint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); glGenTextures(1, &g_FontTexture); glBindTexture(GL_TEXTURE_2D, g_FontTexture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels); // Store our identifier io.Fonts->TexID = (void *)(intptr_t)g_FontTexture; // Restore state glBindTexture(GL_TEXTURE_2D, last_texture); } void InvalidateDeviceObjects() { if (g_VaoHandle) glDeleteVertexArrays(1, &g_VaoHandle); if (g_VboHandle) glDeleteBuffers(1, &g_VboHandle); if (g_ElementsHandle) glDeleteBuffers(1, &g_ElementsHandle); g_VaoHandle = g_VboHandle = g_ElementsHandle = 0; if (g_ShaderHandle && g_VertHandle) glDetachShader(g_ShaderHandle, g_VertHandle); if (g_VertHandle) glDeleteShader(g_VertHandle); g_VertHandle = 0; if (g_ShaderHandle && g_FragHandle) glDetachShader(g_ShaderHandle, g_FragHandle); if (g_FragHandle) glDeleteShader(g_FragHandle); g_FragHandle = 0; if (g_ShaderHandle) glDeleteProgram(g_ShaderHandle); g_ShaderHandle = 0; if (g_FontTexture) { glDeleteTextures(1, &g_FontTexture); ImGui::GetIO().Fonts->TexID = 0; g_FontTexture = 0; } } } // end of namespace SFML } // end of namespace ImGui namespace { // Rendering callback void RenderDrawLists(ImDrawData* draw_data) { GLint last_program, last_texture; glGetIntegerv(GL_CURRENT_PROGRAM, &last_program); glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); glEnable(GL_BLEND); glBlendEquation(GL_FUNC_ADD); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); glEnable(GL_SCISSOR_TEST); glActiveTexture(GL_TEXTURE0); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); // Handle cases of screen coordinates != from framebuffer coordinates (e.g. retina displays) ImGuiIO& io = ImGui::GetIO(); float fb_height = io.DisplaySize.y * io.DisplayFramebufferScale.y; draw_data->ScaleClipRects(io.DisplayFramebufferScale); // Setup orthographic projection matrix const float ortho_projection[4][4] = { { 2.0f/io.DisplaySize.x, 0.0f, 0.0f, 0.0f }, { 0.0f, 2.0f/-io.DisplaySize.y, 0.0f, 0.0f }, { 0.0f, 0.0f, -1.0f, 0.0f }, {-1.0f, 1.0f, 0.0f, 1.0f }, }; glUseProgram(g_ShaderHandle); glUniform1i(g_AttribLocationTex, 0); glUniformMatrix4fv(g_AttribLocationProjMtx, 1, GL_FALSE, &ortho_projection[0][0]); glBindVertexArray(g_VaoHandle); for (int n = 0; n < draw_data->CmdListsCount; n++) { const ImDrawList* cmd_list = draw_data->CmdLists[n]; const ImDrawIdx* idx_buffer_offset = 0; glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle); glBufferData(GL_ARRAY_BUFFER, (GLsizeiptr)cmd_list->VtxBuffer.size() * sizeof(ImDrawVert), (GLvoid*)&cmd_list->VtxBuffer.front(), GL_STREAM_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_ElementsHandle); glBufferData(GL_ELEMENT_ARRAY_BUFFER, (GLsizeiptr)cmd_list->IdxBuffer.size() * sizeof(ImDrawIdx), (GLvoid*)&cmd_list->IdxBuffer.front(), GL_STREAM_DRAW); for (const ImDrawCmd* pcmd = cmd_list->CmdBuffer.begin(); pcmd != cmd_list->CmdBuffer.end(); pcmd++) { if (pcmd->UserCallback) { pcmd->UserCallback(cmd_list, pcmd); } else { glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->TextureId); glScissor((int)pcmd->ClipRect.x, (int)(fb_height - pcmd->ClipRect.w), (int)(pcmd->ClipRect.z - pcmd->ClipRect.x), (int)(pcmd->ClipRect.w - pcmd->ClipRect.y)); glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, GL_UNSIGNED_SHORT, idx_buffer_offset); } idx_buffer_offset += pcmd->ElemCount; } } // Restore modified state glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glUseProgram(last_program); glDisable(GL_SCISSOR_TEST); glBindTexture(GL_TEXTURE_2D, last_texture); } } // end of anonymous namespace
#include "IRremote.h" #include "IRremoteInt.h" //+============================================================================= // Gets one undecoded level at a time from the raw buffer. // The RC5/6 decoding is easier if the data is broken into time intervals. // E.g. if the buffer has MARK for 2 time intervals and SPACE for 1, // successive calls to getRClevel will return MARK, MARK, SPACE. // offset and used are updated to keep track of the current position. // t1 is the time interval for a single bit in microseconds. // Returns -1 for error (measured time interval is not a multiple of t1). // #if (DECODE_RC5 || DECODE_RC6) int IRrecv::getRClevel (decode_results *results, int *offset, int *used, int t1) { int width; int val; int correction; int avail; if (*offset >= results->rawlen) return SPACE ; // After end of recorded buffer, assume SPACE. width = results->rawbuf[*offset]; val = ((*offset) % 2) ? MARK : SPACE; correction = (val == MARK) ? MARK_EXCESS : - MARK_EXCESS; if (MATCH(width, ( t1) + correction)) avail = 1 ; else if (MATCH(width, (2*t1) + correction)) avail = 2 ; else if (MATCH(width, (3*t1) + correction)) avail = 3 ; else return -1 ; (*used)++; if (*used >= avail) { *used = 0; (*offset)++; } DBG_PRINTLN( (val == MARK) ? "MARK" : "SPACE" ); return val; } #endif //============================================================================== // RRRR CCCC 55555 // R R C 5 // RRRR C 5555 // R R C 5 // R R CCCC 5555 // // NB: First bit must be a one (start bit) // #define MIN_RC5_SAMPLES 11 #define RC5_T1 889 #define RC5_RPT_LENGTH 46000 //+============================================================================= #if SEND_RC5 void IRsend::sendRC5 (unsigned long data, int nbits) { // Set IR carrier frequency enableIROut(36); // Start mark(RC5_T1); space(RC5_T1); mark(RC5_T1); // Data for (unsigned long mask = 1UL << (nbits - 1); mask; mask >>= 1) { if (data & mask) { space(RC5_T1); // 1 is space, then mark mark(RC5_T1); } else { mark(RC5_T1); space(RC5_T1); } } space(0); // Always end with the LED off } #endif //+============================================================================= #if DECODE_RC5 bool IRrecv::decodeRC5 (decode_results *results) { int nbits; long data = 0; int used = 0; int offset = 1; // Skip gap space if (irparams.rawlen < MIN_RC5_SAMPLES + 2) return false ; // Get start bits if (getRClevel(results, &offset, &used, RC5_T1) != MARK) return false ; if (getRClevel(results, &offset, &used, RC5_T1) != SPACE) return false ; if (getRClevel(results, &offset, &used, RC5_T1) != MARK) return false ; for (nbits = 0; offset < irparams.rawlen; nbits++) { int levelA = getRClevel(results, &offset, &used, RC5_T1); int levelB = getRClevel(results, &offset, &used, RC5_T1); if ((levelA == SPACE) && (levelB == MARK )) data = (data << 1) | 1 ; else if ((levelA == MARK ) && (levelB == SPACE)) data = (data << 1) | 0 ; else return false ; } // Success results->bits = nbits; results->value = data; results->decode_type = RC5; return true; } #endif //+============================================================================= // RRRR CCCC 6666 // R R C 6 // RRRR C 6666 // R R C 6 6 // R R CCCC 666 // // NB : Caller needs to take care of flipping the toggle bit // #define MIN_RC6_SAMPLES 1 #define RC6_HDR_MARK 2666 #define RC6_HDR_SPACE 889 #define RC6_T1 444 #define RC6_RPT_LENGTH 46000 #if SEND_RC6 void IRsend::sendRC6 (unsigned long data, int nbits) { // Set IR carrier frequency enableIROut(36); // Header mark(RC6_HDR_MARK); space(RC6_HDR_SPACE); // Start bit mark(RC6_T1); space(RC6_T1); // Data for (unsigned long i = 1, mask = 1UL << (nbits - 1); mask; i++, mask >>= 1) { // The fourth bit we send is a "double width trailer bit" int t = (i == 4) ? (RC6_T1 * 2) : (RC6_T1) ; if (data & mask) { mark(t); space(t); } else { space(t); mark(t); } } space(0); // Always end with the LED off } #endif //+============================================================================= #if DECODE_RC6 bool IRrecv::decodeRC6 (decode_results *results) { int nbits; long data = 0; int used = 0; int offset = 1; // Skip first space if (results->rawlen < MIN_RC6_SAMPLES) return false ; // Initial mark if (!MATCH_MARK(results->rawbuf[offset++], RC6_HDR_MARK)) return false ; if (!MATCH_SPACE(results->rawbuf[offset++], RC6_HDR_SPACE)) return false ; // Get start bit (1) if (getRClevel(results, &offset, &used, RC6_T1) != MARK) return false ; if (getRClevel(results, &offset, &used, RC6_T1) != SPACE) return false ; for (nbits = 0; offset < results->rawlen; nbits++) { int levelA, levelB; // Next two levels levelA = getRClevel(results, &offset, &used, RC6_T1); if (nbits == 3) { // T bit is double wide; make sure second half matches if (levelA != getRClevel(results, &offset, &used, RC6_T1)) return false; } levelB = getRClevel(results, &offset, &used, RC6_T1); if (nbits == 3) { // T bit is double wide; make sure second half matches if (levelB != getRClevel(results, &offset, &used, RC6_T1)) return false; } if ((levelA == MARK ) && (levelB == SPACE)) data = (data << 1) | 1 ; // inverted compared to RC5 else if ((levelA == SPACE) && (levelB == MARK )) data = (data << 1) | 0 ; // ... else return false ; // Error } // Success results->bits = nbits; results->value = data; results->decode_type = RC6; return true; } #endif
#include "MipsGenerator.h" #include "LinearDescriptorAllocator.h" #include "DWParam.h" #include "ShaderUtility.h" #include "d3dx12.h" //https://slindev.com/d3d12-texture-mipmap-generation/ namespace adria { MipsGenerator::MipsGenerator(ID3D12Device* device, UINT max_textures) : device(device) { CreateRootSignature(); CreatePSO(); CreateHeap(max_textures); } void MipsGenerator::Add(ID3D12Resource* texture) { resources.push_back(texture); } void MipsGenerator::Generate(ID3D12GraphicsCommandList* command_list) { ID3D12DescriptorHeap* pp_heaps[] = { descriptor_allocator->Heap() }; command_list->SetDescriptorHeaps(1, pp_heaps); //Set root signature, pso and descriptor heap command_list->SetComputeRootSignature(root_signature.Get()); command_list->SetPipelineState(pso.Get()); for (auto texture : resources) { //Prepare the shader resource view description for the source texture D3D12_SHADER_RESOURCE_VIEW_DESC src_srv_desc = {}; src_srv_desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; src_srv_desc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; //Prepare the unordered access view description for the destination texture D3D12_UNORDERED_ACCESS_VIEW_DESC dst_uav_desc = {}; dst_uav_desc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; D3D12_RESOURCE_DESC tex_desc = texture->GetDesc(); UINT const mipmap_levels = tex_desc.MipLevels; auto transition_barrier = CD3DX12_RESOURCE_BARRIER::Transition(texture, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); command_list->ResourceBarrier(1, &transition_barrier); OffsetType i{}; for (UINT top_mip = 0; top_mip < mipmap_levels - 1; top_mip++) { //Get mipmap dimensions UINT dst_width = (std::max)((UINT)tex_desc.Width >> (top_mip + 1), 1u); UINT dst_height = (std::max)(tex_desc.Height >> (top_mip + 1), 1u); i = descriptor_allocator->AllocateRange(2); D3D12_CPU_DESCRIPTOR_HANDLE cpu_handle1 = descriptor_allocator->GetCpuHandle(i); D3D12_GPU_DESCRIPTOR_HANDLE gpu_handle1 = descriptor_allocator->GetGpuHandle(i); src_srv_desc.Format = tex_desc.Format; src_srv_desc.Texture2D.MipLevels = 1; src_srv_desc.Texture2D.MostDetailedMip = top_mip; device->CreateShaderResourceView(texture, &src_srv_desc, cpu_handle1); D3D12_CPU_DESCRIPTOR_HANDLE cpu_handle2 = descriptor_allocator->GetCpuHandle(i + 1); D3D12_GPU_DESCRIPTOR_HANDLE gpu_handle2 = descriptor_allocator->GetGpuHandle(i + 1); dst_uav_desc.Format = tex_desc.Format; dst_uav_desc.Texture2D.MipSlice = top_mip + 1; device->CreateUnorderedAccessView(texture, nullptr, &dst_uav_desc, cpu_handle2); //Pass the destination texture pixel size to the shader as constants command_list->SetComputeRoot32BitConstant(0, DWParam(1.0f / dst_width).Uint, 0); command_list->SetComputeRoot32BitConstant(0, DWParam(1.0f / dst_height).Uint, 1); command_list->SetComputeRootDescriptorTable(1, gpu_handle1); command_list->SetComputeRootDescriptorTable(2, gpu_handle2); //Dispatch the compute shader with one thread per 8x8 pixels command_list->Dispatch((std::max)(dst_width / 8u, 1u), (std::max)(dst_height / 8u, 1u), 1); //Wait for all accesses to the destination texture UAV to be finished before generating the next mipmap, as it will be the source texture for the next mipmap auto uav_barrier = CD3DX12_RESOURCE_BARRIER::UAV(texture); command_list->ResourceBarrier(1, &uav_barrier); } transition_barrier = CD3DX12_RESOURCE_BARRIER::Transition(texture, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE); command_list->ResourceBarrier(1, &transition_barrier); } resources.clear(); descriptor_allocator->Clear(); } void MipsGenerator::CreateRootSignature() { D3D12_FEATURE_DATA_ROOT_SIGNATURE feature_data = {}; feature_data.HighestVersion = D3D_ROOT_SIGNATURE_VERSION_1_1; if (FAILED(device->CheckFeatureSupport(D3D12_FEATURE_ROOT_SIGNATURE, &feature_data, sizeof(feature_data)))) { feature_data.HighestVersion = D3D_ROOT_SIGNATURE_VERSION_1_0; } CD3DX12_DESCRIPTOR_RANGE1 srv_uav_ranges[2] = {}; CD3DX12_ROOT_PARAMETER1 root_parameters[3] = {}; srv_uav_ranges[0].Init(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0); srv_uav_ranges[1].Init(D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1, 0, 0); root_parameters[0].InitAsConstants(2, 0); root_parameters[1].InitAsDescriptorTable(1, &srv_uav_ranges[0]); root_parameters[2].InitAsDescriptorTable(1, &srv_uav_ranges[1]); D3D12_ROOT_SIGNATURE_FLAGS root_signature_flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT; D3D12_STATIC_SAMPLER_DESC sampler = {}; sampler.Filter = D3D12_FILTER_MIN_MAG_LINEAR_MIP_POINT; sampler.AddressU = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; sampler.AddressV = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; sampler.AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; sampler.MipLODBias = 0.0f; sampler.ComparisonFunc = D3D12_COMPARISON_FUNC_NEVER; sampler.MinLOD = 0.0f; sampler.MaxLOD = D3D12_FLOAT32_MAX; sampler.MaxAnisotropy = 0; sampler.BorderColor = D3D12_STATIC_BORDER_COLOR_OPAQUE_BLACK; sampler.ShaderRegister = 0; sampler.RegisterSpace = 0; sampler.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; CD3DX12_VERSIONED_ROOT_SIGNATURE_DESC root_signature_desc{}; root_signature_desc.Init_1_1(_countof(root_parameters), root_parameters, 1, &sampler, D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT); Microsoft::WRL::ComPtr<ID3DBlob> signature; Microsoft::WRL::ComPtr<ID3DBlob> error; BREAK_IF_FAILED(D3DX12SerializeVersionedRootSignature(&root_signature_desc, feature_data.HighestVersion, &signature, &error)); BREAK_IF_FAILED(device->CreateRootSignature(0, signature->GetBufferPointer(), signature->GetBufferSize(), IID_PPV_ARGS(&root_signature))); } void MipsGenerator::CreatePSO() { ShaderBlob cs_blob; ShaderInfo info{}; info.shadersource = "Resources\\Shaders\\Misc\\GenerateMipsCS.hlsl"; info.stage = ShaderStage::CS; ShaderUtility::CompileShader(info, cs_blob); //Create pipeline state object for the compute shader using the root signature. D3D12_COMPUTE_PIPELINE_STATE_DESC pso_desc = {}; pso_desc.pRootSignature = root_signature.Get(); pso_desc.CS = cs_blob; device->CreateComputePipelineState(&pso_desc, IID_PPV_ARGS(&pso)); } void MipsGenerator::CreateHeap(UINT max_textures) //approximate number of descriptors as : ~ max_textures * 2 * 10 (avg mip levels) { D3D12_DESCRIPTOR_HEAP_DESC shader_visible_desc = {}; shader_visible_desc.NumDescriptors = 20 * max_textures + 200; shader_visible_desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE; shader_visible_desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; descriptor_allocator = std::make_unique<LinearDescriptorAllocator>(device, shader_visible_desc); } }
// @COPYRIGHT@ // Licensed under MIT license (LICENSE.txt) // clxx/app/exception.hpp /** // doc: clxx/app/exception.hpp {{{ * \todo Write documentation */ // }}} #ifndef CLXX_APP_EXCEPTION_HPP_INCLUDED #define CLXX_APP_EXCEPTION_HPP_INCLUDED /* clxx includes */ #include <clxx/common/exception.hpp> namespace clxx { namespace app { class exception : public clxx::exception { }; } } // end namespace clxx::app #endif // vim: set expandtab tabstop=2 shiftwidth=2: // vim: set foldmethod=marker foldcolumn=4:
/* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ /* * This GM exercises stroking of paths with large stroke lengths, which is * referred to as "overstroke" for brevity. In Skia as of 8/2016 we offset * each part of the curve the request amount even if it makes the offsets * overlap and create holes. There is not a really great algorithm for this * and several other 2D graphics engines have the same bug. * * If we run this using Nvidia Path Renderer with: * `path/to/dm --match OverStroke -w gm_out --gpu --config nvpr16` * then we get correct results, so that is a possible direction of attack - * use the GPU and a completely different algorithm to get correctness in * Skia. * * See crbug.com/589769 skbug.com/5405 skbug.com/5406 */ #include "gm.h" #include "SkPaint.h" #include "SkPath.h" #include "SkPathMeasure.h" const SkScalar OVERSTROKE_WIDTH = 500.0f; const SkScalar NORMALSTROKE_WIDTH = 3.0f; //////// path and paint builders SkPaint make_normal_paint() { SkPaint p; p.setAntiAlias(true); p.setStyle(SkPaint::kStroke_Style); p.setStrokeWidth(NORMALSTROKE_WIDTH); p.setColor(SK_ColorBLUE); return p; } SkPaint make_overstroke_paint() { SkPaint p; p.setAntiAlias(true); p.setStyle(SkPaint::kStroke_Style); p.setStrokeWidth(OVERSTROKE_WIDTH); return p; } SkPath quad_path() { SkPath path; path.moveTo(0, 0); path.lineTo(100, 0); path.quadTo(50, -40, 0, 0); path.close(); return path; } SkPath cubic_path() { SkPath path; path.moveTo(0, 0); path.cubicTo(25, 75, 75, -50, 100, 0); return path; } SkPath oval_path() { SkRect oval = SkRect::MakeXYWH(0, -25, 100, 50); SkPath path; path.arcTo(oval, 0, 359, true); path.close(); return path; } SkPath ribs_path(SkPath path, SkScalar radius) { SkPath ribs; const SkScalar spacing = 5.0f; float accum = 0.0f; SkPathMeasure meas(path, false); SkScalar length = meas.getLength(); SkPoint pos; SkVector tan; while (accum < length) { if (meas.getPosTan(accum, &pos, &tan)) { tan.scale(radius); tan.rotateCCW(); ribs.moveTo(pos.x() + tan.x(), pos.y() + tan.y()); ribs.lineTo(pos.x() - tan.x(), pos.y() - tan.y()); } accum += spacing; } return ribs; } void draw_ribs(SkCanvas *canvas, SkPath path) { SkPath ribs = ribs_path(path, OVERSTROKE_WIDTH/2.0f); SkPaint p = make_normal_paint(); p.setStrokeWidth(1); p.setColor(SK_ColorBLUE); p.setColor(SK_ColorGREEN); canvas->drawPath(ribs, p); } ///////// quads void draw_small_quad(SkCanvas *canvas) { // scaled so it's visible // canvas->scale(8, 8); SkPaint p = make_normal_paint(); SkPath path = quad_path(); draw_ribs(canvas, path); canvas->drawPath(path, p); } void draw_large_quad(SkCanvas *canvas) { SkPaint p = make_overstroke_paint(); SkPath path = quad_path(); canvas->drawPath(path, p); draw_ribs(canvas, path); } void draw_quad_fillpath(SkCanvas *canvas) { SkPath path = quad_path(); SkPaint p = make_overstroke_paint(); SkPaint fillp = make_normal_paint(); fillp.setColor(SK_ColorMAGENTA); SkPath fillpath; p.getFillPath(path, &fillpath); canvas->drawPath(fillpath, fillp); } void draw_stroked_quad(SkCanvas *canvas) { canvas->translate(400, 0); draw_large_quad(canvas); draw_quad_fillpath(canvas); } ////////// cubics void draw_small_cubic(SkCanvas *canvas) { SkPaint p = make_normal_paint(); SkPath path = cubic_path(); draw_ribs(canvas, path); canvas->drawPath(path, p); } void draw_large_cubic(SkCanvas *canvas) { SkPaint p = make_overstroke_paint(); SkPath path = cubic_path(); canvas->drawPath(path, p); draw_ribs(canvas, path); } void draw_cubic_fillpath(SkCanvas *canvas) { SkPath path = cubic_path(); SkPaint p = make_overstroke_paint(); SkPaint fillp = make_normal_paint(); fillp.setColor(SK_ColorMAGENTA); SkPath fillpath; p.getFillPath(path, &fillpath); canvas->drawPath(fillpath, fillp); } void draw_stroked_cubic(SkCanvas *canvas) { canvas->translate(400, 0); draw_large_cubic(canvas); draw_cubic_fillpath(canvas); } ////////// ovals void draw_small_oval(SkCanvas *canvas) { SkPaint p = make_normal_paint(); SkPath path = oval_path(); draw_ribs(canvas, path); canvas->drawPath(path, p); } void draw_large_oval(SkCanvas *canvas) { SkPaint p = make_overstroke_paint(); SkPath path = oval_path(); canvas->drawPath(path, p); draw_ribs(canvas, path); } void draw_oval_fillpath(SkCanvas *canvas) { SkPath path = oval_path(); SkPaint p = make_overstroke_paint(); SkPaint fillp = make_normal_paint(); fillp.setColor(SK_ColorMAGENTA); SkPath fillpath; p.getFillPath(path, &fillpath); canvas->drawPath(fillpath, fillp); } void draw_stroked_oval(SkCanvas *canvas) { canvas->translate(400, 0); draw_large_oval(canvas); draw_oval_fillpath(canvas); } ////////// gm void (*examples[])(SkCanvas *canvas) = { draw_small_quad, draw_stroked_quad, draw_small_cubic, draw_stroked_cubic, draw_small_oval, draw_stroked_oval, }; DEF_SIMPLE_GM(OverStroke, canvas, 500, 500) { const size_t length = sizeof(examples) / sizeof(examples[0]); const size_t width = 2; for (size_t i = 0; i < length; i++) { int x = (int)(i % width); int y = (int)(i / width); canvas->save(); canvas->translate(150.0f * x, 150.0f * y); canvas->scale(0.2f, 0.2f); canvas->translate(300.0f, 400.0f); examples[i](canvas); canvas->restore(); } }
/* * Copyright (C) 2019-2020 LEIDOS. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ #ifndef __ARBITRATOR_INCLUDE_FIXED_PRIORITY_COST_FUNCTION_HPP__ #define __ARBITRATOR_INCLUDE_FIXED_PRIORITY_COST_FUNCTION_HPP__ #include "cost_function.hpp" #include <map> #include <string> namespace arbitrator { /** * \brief Implementation of the CostFunction interface * * Implements costs by associating a fixed priority number with each plugin * (as specified by configuration). This priority is then normalized across * all plugins, and then an inverse is computed to arrive at the cost per * unit distance for that plugins. * * e.g. Three plugins with priority 20, 10, and 5 will respectively have * costs 0, 0.5, 0.75 per unit distance. */ class FixedPriorityCostFunction : public CostFunction { public: /** * \brief Constructor for FixedPriorityCostFunction * \param nh A publically namespaced ("/") ros::NodeHandle */ FixedPriorityCostFunction(const std::map<std::string, double> &plugin_priorities); /** * \brief Compute the unit cost over distance of a given maneuver plan * \param plan The plan to evaluate * \return double The total cost divided by the total distance of the plan */ double compute_total_cost(const cav_msgs::ManeuverPlan& plan); /** * \brief Compute the unit cost over distance of a given maneuver plan * \param plan The plan to evaluate * \return double The total cost divided by the total distance of the plan */ double compute_cost_per_unit_distance(const cav_msgs::ManeuverPlan& plan); private: std::map<std::string, double> plugin_costs_; }; }; #endif //__ARBITRATOR_INCLUDE_FIXED_PRIORITY_COST_FUNCTION_HPP__
// Copyright (c) 2014-2018, The Simplix Project // // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other // materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be // used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers #include "gtest/gtest.h" #include "cryptonote_basic/cryptonote_format_utils.h" using namespace cryptonote; namespace { void do_pos_test(uint64_t expected, const std::string& str) { uint64_t val; std::string number_str = str; std::replace(number_str.begin(), number_str.end(), '_', '.'); number_str.erase(std::remove(number_str.begin(), number_str.end(), '~'), number_str.end()); ASSERT_TRUE(parse_amount(val, number_str)); ASSERT_EQ(expected, val); } void do_neg_test(const std::string& str) { uint64_t val; std::string number_str = str; std::replace(number_str.begin(), number_str.end(), '_', '.'); number_str.erase(std::remove(number_str.begin(), number_str.end(), '~'), number_str.end()); ASSERT_FALSE(parse_amount(val, number_str)); } } #define TEST_pos(expected, str) \ TEST(parse_amount, handles_pos_ ## str) \ { \ do_pos_test(UINT64_C(expected), #str); \ } #define TEST_neg(str) \ TEST(parse_amount, handles_neg_ ## str) \ { \ do_neg_test(#str); \ } #define TEST_neg_n(str, name) \ TEST(parse_amount, handles_neg_ ## name) \ { \ do_neg_test(#str); \ } TEST_pos(0, 0); TEST_pos(0, 00); TEST_pos(0, 00000000); TEST_pos(0, 000000000); TEST_pos(0, 00000000000000000000000000000000); TEST_pos(0, _0); TEST_pos(0, _00); TEST_pos(0, _00000000); TEST_pos(0, _000000000); TEST_pos(0, _00000000000000000000000000000000); TEST_pos(0, 00000000_); TEST_pos(0, 000000000_); TEST_pos(0, 00000000000000000000000000000000_); TEST_pos(0, 0_); TEST_pos(0, 0_0); TEST_pos(0, 0_00); TEST_pos(0, 0_00000000); TEST_pos(0, 0_000000000); TEST_pos(0, 0_00000000000000000000000000000000); TEST_pos(0, 00_); TEST_pos(0, 00_0); TEST_pos(0, 00_00); TEST_pos(0, 00_00000000); TEST_pos(0, 00_000000000); TEST_pos(0, 00_00000000000000000000000000000000); TEST_pos(1, 0_000000000001); TEST_pos(1, 0_0000000000010); TEST_pos(1, 0_0000000000010000000000000000000000000); TEST_pos(9, 0_000000000009); TEST_pos(9, 0_0000000000090); TEST_pos(9, 0_0000000000090000000000000000000000000); TEST_pos(1000000000000, 1); TEST_pos(10000000000000, 10); TEST_pos(100000000000000, 100); TEST_pos(1000000000000000, 1000); TEST_pos(6553500000000000, 6553_5); TEST_pos(429496729500000000, 429496_7295); TEST_pos(18446744073700000000, 18446744_0737); TEST_pos(18446744073700000000, 18446744_0737000); TEST_pos(18446744073700000000, 18446744_07370000); TEST_pos(18446744073700000000, 18446744_073700000); TEST_pos(18446744073700000000, 18446744_0737000000000000000); /* Max supply */ TEST_pos(18446744073709551615, 18446744_073709551615); // Invalid numbers TEST_neg_n(~, empty_string); TEST_neg_n(-0, minus_0); TEST_neg_n(+0, plus_0); TEST_neg_n(-1, minus_1); TEST_neg_n(+1, plus_1); TEST_neg_n(_, only_point); // Don't go below 10^-12 TEST_neg(0_0000000000001); TEST_neg(0_0000000000009); TEST_neg(184467440737_000000001); // Overflow TEST_neg(184467440737_09551616); TEST_neg(184467440738); TEST_neg(18446744073709551616); // Two or more points TEST_neg(__); TEST_neg(0__); TEST_neg(__0); TEST_neg(0__0); TEST_neg(0_0_); TEST_neg(_0_0); TEST_neg(0_0_0);
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "google/cloud/pubsub/internal/session_shutdown_manager.h" #include "google/cloud/internal/absl_str_join_quiet.h" #include "google/cloud/log.h" namespace google { namespace cloud { namespace pubsub_internal { inline namespace GOOGLE_CLOUD_CPP_PUBSUB_NS { std::string FormatOps(std::unordered_map<std::string, int> const& ops) { std::ostringstream os; os << "{"; os << absl::StrJoin(ops, ", ", absl::PairFormatter("=")); os << "}"; return std::move(os).str(); }; SessionShutdownManager::~SessionShutdownManager() { if (signaled_) return; GCP_LOG(TRACE) << __func__ << "() - do signal" << ", shutdown=" << shutdown_ << ", signaled=" << signaled_ << ", outstanding_operations=" << outstanding_operations_ << ", result=" << result_ << ", ops=" << FormatOps(ops_); signaled_ = true; done_.set_value(std::move(result_)); } void SessionShutdownManager::LogStart(const char* caller, const char* name) { auto increase_count = [&] { return ++ops_[name]; }; GCP_LOG(TRACE) << "operation <" << name << "> starting from " << caller << ", shutdown=" << shutdown_ << ", signaled=" << signaled_ << ", outstanding_operations=" << outstanding_operations_ << ", result=" << result_ << ", count=" << increase_count(); } bool SessionShutdownManager::FinishedOperation(char const* name) { std::unique_lock<std::mutex> lk(mu_); auto decrease_count = [&] { return --ops_[name]; }; GCP_LOG(TRACE) << "operation <" << name << "> finished" << ", shutdown=" << shutdown_ << ", signaled=" << signaled_ << ", outstanding_operations=" << outstanding_operations_ << ", result=" << result_ << ", count=" << decrease_count(); bool r = shutdown_; --outstanding_operations_; SignalOnShutdown(std::move(lk)); return r; } void SessionShutdownManager::MarkAsShutdown(char const* caller, Status status) { std::unique_lock<std::mutex> lk(mu_); GCP_LOG(TRACE) << __func__ << "() - from " << caller << "() - shutting down" << ", shutdown=" << shutdown_ << ", signaled=" << signaled_ << ", outstanding_operations=" << outstanding_operations_ << ", result=" << result_ << ", status=" << status; shutdown_ = true; result_ = std::move(status); SignalOnShutdown(std::move(lk)); } void SessionShutdownManager::SignalOnShutdown(std::unique_lock<std::mutex> lk) { GCP_LOG(TRACE) << __func__ << "() - maybe signal" << ", shutdown=" << shutdown_ << ", signaled=" << signaled_ << ", outstanding_operations=" << outstanding_operations_ << ", result=" << result_ << ", ops=" << FormatOps(ops_); if (outstanding_operations_ > 0 || !shutdown_ || signaled_) return; // No other thread will go beyond this point, as `signaled_` is only set // once. signaled_ = true; // As satisfying the `done_` promise might trigger callbacks we should release // the lock before doing so. But we also need to modify any variables with // the lock held: auto p = std::move(done_); auto s = std::move(result_); lk.unlock(); p.set_value(std::move(s)); } } // namespace GOOGLE_CLOUD_CPP_PUBSUB_NS } // namespace pubsub_internal } // namespace cloud } // namespace google
// Copyright 2016 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <atomic> #include <ctype.h> #include <inttypes.h> #include <limits.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <threads.h> #include <unistd.h> #include <fbl/algorithm.h> #include <fbl/function.h> #include <lib/fit/defer.h> #include <lib/fzl/memory-probe.h> #include <lib/zx/bti.h> #include <lib/zx/iommu.h> #include <lib/zx/vmo.h> #include <zircon/process.h> #include <zircon/syscalls.h> #include <zircon/syscalls/iommu.h> #include <zircon/syscalls/object.h> #include <zxtest/zxtest.h> extern "C" __WEAK zx_handle_t get_root_resource(void); namespace { TEST(VmoTestCase, Create) { zx_status_t status; zx_handle_t vmo[16]; // allocate a bunch of vmos then free them for (size_t i = 0; i < fbl::count_of(vmo); i++) { status = zx_vmo_create(i * PAGE_SIZE, 0, &vmo[i]); EXPECT_OK(status, "vm_object_create"); } for (size_t i = 0; i < fbl::count_of(vmo); i++) { status = zx_handle_close(vmo[i]); EXPECT_OK(status, "handle_close"); } } TEST(VmoTestCase, ReadWrite) { zx_status_t status; zx_handle_t vmo; // allocate an object and read/write from it const size_t len = PAGE_SIZE * 4; status = zx_vmo_create(len, 0, &vmo); EXPECT_OK(status, "vm_object_create"); char buf[len]; status = zx_vmo_read(vmo, buf, 0, sizeof(buf)); EXPECT_OK(status, "vm_object_read"); // make sure it's full of zeros size_t count = 0; for (auto c : buf) { EXPECT_EQ(c, 0, "zero test"); if (c != 0) { printf("char at offset %#zx is bad\n", count); } count++; } memset(buf, 0x99, sizeof(buf)); status = zx_vmo_write(vmo, buf, 0, sizeof(buf)); EXPECT_OK(status, "vm_object_write"); // map it uintptr_t ptr; status = zx_vmar_map(zx_vmar_root_self(), ZX_VM_PERM_READ | ZX_VM_PERM_WRITE, 0, vmo, 0, len, &ptr); EXPECT_OK(status, "vm_map"); EXPECT_NE(0u, ptr, "vm_map"); // check that it matches what we last wrote into it EXPECT_BYTES_EQ((uint8_t *)buf, (uint8_t *)ptr, sizeof(buf), "mapped buffer"); status = zx_vmar_unmap(zx_vmar_root_self(), ptr, len); EXPECT_OK(status, "vm_unmap"); // close the handle status = zx_handle_close(vmo); EXPECT_OK(status, "handle_close"); } TEST(VmoTestCase, ReadWriteRange) { zx_status_t status; zx_handle_t vmo; // allocate an object const size_t len = PAGE_SIZE * 4; status = zx_vmo_create(len, 0, &vmo); EXPECT_OK(status, "vm_object_create"); // fail to read past end char buf[len * 2]; status = zx_vmo_read(vmo, buf, 0, sizeof(buf)); EXPECT_EQ(status, ZX_ERR_OUT_OF_RANGE, "vm_object_read past end"); // Successfully read 0 bytes at end status = zx_vmo_read(vmo, buf, len, 0); EXPECT_OK(status, "vm_object_read zero at end"); // Fail to read 0 bytes past end status = zx_vmo_read(vmo, buf, len + 1, 0); EXPECT_EQ(status, ZX_ERR_OUT_OF_RANGE, "vm_object_read zero past end"); // fail to write past end status = zx_vmo_write(vmo, buf, 0, sizeof(buf)); EXPECT_EQ(status, ZX_ERR_OUT_OF_RANGE, "vm_object_write past end"); // Successfully write 0 bytes at end status = zx_vmo_write(vmo, buf, len, 0); EXPECT_OK(status, "vm_object_write zero at end"); // Fail to read 0 bytes past end status = zx_vmo_write(vmo, buf, len + 1, 0); EXPECT_EQ(status, ZX_ERR_OUT_OF_RANGE, "vm_object_write zero past end"); // Test for unsigned wraparound status = zx_vmo_read(vmo, buf, UINT64_MAX - (len / 2), len); EXPECT_EQ(status, ZX_ERR_OUT_OF_RANGE, "vm_object_read offset + len wraparound"); status = zx_vmo_write(vmo, buf, UINT64_MAX - (len / 2), len); EXPECT_EQ(status, ZX_ERR_OUT_OF_RANGE, "vm_object_write offset + len wraparound"); // close the handle status = zx_handle_close(vmo); EXPECT_OK(status, "handle_close"); } TEST(VmoTestCase, Map) { zx_status_t status; zx_handle_t vmo; uintptr_t ptr[3] = {}; // allocate a vmo status = zx_vmo_create(4 * PAGE_SIZE, 0, &vmo); EXPECT_OK(status, "vm_object_create"); // do a regular map ptr[0] = 0; status = zx_vmar_map(zx_vmar_root_self(), ZX_VM_PERM_READ, 0, vmo, 0, PAGE_SIZE, &ptr[0]); EXPECT_OK(status, "map"); EXPECT_NE(0u, ptr[0], "map address"); // printf("mapped %#" PRIxPTR "\n", ptr[0]); // try to map something completely out of range without any fixed mapping, should succeed ptr[2] = UINTPTR_MAX; status = zx_vmar_map(zx_vmar_root_self(), ZX_VM_PERM_READ, 0, vmo, 0, PAGE_SIZE, &ptr[2]); EXPECT_OK(status, "map"); EXPECT_NE(0u, ptr[2], "map address"); // try to map something completely out of range fixed, should fail uintptr_t map_addr; status = zx_vmar_map(zx_vmar_root_self(), ZX_VM_PERM_READ | ZX_VM_SPECIFIC, UINTPTR_MAX, vmo, 0, PAGE_SIZE, &map_addr); EXPECT_EQ(ZX_ERR_INVALID_ARGS, status, "map"); // cleanup status = zx_handle_close(vmo); EXPECT_OK(status, "handle_close"); for (auto p : ptr) { if (p) { status = zx_vmar_unmap(zx_vmar_root_self(), p, PAGE_SIZE); EXPECT_OK(status, "unmap"); } } } TEST(VmoTestCase, ReadOnlyMap) { zx_status_t status; zx_handle_t vmo; // allocate an object and read/write from it const size_t len = PAGE_SIZE; status = zx_vmo_create(len, 0, &vmo); EXPECT_OK(status, "vm_object_create"); // map it uintptr_t ptr; status = zx_vmar_map(zx_vmar_root_self(), ZX_VM_PERM_READ, 0, vmo, 0, len, &ptr); EXPECT_OK(status, "vm_map"); EXPECT_NE(0u, ptr, "vm_map"); EXPECT_EQ(false, probe_for_write((void *)ptr), "write"); status = zx_vmar_unmap(zx_vmar_root_self(), ptr, len); EXPECT_OK(status, "vm_unmap"); // close the handle status = zx_handle_close(vmo); EXPECT_OK(status, "handle_close"); } TEST(VmoTestCase, NoPermMap) { zx_status_t status; zx_handle_t vmo; // allocate an object and read/write from it const size_t len = PAGE_SIZE; status = zx_vmo_create(len, 0, &vmo); EXPECT_OK(status, "vm_object_create"); // map it with read permissions uintptr_t ptr; status = zx_vmar_map(zx_vmar_root_self(), ZX_VM_PERM_READ, 0, vmo, 0, len, &ptr); EXPECT_OK(status, "vm_map"); EXPECT_NE(0u, ptr, "vm_map"); // protect it to no permissions status = zx_vmar_protect(zx_vmar_root_self(), 0, ptr, len); EXPECT_OK(status, "vm_protect"); // test reading writing to the mapping EXPECT_EQ(false, probe_for_read(reinterpret_cast<void *>(ptr)), "read"); EXPECT_EQ(false, probe_for_write(reinterpret_cast<void *>(ptr)), "write"); status = zx_vmar_unmap(zx_vmar_root_self(), ptr, len); EXPECT_OK(status, "vm_unmap"); // close the handle EXPECT_OK(zx_handle_close(vmo), "handle_close"); } TEST(VmoTestCase, NoPermProtect) { zx_status_t status; zx_handle_t vmo; // allocate an object and read/write from it const size_t len = PAGE_SIZE; status = zx_vmo_create(len, 0, &vmo); EXPECT_OK(status, "vm_object_create"); // map it with no permissions uintptr_t ptr; status = zx_vmar_map(zx_vmar_root_self(), 0, 0, vmo, 0, len, &ptr); EXPECT_OK(status, "vm_map"); EXPECT_NE(0u, ptr, "vm_map"); // test writing to the mapping EXPECT_EQ(false, probe_for_write(reinterpret_cast<void *>(ptr)), "write"); // test reading to the mapping EXPECT_EQ(false, probe_for_read(reinterpret_cast<void *>(ptr)), "read"); // protect it to read permissions and make sure it works as expected status = zx_vmar_protect(zx_vmar_root_self(), ZX_VM_PERM_READ, ptr, len); EXPECT_OK(status, "vm_protect"); // test writing to the mapping EXPECT_EQ(false, probe_for_write(reinterpret_cast<void *>(ptr)), "write"); // test reading from the mapping EXPECT_EQ(true, probe_for_read(reinterpret_cast<void *>(ptr)), "read"); status = zx_vmar_unmap(zx_vmar_root_self(), ptr, len); EXPECT_OK(status, "vm_unmap"); // close the handle EXPECT_OK(zx_handle_close(vmo), "handle_close"); } TEST(VmoTestCase, Resize) { zx_status_t status; zx_handle_t vmo; // allocate an object size_t len = PAGE_SIZE * 4; status = zx_vmo_create(len, ZX_VMO_RESIZABLE, &vmo); EXPECT_OK(status, "vm_object_create"); // get the size that we set it to uint64_t size = 0x99999999; status = zx_vmo_get_size(vmo, &size); EXPECT_OK(status, "vm_object_get_size"); EXPECT_EQ(len, size, "vm_object_get_size"); // try to resize it len += PAGE_SIZE; status = zx_vmo_set_size(vmo, len); EXPECT_OK(status, "vm_object_set_size"); // get the size again size = 0x99999999; status = zx_vmo_get_size(vmo, &size); EXPECT_OK(status, "vm_object_get_size"); EXPECT_EQ(len, size, "vm_object_get_size"); // try to resize it to a ludicrous size status = zx_vmo_set_size(vmo, UINT64_MAX); EXPECT_EQ(ZX_ERR_OUT_OF_RANGE, status, "vm_object_set_size too big"); // resize it to a non aligned size status = zx_vmo_set_size(vmo, len + 1); EXPECT_OK(status, "vm_object_set_size"); // size should be rounded up to the next page boundary size = 0x99999999; status = zx_vmo_get_size(vmo, &size); EXPECT_OK(status, "vm_object_get_size"); EXPECT_EQ(fbl::round_up(len + 1u, static_cast<size_t>(PAGE_SIZE)), size, "vm_object_get_size"); len = fbl::round_up(len + 1u, static_cast<size_t>(PAGE_SIZE)); // map it uintptr_t ptr; status = zx_vmar_map(zx_vmar_root_self(), ZX_VM_PERM_READ, 0, vmo, 0, len, &ptr); EXPECT_OK(status, "vm_map"); EXPECT_NE(ptr, 0, "vm_map"); // attempt to map expecting an non resizable vmo. uintptr_t ptr2; status = zx_vmar_map(zx_vmar_root_self(), ZX_VM_PERM_READ | ZX_VM_REQUIRE_NON_RESIZABLE, 0, vmo, 0, len, &ptr2); EXPECT_EQ(ZX_ERR_NOT_SUPPORTED, status, "vm_map"); // resize it with it mapped status = zx_vmo_set_size(vmo, size); EXPECT_OK(status, "vm_object_set_size"); // unmap it status = zx_vmar_unmap(zx_vmar_root_self(), ptr, len); EXPECT_OK(status, "unmap"); // close the handle status = zx_handle_close(vmo); EXPECT_OK(status, "handle_close"); } // Check that non-resizable VMOs cannot get resized. TEST(VmoTestCase, NoResize) { const size_t len = PAGE_SIZE * 4; zx_handle_t vmo = ZX_HANDLE_INVALID; zx_vmo_create(len, 0, &vmo); EXPECT_NE(vmo, ZX_HANDLE_INVALID); zx_status_t status; status = zx_vmo_set_size(vmo, len + PAGE_SIZE); EXPECT_EQ(ZX_ERR_UNAVAILABLE, status, "vm_object_set_size"); status = zx_vmo_set_size(vmo, len - PAGE_SIZE); EXPECT_EQ(ZX_ERR_UNAVAILABLE, status, "vm_object_set_size"); size_t size; status = zx_vmo_get_size(vmo, &size); EXPECT_OK(status, "vm_object_get_size"); EXPECT_EQ(len, size, "vm_object_get_size"); uintptr_t ptr; status = zx_vmar_map(zx_vmar_root_self(), ZX_VM_PERM_READ | ZX_VM_PERM_WRITE | ZX_VM_REQUIRE_NON_RESIZABLE, 0, vmo, 0, len, &ptr); ASSERT_OK(status, "vm_map"); ASSERT_NE(ptr, 0, "vm_map"); status = zx_vmar_unmap(zx_vmar_root_self(), ptr, len); EXPECT_OK(status, "unmap"); status = zx_handle_close(vmo); EXPECT_OK(status, "handle_close"); } TEST(VmoTestCase, Info) { size_t len = PAGE_SIZE * 4; zx::vmo vmo; zx_info_vmo_t info; zx_status_t status; // Create a non-resizeable VMO, query the INFO on it // and dump it. status = zx::vmo::create(len, 0, &vmo); EXPECT_OK(status, "vm_info_test: vmo_create"); status = vmo.get_info(ZX_INFO_VMO, &info, sizeof(info), nullptr, nullptr); EXPECT_OK(status, "vm_info_test: info_vmo"); vmo.reset(); EXPECT_EQ(info.size_bytes, len, "vm_info_test: info_vmo.size_bytes"); EXPECT_EQ(info.flags, ZX_INFO_VMO_TYPE_PAGED | ZX_INFO_VMO_VIA_HANDLE, "vm_info_test: info_vmo.flags"); EXPECT_EQ(info.cache_policy, ZX_CACHE_POLICY_CACHED, "vm_info_test: info_vmo.cache_policy"); // Create a resizeable uncached VMO, query the INFO on it and dump it. len = PAGE_SIZE * 8; zx::vmo::create(len, ZX_VMO_RESIZABLE, &vmo); EXPECT_OK(status, "vm_info_test: vmo_create"); vmo.set_cache_policy(ZX_CACHE_POLICY_UNCACHED); status = vmo.get_info(ZX_INFO_VMO, &info, sizeof(info), nullptr, nullptr); EXPECT_OK(status, "vm_info_test: info_vmo"); vmo.reset(); EXPECT_EQ(info.size_bytes, len, "vm_info_test: info_vmo.size_bytes"); EXPECT_EQ(info.flags, ZX_INFO_VMO_TYPE_PAGED | ZX_INFO_VMO_VIA_HANDLE | ZX_INFO_VMO_RESIZABLE, "vm_info_test: info_vmo.flags"); EXPECT_EQ(info.cache_policy, ZX_CACHE_POLICY_UNCACHED, "vm_info_test: info_vmo.cache_policy"); if (get_root_resource) { zx::iommu iommu; zx::bti bti; // Please do not use get_root_resource() in new code. See ZX-1467. zx::unowned_resource root_res(get_root_resource()); zx_iommu_desc_dummy_t desc; EXPECT_EQ(zx_iommu_create((*root_res).get(), ZX_IOMMU_TYPE_DUMMY, &desc, sizeof(desc), iommu.reset_and_get_address()), ZX_OK); EXPECT_OK(zx::bti::create(iommu, 0, 0xdeadbeef, &bti)); len = PAGE_SIZE * 12; EXPECT_OK(zx::vmo::create_contiguous(bti, len, 0, &vmo)); status = vmo.get_info(ZX_INFO_VMO, &info, sizeof(info), nullptr, nullptr); EXPECT_OK(status, "vm_info_test: info_vmo"); EXPECT_EQ(info.size_bytes, len, "vm_info_test: info_vmo.size_bytes"); EXPECT_EQ(info.flags, ZX_INFO_VMO_TYPE_PAGED | ZX_INFO_VMO_VIA_HANDLE | ZX_INFO_VMO_CONTIGUOUS, "vm_info_test: info_vmo.flags"); EXPECT_EQ(info.cache_policy, ZX_CACHE_POLICY_CACHED, "vm_info_test: info_vmo.cache_policy"); } } TEST(VmoTestCase, SizeAlign) { for (uint64_t s = 0; s < PAGE_SIZE * 4; s++) { zx_handle_t vmo; // create a new object with nonstandard size zx_status_t status = zx_vmo_create(s, 0, &vmo); EXPECT_OK(status, "vm_object_create"); // should be the size rounded up to the nearest page boundary uint64_t size = 0x99999999; status = zx_vmo_get_size(vmo, &size); EXPECT_OK(status, "vm_object_get_size"); EXPECT_EQ(fbl::round_up(s, static_cast<size_t>(PAGE_SIZE)), size, "vm_object_get_size"); // close the handle EXPECT_OK(zx_handle_close(vmo), "handle_close"); } } TEST(VmoTestCase, ResizeAlign) { // resize a vmo with a particular size and test that the resulting size is aligned on a page // boundary. zx_handle_t vmo; zx_status_t status = zx_vmo_create(0, ZX_VMO_RESIZABLE, &vmo); EXPECT_OK(status, "vm_object_create"); for (uint64_t s = 0; s < PAGE_SIZE * 4; s++) { // set the size of the object zx_status_t status = zx_vmo_set_size(vmo, s); EXPECT_OK(status, "vm_object_create"); // should be the size rounded up to the nearest page boundary uint64_t size = 0x99999999; status = zx_vmo_get_size(vmo, &size); EXPECT_OK(status, "vm_object_get_size"); EXPECT_EQ(fbl::round_up(s, static_cast<size_t>(PAGE_SIZE)), size, "vm_object_get_size"); } // close the handle EXPECT_OK(zx_handle_close(vmo), "handle_close"); } void RightsTestMapHelper(zx_handle_t vmo, size_t len, uint32_t flags, bool expect_success, zx_status_t fail_err_code) { uintptr_t ptr; zx_status_t r = zx_vmar_map(zx_vmar_root_self(), flags, 0, vmo, 0, len, &ptr); if (expect_success) { EXPECT_OK(r); r = zx_vmar_unmap(zx_vmar_root_self(), ptr, len); EXPECT_OK(r, "unmap"); } else { EXPECT_EQ(fail_err_code, r); } } zx_rights_t GetHandleRights(zx_handle_t h) { zx_info_handle_basic_t info; zx_status_t s = zx_object_get_info(h, ZX_INFO_HANDLE_BASIC, &info, sizeof(info), nullptr, nullptr); if (s != ZX_OK) { EXPECT_OK(s); // Poison the test return 0; } return info.rights; } TEST(VmoTestCase, Rights) { char buf[4096]; size_t len = PAGE_SIZE * 4; zx_status_t status; zx_handle_t vmo, vmo2; // allocate an object status = zx_vmo_create(len, 0, &vmo); EXPECT_OK(status, "vm_object_create"); // Check that the handle has at least the expected rights. // This list should match the list in docs/syscalls/vmo_create.md. static const zx_rights_t kExpectedRights = ZX_RIGHT_DUPLICATE | ZX_RIGHT_TRANSFER | ZX_RIGHT_WAIT | ZX_RIGHT_READ | ZX_RIGHT_WRITE | ZX_RIGHT_MAP | ZX_RIGHT_GET_PROPERTY | ZX_RIGHT_SET_PROPERTY; EXPECT_EQ(kExpectedRights, kExpectedRights & GetHandleRights(vmo)); // test that we can read/write it status = zx_vmo_read(vmo, buf, 0, 0); EXPECT_EQ(0, status, "vmo_read"); status = zx_vmo_write(vmo, buf, 0, 0); EXPECT_EQ(0, status, "vmo_write"); vmo2 = ZX_HANDLE_INVALID; zx_handle_duplicate(vmo, ZX_RIGHT_READ, &vmo2); status = zx_vmo_read(vmo2, buf, 0, 0); EXPECT_EQ(0, status, "vmo_read"); status = zx_vmo_write(vmo2, buf, 0, 0); EXPECT_EQ(ZX_ERR_ACCESS_DENIED, status, "vmo_write"); zx_handle_close(vmo2); vmo2 = ZX_HANDLE_INVALID; zx_handle_duplicate(vmo, ZX_RIGHT_WRITE, &vmo2); status = zx_vmo_read(vmo2, buf, 0, 0); EXPECT_EQ(ZX_ERR_ACCESS_DENIED, status, "vmo_read"); status = zx_vmo_write(vmo2, buf, 0, 0); EXPECT_EQ(0, status, "vmo_write"); zx_handle_close(vmo2); vmo2 = ZX_HANDLE_INVALID; zx_handle_duplicate(vmo, 0, &vmo2); status = zx_vmo_read(vmo2, buf, 0, 0); EXPECT_EQ(ZX_ERR_ACCESS_DENIED, status, "vmo_read"); status = zx_vmo_write(vmo2, buf, 0, 0); EXPECT_EQ(ZX_ERR_ACCESS_DENIED, status, "vmo_write"); zx_handle_close(vmo2); status = zx_vmo_replace_as_executable(vmo, ZX_HANDLE_INVALID, &vmo); EXPECT_OK(status, "vmo_replace_as_executable"); EXPECT_EQ(kExpectedRights | ZX_RIGHT_EXECUTE, (kExpectedRights | ZX_RIGHT_EXECUTE) & GetHandleRights(vmo)); // full perm test ASSERT_NO_FATAL_FAILURES(RightsTestMapHelper(vmo, len, 0, true, 0)); ASSERT_NO_FATAL_FAILURES(RightsTestMapHelper(vmo, len, ZX_VM_PERM_READ, true, 0)); ASSERT_NO_FATAL_FAILURES( RightsTestMapHelper(vmo, len, ZX_VM_PERM_WRITE, false, ZX_ERR_INVALID_ARGS)); ASSERT_NO_FATAL_FAILURES( RightsTestMapHelper(vmo, len, ZX_VM_PERM_READ | ZX_VM_PERM_WRITE, true, 0)); ASSERT_NO_FATAL_FAILURES(RightsTestMapHelper( vmo, len, ZX_VM_PERM_READ | ZX_VM_PERM_WRITE | ZX_VM_PERM_EXECUTE, true, 0)); ASSERT_NO_FATAL_FAILURES( RightsTestMapHelper(vmo, len, ZX_VM_PERM_READ | ZX_VM_PERM_EXECUTE, true, 0)); // try most of the permutations of mapping a vmo with various rights dropped vmo2 = ZX_HANDLE_INVALID; zx_handle_duplicate(vmo, ZX_RIGHT_READ | ZX_RIGHT_WRITE | ZX_RIGHT_EXECUTE, &vmo2); ASSERT_NO_FATAL_FAILURES(RightsTestMapHelper(vmo2, len, 0, false, ZX_ERR_ACCESS_DENIED)); ASSERT_NO_FATAL_FAILURES( RightsTestMapHelper(vmo2, len, ZX_VM_PERM_READ, false, ZX_ERR_ACCESS_DENIED)); ASSERT_NO_FATAL_FAILURES( RightsTestMapHelper(vmo2, len, ZX_VM_PERM_WRITE, false, ZX_ERR_ACCESS_DENIED)); ASSERT_NO_FATAL_FAILURES(RightsTestMapHelper(vmo2, len, ZX_VM_PERM_READ | ZX_VM_PERM_WRITE, false, ZX_ERR_ACCESS_DENIED)); ASSERT_NO_FATAL_FAILURES( RightsTestMapHelper(vmo2, len, ZX_VM_PERM_READ | ZX_VM_PERM_WRITE | ZX_VM_PERM_EXECUTE, false, ZX_ERR_ACCESS_DENIED)); ASSERT_NO_FATAL_FAILURES(RightsTestMapHelper(vmo2, len, ZX_VM_PERM_READ | ZX_VM_PERM_EXECUTE, false, ZX_ERR_ACCESS_DENIED)); zx_handle_close(vmo2); vmo2 = ZX_HANDLE_INVALID; zx_handle_duplicate(vmo, ZX_RIGHT_READ | ZX_RIGHT_MAP, &vmo2); ASSERT_NO_FATAL_FAILURES(RightsTestMapHelper(vmo2, len, 0, true, 0)); ASSERT_NO_FATAL_FAILURES(RightsTestMapHelper(vmo2, len, ZX_VM_PERM_READ, true, 0)); ASSERT_NO_FATAL_FAILURES( RightsTestMapHelper(vmo2, len, ZX_VM_PERM_WRITE, false, ZX_ERR_INVALID_ARGS)); ASSERT_NO_FATAL_FAILURES(RightsTestMapHelper(vmo2, len, ZX_VM_PERM_READ | ZX_VM_PERM_WRITE, false, ZX_ERR_ACCESS_DENIED)); ASSERT_NO_FATAL_FAILURES( RightsTestMapHelper(vmo2, len, ZX_VM_PERM_READ | ZX_VM_PERM_WRITE | ZX_VM_PERM_EXECUTE, false, ZX_ERR_ACCESS_DENIED)); ASSERT_NO_FATAL_FAILURES(RightsTestMapHelper(vmo2, len, ZX_VM_PERM_READ | ZX_VM_PERM_EXECUTE, false, ZX_ERR_ACCESS_DENIED)); zx_handle_close(vmo2); vmo2 = ZX_HANDLE_INVALID; zx_handle_duplicate(vmo, ZX_RIGHT_WRITE | ZX_RIGHT_MAP, &vmo2); ASSERT_NO_FATAL_FAILURES(RightsTestMapHelper(vmo2, len, 0, true, 0)); ASSERT_NO_FATAL_FAILURES( RightsTestMapHelper(vmo2, len, ZX_VM_PERM_READ, false, ZX_ERR_ACCESS_DENIED)); ASSERT_NO_FATAL_FAILURES( RightsTestMapHelper(vmo2, len, ZX_VM_PERM_WRITE, false, ZX_ERR_INVALID_ARGS)); ASSERT_NO_FATAL_FAILURES(RightsTestMapHelper(vmo2, len, ZX_VM_PERM_READ | ZX_VM_PERM_WRITE, false, ZX_ERR_ACCESS_DENIED)); ASSERT_NO_FATAL_FAILURES( RightsTestMapHelper(vmo2, len, ZX_VM_PERM_READ | ZX_VM_PERM_WRITE | ZX_VM_PERM_EXECUTE, false, ZX_ERR_ACCESS_DENIED)); ASSERT_NO_FATAL_FAILURES(RightsTestMapHelper(vmo2, len, ZX_VM_PERM_READ | ZX_VM_PERM_EXECUTE, false, ZX_ERR_ACCESS_DENIED)); zx_handle_close(vmo2); vmo2 = ZX_HANDLE_INVALID; zx_handle_duplicate(vmo, ZX_RIGHT_READ | ZX_RIGHT_WRITE | ZX_RIGHT_MAP, &vmo2); ASSERT_NO_FATAL_FAILURES(RightsTestMapHelper(vmo2, len, 0, true, 0)); ASSERT_NO_FATAL_FAILURES(RightsTestMapHelper(vmo2, len, ZX_VM_PERM_READ, true, 0)); ASSERT_NO_FATAL_FAILURES( RightsTestMapHelper(vmo2, len, ZX_VM_PERM_WRITE, false, ZX_ERR_INVALID_ARGS)); ASSERT_NO_FATAL_FAILURES( RightsTestMapHelper(vmo2, len, ZX_VM_PERM_READ | ZX_VM_PERM_WRITE, true, 0)); ASSERT_NO_FATAL_FAILURES( RightsTestMapHelper(vmo2, len, ZX_VM_PERM_READ | ZX_VM_PERM_WRITE | ZX_VM_PERM_EXECUTE, false, ZX_ERR_ACCESS_DENIED)); ASSERT_NO_FATAL_FAILURES(RightsTestMapHelper(vmo2, len, ZX_VM_PERM_READ | ZX_VM_PERM_EXECUTE, false, ZX_ERR_ACCESS_DENIED)); zx_handle_close(vmo2); vmo2 = ZX_HANDLE_INVALID; zx_handle_duplicate(vmo, ZX_RIGHT_READ | ZX_RIGHT_EXECUTE | ZX_RIGHT_MAP, &vmo2); ASSERT_NO_FATAL_FAILURES(RightsTestMapHelper(vmo2, len, 0, true, 0)); ASSERT_NO_FATAL_FAILURES(RightsTestMapHelper(vmo2, len, ZX_VM_PERM_READ, true, 0)); ASSERT_NO_FATAL_FAILURES( RightsTestMapHelper(vmo2, len, ZX_VM_PERM_WRITE, false, ZX_ERR_INVALID_ARGS)); ASSERT_NO_FATAL_FAILURES(RightsTestMapHelper(vmo2, len, ZX_VM_PERM_READ | ZX_VM_PERM_WRITE, false, ZX_ERR_ACCESS_DENIED)); ASSERT_NO_FATAL_FAILURES( RightsTestMapHelper(vmo2, len, ZX_VM_PERM_READ | ZX_VM_PERM_WRITE | ZX_VM_PERM_EXECUTE, false, ZX_ERR_ACCESS_DENIED)); ASSERT_NO_FATAL_FAILURES( RightsTestMapHelper(vmo, len, ZX_VM_PERM_READ | ZX_VM_PERM_EXECUTE, true, 0)); zx_handle_close(vmo2); vmo2 = ZX_HANDLE_INVALID; zx_handle_duplicate(vmo, ZX_RIGHT_READ | ZX_RIGHT_WRITE | ZX_RIGHT_EXECUTE | ZX_RIGHT_MAP, &vmo2); ASSERT_NO_FATAL_FAILURES(RightsTestMapHelper(vmo2, len, 0, true, 0)); ASSERT_NO_FATAL_FAILURES(RightsTestMapHelper(vmo2, len, ZX_VM_PERM_READ, true, 0)); ASSERT_NO_FATAL_FAILURES( RightsTestMapHelper(vmo2, len, ZX_VM_PERM_WRITE, false, ZX_ERR_INVALID_ARGS)); ASSERT_NO_FATAL_FAILURES( RightsTestMapHelper(vmo2, len, ZX_VM_PERM_READ | ZX_VM_PERM_WRITE, true, 0)); ASSERT_NO_FATAL_FAILURES(RightsTestMapHelper( vmo2, len, ZX_VM_PERM_READ | ZX_VM_PERM_WRITE | ZX_VM_PERM_EXECUTE, true, 0)); ASSERT_NO_FATAL_FAILURES( RightsTestMapHelper(vmo, len, ZX_VM_PERM_READ | ZX_VM_PERM_EXECUTE, true, 0)); zx_handle_close(vmo2); // test that we can get/set a property on it const char *set_name = "test vmo"; status = zx_object_set_property(vmo, ZX_PROP_NAME, set_name, sizeof(set_name)); EXPECT_OK(status, "set_property"); char get_name[ZX_MAX_NAME_LEN]; status = zx_object_get_property(vmo, ZX_PROP_NAME, get_name, sizeof(get_name)); EXPECT_OK(status, "get_property"); EXPECT_STR_EQ(set_name, get_name, "vmo name"); // close the handle status = zx_handle_close(vmo); EXPECT_OK(status, "handle_close"); // Use wrong handle with wrong permission, and expect wrong type not // ZX_ERR_ACCESS_DENIED vmo = ZX_HANDLE_INVALID; vmo2 = ZX_HANDLE_INVALID; status = zx_port_create(0, &vmo); EXPECT_OK(status, "zx_port_create"); status = zx_handle_duplicate(vmo, 0, &vmo2); EXPECT_OK(status, "zx_handle_duplicate"); status = zx_vmo_read(vmo2, buf, 0, 0); EXPECT_EQ(ZX_ERR_WRONG_TYPE, status, "vmo_read wrong type"); // close the handle status = zx_handle_close(vmo); EXPECT_OK(status, "handle_close"); status = zx_handle_close(vmo2); EXPECT_OK(status, "handle_close"); } TEST(VmoTestCase, Commit) { zx_handle_t vmo; zx_status_t status; uintptr_t ptr, ptr2, ptr3; // create a vmo const size_t size = 16384; status = zx_vmo_create(size, 0, &vmo); EXPECT_EQ(0, status, "vm_object_create"); // commit a range of it status = zx_vmo_op_range(vmo, ZX_VMO_OP_COMMIT, 0, size, nullptr, 0); EXPECT_EQ(0, status, "vm commit"); // decommit that range status = zx_vmo_op_range(vmo, ZX_VMO_OP_DECOMMIT, 0, size, nullptr, 0); EXPECT_EQ(0, status, "vm decommit"); // commit a range of it status = zx_vmo_op_range(vmo, ZX_VMO_OP_COMMIT, 0, size, nullptr, 0); EXPECT_EQ(0, status, "vm commit"); // map it ptr = 0; status = zx_vmar_map(zx_vmar_root_self(), ZX_VM_PERM_READ | ZX_VM_PERM_WRITE, 0, vmo, 0, size, &ptr); EXPECT_OK(status, "map"); EXPECT_NE(ptr, 0, "map address"); // second mapping with an offset ptr2 = 0; status = zx_vmar_map(zx_vmar_root_self(), ZX_VM_PERM_READ | ZX_VM_PERM_WRITE, 0, vmo, PAGE_SIZE, size, &ptr2); EXPECT_OK(status, "map2"); EXPECT_NE(ptr2, 0, "map address2"); // third mapping with a totally non-overlapping offset ptr3 = 0; status = zx_vmar_map(zx_vmar_root_self(), ZX_VM_PERM_READ | ZX_VM_PERM_WRITE, 0, vmo, size * 2, size, &ptr3); EXPECT_OK(status, "map3"); EXPECT_NE(ptr3, 0, "map address3"); // write into it at offset PAGE_SIZE, read it back volatile uint32_t *u32 = (volatile uint32_t *)(ptr + PAGE_SIZE); *u32 = 99; EXPECT_EQ(99u, (*u32), "written memory"); // check the alias volatile uint32_t *u32a = (volatile uint32_t *)(ptr2); EXPECT_EQ(99u, (*u32a), "written memory"); // decommit page 0 status = zx_vmo_op_range(vmo, ZX_VMO_OP_DECOMMIT, 0, PAGE_SIZE, nullptr, 0); EXPECT_EQ(0, status, "vm decommit"); // verify that it didn't get unmapped EXPECT_EQ(99u, (*u32), "written memory"); // verify that it didn't get unmapped EXPECT_EQ(99u, (*u32a), "written memory2"); // decommit page 1 status = zx_vmo_op_range(vmo, ZX_VMO_OP_DECOMMIT, PAGE_SIZE, PAGE_SIZE, nullptr, 0); EXPECT_EQ(0, status, "vm decommit"); // verify that it did get unmapped EXPECT_EQ(0u, (*u32), "written memory"); // verify that it did get unmapped EXPECT_EQ(0u, (*u32a), "written memory2"); // unmap our vmos status = zx_vmar_unmap(zx_vmar_root_self(), ptr, size); EXPECT_OK(status, "vm_unmap"); status = zx_vmar_unmap(zx_vmar_root_self(), ptr2, size); EXPECT_OK(status, "vm_unmap"); status = zx_vmar_unmap(zx_vmar_root_self(), ptr3, size); EXPECT_OK(status, "vm_unmap"); // close the handle status = zx_handle_close(vmo); EXPECT_OK(status, "handle_close"); } TEST(VmoTestCase, ZeroPage) { zx_handle_t vmo; zx_status_t status; uintptr_t ptr[3]; // create a vmo const size_t size = PAGE_SIZE * 4; EXPECT_OK(zx_vmo_create(size, 0, &vmo), "vm_object_create"); // make a few mappings of the vmo for (auto &p : ptr) { EXPECT_EQ( ZX_OK, zx_vmar_map(zx_vmar_root_self(), ZX_VM_PERM_READ | ZX_VM_PERM_WRITE, 0, vmo, 0, size, &p), "map"); EXPECT_NE(0, p, "map address"); } volatile uint32_t *val = (volatile uint32_t *)ptr[0]; volatile uint32_t *val2 = (volatile uint32_t *)ptr[1]; volatile uint32_t *val3 = (volatile uint32_t *)ptr[2]; // read fault in the first mapping EXPECT_EQ(0, *val, "read zero"); // write fault the second mapping *val2 = 99; EXPECT_EQ(99, *val2, "read back 99"); // expect the third mapping to read fault in the new page EXPECT_EQ(99, *val3, "read 99"); // expect the first mapping to have gotten updated with the new mapping // and no longer be mapping the zero page EXPECT_EQ(99, *val, "read 99 from former zero page"); // read fault in zeros on the second page val = (volatile uint32_t *)(ptr[0] + PAGE_SIZE); EXPECT_EQ(0, *val, "read zero"); // write to the page via a vmo_write call uint32_t v = 100; status = zx_vmo_write(vmo, &v, PAGE_SIZE, sizeof(v)); EXPECT_OK(status, "writing to vmo"); // expect it to read back the new value EXPECT_EQ(100, *val, "read 100 from former zero page"); // read fault in zeros on the third page val = (volatile uint32_t *)(ptr[0] + PAGE_SIZE * 2); EXPECT_EQ(0, *val, "read zero"); // commit this range of the vmo via a commit call status = zx_vmo_op_range(vmo, ZX_VMO_OP_COMMIT, PAGE_SIZE * 2, PAGE_SIZE, nullptr, 0); EXPECT_OK(status, "committing memory"); // write to the third page status = zx_vmo_write(vmo, &v, PAGE_SIZE * 2, sizeof(v)); EXPECT_OK(status, "writing to vmo"); // expect it to read back the new value EXPECT_EQ(100, *val, "read 100 from former zero page"); // unmap for (auto p : ptr) EXPECT_OK(zx_vmar_unmap(zx_vmar_root_self(), p, size), "unmap"); // close the handle EXPECT_OK(zx_handle_close(vmo), "handle_close"); } TEST(VmoTestCase, Cache) { zx_handle_t vmo; const size_t size = PAGE_SIZE; EXPECT_OK(zx_vmo_create(size, 0, &vmo), "creation for cache_policy"); // clean vmo can have all valid cache policies set EXPECT_OK(zx_vmo_set_cache_policy(vmo, ZX_CACHE_POLICY_CACHED)); EXPECT_OK(zx_vmo_set_cache_policy(vmo, ZX_CACHE_POLICY_UNCACHED)); EXPECT_OK(zx_vmo_set_cache_policy(vmo, ZX_CACHE_POLICY_UNCACHED_DEVICE)); EXPECT_OK(zx_vmo_set_cache_policy(vmo, ZX_CACHE_POLICY_WRITE_COMBINING)); // bad cache policy EXPECT_EQ(ZX_ERR_INVALID_ARGS, zx_vmo_set_cache_policy(vmo, ZX_CACHE_POLICY_MASK + 1)); // commit a page, make sure the policy doesn't set EXPECT_OK(zx_vmo_op_range(vmo, ZX_VMO_OP_COMMIT, 0, size, nullptr, 0)); EXPECT_EQ(ZX_ERR_BAD_STATE, zx_vmo_set_cache_policy(vmo, ZX_CACHE_POLICY_CACHED)); EXPECT_OK(zx_vmo_op_range(vmo, ZX_VMO_OP_DECOMMIT, 0, size, nullptr, 0)); EXPECT_OK(zx_vmo_set_cache_policy(vmo, ZX_CACHE_POLICY_CACHED)); // map the vmo, make sure policy doesn't set uintptr_t ptr; EXPECT_OK(zx_vmar_map(zx_vmar_root_self(), ZX_VM_PERM_READ, 0, vmo, 0, size, &ptr)); EXPECT_EQ(ZX_ERR_BAD_STATE, zx_vmo_set_cache_policy(vmo, ZX_CACHE_POLICY_CACHED)); EXPECT_OK(zx_vmar_unmap(zx_vmar_root_self(), ptr, size)); EXPECT_OK(zx_vmo_set_cache_policy(vmo, ZX_CACHE_POLICY_CACHED)); // clone the vmo, make sure policy doesn't set zx_handle_t clone; EXPECT_OK(zx_vmo_create_child(vmo, ZX_VMO_CHILD_COPY_ON_WRITE, 0, size, &clone)); EXPECT_EQ(ZX_ERR_BAD_STATE, zx_vmo_set_cache_policy(vmo, ZX_CACHE_POLICY_CACHED)); EXPECT_OK(zx_handle_close(clone)); EXPECT_OK(zx_vmo_set_cache_policy(vmo, ZX_CACHE_POLICY_CACHED)); // clone the vmo, try to set policy on the clone EXPECT_OK(zx_vmo_create_child(vmo, ZX_VMO_CHILD_COPY_ON_WRITE, 0, size, &clone)); EXPECT_EQ(ZX_ERR_BAD_STATE, zx_vmo_set_cache_policy(clone, ZX_CACHE_POLICY_CACHED)); EXPECT_OK(zx_handle_close(clone)); // set the policy, make sure future clones do not go through EXPECT_OK(zx_vmo_set_cache_policy(vmo, ZX_CACHE_POLICY_UNCACHED)); EXPECT_EQ(ZX_ERR_BAD_STATE, zx_vmo_create_child(vmo, ZX_VMO_CHILD_COPY_ON_WRITE, 0, size, &clone)); EXPECT_OK(zx_vmo_set_cache_policy(vmo, ZX_CACHE_POLICY_CACHED)); EXPECT_OK(zx_vmo_create_child(vmo, ZX_VMO_CHILD_COPY_ON_WRITE, 0, size, &clone)); EXPECT_OK(zx_handle_close(clone)); // set the policy, make sure vmo read/write do not work char c; EXPECT_OK(zx_vmo_set_cache_policy(vmo, ZX_CACHE_POLICY_UNCACHED)); EXPECT_EQ(ZX_ERR_BAD_STATE, zx_vmo_read(vmo, &c, 0, sizeof(c))); EXPECT_EQ(ZX_ERR_BAD_STATE, zx_vmo_write(vmo, &c, 0, sizeof(c))); EXPECT_OK(zx_vmo_set_cache_policy(vmo, ZX_CACHE_POLICY_CACHED)); EXPECT_OK(zx_vmo_read(vmo, &c, 0, sizeof(c))); EXPECT_OK(zx_vmo_write(vmo, &c, 0, sizeof(c))); EXPECT_OK(zx_handle_close(vmo), "close handle"); } TEST(VmoTestCase, CacheOp) { { // scope unpin_pmt so ~unpin_pmt is before END_TEST const size_t size = 0x8000; zx_handle_t normal_vmo = ZX_HANDLE_INVALID; zx_handle_t physical_vmo = ZX_HANDLE_INVALID; // To get physical pages in physmap for the physical_vmo, we create a // contiguous vmo. This needs to last until after we're done testing // with the physical_vmo. zx::vmo contig_vmo; zx::pmt pmt; auto unpin_pmt = fit::defer([&pmt] { if (pmt) { EXPECT_OK(pmt.unpin()); } }); EXPECT_OK(zx_vmo_create(size, 0, &normal_vmo), "creation for cache op (normal vmo)"); // Create physical_vmo if we can. if (get_root_resource) { // Please do not use get_root_resource() in new code. See ZX-1467. zx::unowned_resource root_res(get_root_resource()); zx::iommu iommu; zx::bti bti; zx_iommu_desc_dummy_t desc; EXPECT_EQ(zx_iommu_create((*root_res).get(), ZX_IOMMU_TYPE_DUMMY, &desc, sizeof(desc), iommu.reset_and_get_address()), ZX_OK); EXPECT_OK(zx::bti::create(iommu, 0, 0xdeadbeef, &bti)); // There's a chance this will flake if we're unable to get size // bytes that are physically contiguous. EXPECT_OK(zx::vmo::create_contiguous(bti, size, 0, &contig_vmo)); zx_paddr_t phys_addr; EXPECT_OK(zx_bti_pin(bti.get(), ZX_BTI_PERM_WRITE | ZX_BTI_CONTIGUOUS, contig_vmo.get(), 0, size, &phys_addr, 1, pmt.reset_and_get_address())); EXPECT_EQ(ZX_OK, zx_vmo_create_physical((*root_res).get(), phys_addr, size, &physical_vmo), "creation for cache op (physical vmo)"); // Go ahead and set the cache policy; we don't want the op_range calls // below to potentially skip running any code. EXPECT_OK(zx_vmo_set_cache_policy(physical_vmo, ZX_CACHE_POLICY_CACHED), "zx_vmo_set_cache_policy"); } auto test_vmo = [](zx_handle_t vmo) { if (vmo == ZX_HANDLE_INVALID) { return; } auto test_op = [vmo](uint32_t op) { EXPECT_OK(zx_vmo_op_range(vmo, op, 0, 1, nullptr, 0), "0 1"); EXPECT_OK(zx_vmo_op_range(vmo, op, 0, 1, nullptr, 0), "0 1"); EXPECT_OK(zx_vmo_op_range(vmo, op, 1, 1, nullptr, 0), "1 1"); EXPECT_OK(zx_vmo_op_range(vmo, op, 0, size, nullptr, 0), "0 size"); EXPECT_OK(zx_vmo_op_range(vmo, op, 1, size - 1, nullptr, 0), "1 size-1"); EXPECT_OK(zx_vmo_op_range(vmo, op, 0x5200, 1, nullptr, 0), "0x5200 1"); EXPECT_OK(zx_vmo_op_range(vmo, op, 0x5200, 0x800, nullptr, 0), "0x5200 0x800"); EXPECT_OK(zx_vmo_op_range(vmo, op, 0x5200, 0x1000, nullptr, 0), "0x5200 0x1000"); EXPECT_OK(zx_vmo_op_range(vmo, op, 0x5200, 0x1200, nullptr, 0), "0x5200 0x1200"); EXPECT_EQ(ZX_ERR_INVALID_ARGS, zx_vmo_op_range(vmo, op, 0, 0, nullptr, 0), "0 0"); EXPECT_EQ(ZX_ERR_OUT_OF_RANGE, zx_vmo_op_range(vmo, op, 1, size, nullptr, 0), "0 size"); EXPECT_EQ(ZX_ERR_OUT_OF_RANGE, zx_vmo_op_range(vmo, op, size, 1, nullptr, 0), "size 1"); EXPECT_EQ(ZX_ERR_OUT_OF_RANGE, zx_vmo_op_range(vmo, op, size + 1, 1, nullptr, 0), "size+1 1"); EXPECT_EQ(ZX_ERR_OUT_OF_RANGE, zx_vmo_op_range(vmo, op, UINT64_MAX - 1, 1, nullptr, 0), "UINT64_MAX-1 1"); EXPECT_EQ(ZX_ERR_OUT_OF_RANGE, zx_vmo_op_range(vmo, op, UINT64_MAX, 1, nullptr, 0), "UINT64_MAX 1"); EXPECT_EQ(ZX_ERR_OUT_OF_RANGE, zx_vmo_op_range(vmo, op, UINT64_MAX, UINT64_MAX, nullptr, 0), "UINT64_MAX UINT64_MAX"); }; test_op(ZX_VMO_OP_CACHE_SYNC); test_op(ZX_VMO_OP_CACHE_CLEAN); test_op(ZX_VMO_OP_CACHE_CLEAN_INVALIDATE); test_op(ZX_VMO_OP_CACHE_INVALIDATE); }; ZX_DEBUG_ASSERT(normal_vmo != ZX_HANDLE_INVALID); ZX_DEBUG_ASSERT(physical_vmo != ZX_HANDLE_INVALID || !get_root_resource); test_vmo(normal_vmo); test_vmo(physical_vmo); EXPECT_OK(zx_handle_close(normal_vmo), "close handle (normal vmo)"); // Closing ZX_HANDLE_INVALID is not an error. EXPECT_OK(zx_handle_close(physical_vmo), "close handle (physical vmo)"); } // ~unpin_pmt before END_TEST } TEST(VmoTestCase, CacheFlush) { zx_handle_t vmo; const size_t size = 0x8000; EXPECT_OK(zx_vmo_create(size, 0, &vmo), "creation for cache op"); uintptr_t ptr_ro; EXPECT_EQ(ZX_OK, zx_vmar_map(zx_vmar_root_self(), ZX_VM_PERM_READ, 0, vmo, 0, size, &ptr_ro), "map"); EXPECT_NE(ptr_ro, 0, "map address"); void *pro = (void *)ptr_ro; uintptr_t ptr_rw; EXPECT_EQ(ZX_OK, zx_vmar_map(zx_vmar_root_self(), ZX_VM_PERM_READ | ZX_VM_PERM_WRITE, 0, vmo, 0, size, &ptr_rw), "map"); EXPECT_NE(ptr_rw, 0, "map address"); void *prw = (void *)ptr_rw; zx_vmo_op_range(vmo, ZX_VMO_OP_COMMIT, 0, size, NULL, 0); EXPECT_OK(zx_cache_flush(prw, size, ZX_CACHE_FLUSH_INSN), "rw flush insn"); EXPECT_OK(zx_cache_flush(prw, size, ZX_CACHE_FLUSH_DATA), "rw clean"); EXPECT_OK(zx_cache_flush(prw, size, ZX_CACHE_FLUSH_DATA | ZX_CACHE_FLUSH_INSN), "rw clean w/ insn"); EXPECT_OK(zx_cache_flush(prw, size, ZX_CACHE_FLUSH_DATA | ZX_CACHE_FLUSH_INVALIDATE), "rw clean/invalidate"); EXPECT_EQ(ZX_OK, zx_cache_flush(prw, size, ZX_CACHE_FLUSH_DATA | ZX_CACHE_FLUSH_INVALIDATE | ZX_CACHE_FLUSH_INSN), "rw all"); EXPECT_OK(zx_cache_flush(pro, size, ZX_CACHE_FLUSH_INSN), "ro flush insn"); EXPECT_OK(zx_cache_flush(pro, size, ZX_CACHE_FLUSH_DATA), "ro clean"); EXPECT_OK(zx_cache_flush(pro, size, ZX_CACHE_FLUSH_DATA | ZX_CACHE_FLUSH_INSN), "ro clean w/ insn"); EXPECT_OK(zx_cache_flush(pro, size, ZX_CACHE_FLUSH_DATA | ZX_CACHE_FLUSH_INVALIDATE), "ro clean/invalidate"); EXPECT_OK(zx_cache_flush(pro, size, ZX_CACHE_FLUSH_DATA | ZX_CACHE_FLUSH_INVALIDATE), "ro clean/invalidate"); EXPECT_EQ(ZX_OK, zx_cache_flush(pro, size, ZX_CACHE_FLUSH_DATA | ZX_CACHE_FLUSH_INVALIDATE | ZX_CACHE_FLUSH_INSN), "ro all"); // Above checks all valid options combinations; check that invalid // combinations are handled correctly here. EXPECT_EQ(ZX_ERR_INVALID_ARGS, zx_cache_flush(pro, size, 0), "no args"); EXPECT_EQ(ZX_ERR_INVALID_ARGS, zx_cache_flush(pro, size, ZX_CACHE_FLUSH_INVALIDATE), "invalidate requires data"); EXPECT_EQ(ZX_ERR_INVALID_ARGS, zx_cache_flush(pro, size, ZX_CACHE_FLUSH_INSN | ZX_CACHE_FLUSH_INVALIDATE), "invalidate requires data"); EXPECT_EQ(ZX_ERR_INVALID_ARGS, zx_cache_flush(pro, size, 1u << 3), "out of range a"); EXPECT_EQ(ZX_ERR_INVALID_ARGS, zx_cache_flush(pro, size, ~0u), "out of range b"); zx_vmar_unmap(zx_vmar_root_self(), ptr_rw, size); zx_vmar_unmap(zx_vmar_root_self(), ptr_ro, size); EXPECT_OK(zx_handle_close(vmo), "close handle"); } TEST(VmoTestCase, DecommitMisaligned) { zx_handle_t vmo; EXPECT_OK(zx_vmo_create(PAGE_SIZE * 2, 0, &vmo), "creation for decommit test"); zx_status_t status = zx_vmo_op_range(vmo, ZX_VMO_OP_DECOMMIT, 0x10, 0x100, NULL, 0); EXPECT_OK(status, "decommitting uncommitted memory"); status = zx_vmo_op_range(vmo, ZX_VMO_OP_COMMIT, 0x10, 0x100, NULL, 0); EXPECT_OK(status, "committing memory"); status = zx_vmo_op_range(vmo, ZX_VMO_OP_DECOMMIT, 0x10, 0x100, NULL, 0); EXPECT_OK(status, "decommitting memory"); EXPECT_OK(zx_handle_close(vmo), "close handle"); } // Resizing a regular mapped VMO causes a fault. TEST(VmoTestCase, ResizeHazard) { const size_t size = PAGE_SIZE * 2; zx_handle_t vmo; ASSERT_OK(zx_vmo_create(size, ZX_VMO_RESIZABLE, &vmo)); uintptr_t ptr_rw; EXPECT_OK(zx_vmar_map(zx_vmar_root_self(), ZX_VM_PERM_READ | ZX_VM_PERM_WRITE, 0, vmo, 0, size, &ptr_rw), "map"); auto int_arr = reinterpret_cast<int *>(ptr_rw); EXPECT_EQ(int_arr[1], 0); EXPECT_OK(zx_vmo_set_size(vmo, 0u)); EXPECT_EQ(false, probe_for_read(&int_arr[1]), "read probe"); EXPECT_EQ(false, probe_for_write(&int_arr[1]), "write probe"); EXPECT_OK(zx_handle_close(vmo)); EXPECT_OK(zx_vmar_unmap(zx_vmar_root_self(), ptr_rw, size), "unmap"); } } // namespace
#ifndef FENESTRATIONCOMMONSTATE_H #define FENESTRATIONCOMMONSTATE_H namespace FenestrationCommon { // class CState is used to keep validity of object state. In some cases calculations do not need // to be performed before results is requested. class CState { public: virtual ~CState() = default; CState(); CState(CState const & t_State); CState & operator=(CState const & t_State); virtual void resetCalculated() final; // to reset state to non-calculated virtual void setCalculated() final; // calculations are up to date and set state to valid state virtual bool isCalculated() final; // check if state have valid results protected: // some intermediate state variables need to pick up new input parameters. virtual void initializeStateVariables(); private: bool m_StateCalculated; }; } // namespace FenestrationCommon #endif
// Cplus_For_Self_Driving_Car.cpp : This file contains the 'main' function. Program execution begins and ends there. // Library for basic function using C++ #include <iostream> #include <vector> #include "Matrix.h" using namespace std; //// Basic Function Group: (Base 1) //void print(vector<float> vector1); //void print(vector<vector<int>> vector1); // print 2 dimension int vector //vector<float> vectorMultiplication(vector<float> vector1, vector<float> vector2); //vector<vector<int>> vectorMultiplication(vector<vector<int>> vector1, vector<vector<int>> vector2); // //// Localization Function Group: //vector<float> sense(vector<float> p, vector<string> world, string Z, float pHit, float pMiss); //vector<float> move(vector<float> p, vector<string> world, int U, float pExact, float pOvershoot, float pUndershoot); //void print_probability(vector<double> p); // //// Gausian class test int main() { vector <vector <float> > initial_grid(7, vector <float>(5, 0.4)); Matrix matrixa(initial_grid); matrixa.matrix_print(); } //int main() //{ // // std::cout << "Hello World!\n"; // /************************************Test 1********************************************/ // //vector<float> v1(3); //v1[0] = 5.0; v1[1] = 10.0; v1[2] = 27.0; // //vector<float> v2(3); //v2[0] = 2.0; v2[1] = 17.0; v2[2] = 12.0; // //vector<float> v3(v1.size()); //v3 = vectorMultiplication(v1, v2); //print(v3); // // /************************************Test 2********************************************/ // //vector < vector <int> > matrix1(5, vector <int>(3, 2)); // //vector < vector <int> > matrix2(5, vector <int>(3, 26)); // //print(matrix1); // //vector < vector<int> > matrix3; // //matrix3 = vectorMultiplication(matrix1, matrix2); // //print(matrix3); // /************************************Test 3********************************************/ // vector<float> p = { 0.2, 0.2, 0.2, 0.2, 0.2 }; // vector<string> world = { "green", "red", "red", "green", "green" }; // vector<string> measurement = { "red", "green" }; // vector<int> motions = { 1, 1 }; // float pHit = 0.6; // float pMiss = 0.2; // float pExact = 0.8; // float pOvershoot = 0.1; // float pUndershoot = 0.1; // //} // //vector<float> sense(vector<float> p, vector<string> world, string Z, float pHit, float pMiss) { // /* // * Updates probability based on a sensor reading. // */ // vector<float> sense(p.size()); // bool hit; // double s = 0; // sum of the q vector's elements // // for (int i = 0; i < p.size(); i++) { // hit = (Z == world[i]); // sense.push_back(p[i] * (hit * pHit + (1 - hit) * pMiss)); // s += sense[i]; // } // // Divide probabilities by the total sum // for (int i = 0; i < sense.size(); i++) { // sense[i] = sense[i] / s; // } // return sense; //} // //vector<float> move(vector<float> p, vector<string> world, int U, // float pExact, float pOvershoot, float pUndershoot) { // vector<float> move(p.size()); // double s = 0; // // // for (int i = 0; i < p.size(); i++) { // if (i - U < 0) { // s = pExact * p[(i - U) + p.size()]; // } // else { // s = pExact * p[(i - U) % p.size()]; // } // if (i - U - 1 < 0) { // s = s + pOvershoot * p[(i - U - 1) + p.size()]; // } // else { // s = s + pOvershoot * p[(i - U - 1) % p.size()]; // } // if (i - U + 1 < 0) { // s = s + pUndershoot * p[(i - U + 1) + p.size()]; // } // else { // s = s + pUndershoot * p[(i - U + 1) % p.size()]; // } // move[i] = s; // } // // return move; //} // //void print_probability(vector<double> p) { // // Iterates through the vector to print it out // for (int i = 0; i < p.size(); i++) { // cout << p[i] << " "; // } // cout << endl; //} //// Run program: Ctrl + F5 or Debug > Start Without Debugging menu //// Debug program: F5 or Debug > Start Debugging menu // //// Tips for Getting Started: //// 1. Use the Solution Explorer window to add/manage files //// 2. Use the Team Explorer window to connect to source control //// 3. Use the Output window to see build output and other messages //// 4. Use the Error List window to view errors //// 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project //// 6. In the future, to open this project again, go to File > Open > Project and select the .sln file // // /************************************Test 1********************************************/ //// Vector multiplication function! //vector<float> vectorMultiplication(vector<float> vector1, vector<float> vector2) //{ // if (vector1.size() == vector2.size()){ // vector<float> result(vector1.size()); // for (int i = 0; i < vector1.size(); i++) { // result[i] = vector1[i] * vector2[i]; // } // return result; // } // else { // cout << "Vector size is not equal!\n"; // } // return vector<float>(); //} // ////2 dimensional multiplication. //vector<vector<int>> vectorMultiplication(vector<vector<int>> matrix1, vector<vector<int>> matrix2) //{ // if (matrix1.size() == matrix2.size() && matrix1[0].size() == matrix2[0].size()) { // vector<vector<int>> result(matrix1.size(), vector <int>(matrix1[0].size(), 0)); // for (int i = 0; i < matrix1.size(); i++) { // for (int j = 0; j < matrix1[i].size(); j++) // { // result[i][j] = matrix1[i][j] * matrix2[i][j]; // } // } // return result; // } // else { // cout << "Vector size is not equal!\n"; // } // return vector<vector<int>>(); //} // ////print 1 dimension vector. //void print(vector<float> vector1) { // for (int i = 0; i < vector1.size(); ++i) { // if (i % 5 == 0) { // cout << "\n"; // } // cout << vector1[i]<<" "; // } //} // ////print 2 dimensional vector. //void print(vector<vector<int>> vector1) { // for (int i = 0; i < vector1.size(); ++i) { // for (int j = 0; j < vector1[i].size(); ++j) { // cout << vector1[i][j] << " "; // } // cout << "\n"; // } //} ///************************************Test 2********************************************/
/*** * Bitwuzla: Satisfiability Modulo Theories (SMT) solver. * * This file is part of Bitwuzla. * * Copyright (C) 2007-2022 by the authors listed in the AUTHORS file. * * See COPYING for more information on using this software. */ #include "test.h" class TestSMTAxioms : public TestFile { protected: void SetUp() override { TestFile::SetUp(); d_check_log_file = false; } void run_smtaxioms_test(const std::string& s) { for (int32_t i = 1; i <= 8; i++) { run_smtaxioms_test_helper(s, i); } if (s != "bvsmod" && s != "bvsdiv" && s != "bvsrem") { run_smtaxioms_test_helper(s, 16); run_smtaxioms_test_helper(s, 32); run_smtaxioms_test_helper(s, 64); } } private: void run_smtaxioms_test_helper(const std::string& s, int32_t i) { std::stringstream ss_name; ss_name << "smtaxiom" << s << i; run_test(ss_name.str().c_str(), ".smt2", BZLA_RESULT_UNSAT); TearDown(); SetUp(); } }; TEST_F(TestSMTAxioms, bvnand) { run_smtaxioms_test("bvnand"); } TEST_F(TestSMTAxioms, bvnor) { run_smtaxioms_test("bvnor"); } TEST_F(TestSMTAxioms, bvsge) { run_smtaxioms_test("bvsge"); } TEST_F(TestSMTAxioms, bvsgt) { run_smtaxioms_test("bvsgt"); } TEST_F(TestSMTAxioms, bvsle) { run_smtaxioms_test("bvsle"); } TEST_F(TestSMTAxioms, bvslt) { run_smtaxioms_test("bvslt"); } TEST_F(TestSMTAxioms, bvuge) { run_smtaxioms_test("bvuge"); } TEST_F(TestSMTAxioms, bvugt) { run_smtaxioms_test("bvugt"); } TEST_F(TestSMTAxioms, bvule) { run_smtaxioms_test("bvule"); } TEST_F(TestSMTAxioms, bvxnor) { run_smtaxioms_test("bvxnor"); } TEST_F(TestSMTAxioms, bvxor) { run_smtaxioms_test("bvxor"); } TEST_F(TestSMTAxioms, bvsub) { run_smtaxioms_test("bvsub"); } /* below are the 'hard' test cases (no 16, 32, 64 bits) */ TEST_F(TestSMTAxioms, bvsmod) { run_smtaxioms_test("bvsmod"); } TEST_F(TestSMTAxioms, bvsdiv) { run_smtaxioms_test("bvsdiv"); } TEST_F(TestSMTAxioms, bvsrem) { run_smtaxioms_test("bvsrem"); }
// Copyright (c) 2012-2017 The Knotcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <rpc/server.h> #include <rpc/client.h> #include <base58.h> #include <core_io.h> #include <netbase.h> #include <test/test_knotcoin.h> #include <boost/algorithm/string.hpp> #include <boost/test/unit_test.hpp> #include <univalue.h> UniValue CallRPC(std::string args) { std::vector<std::string> vArgs; boost::split(vArgs, args, boost::is_any_of(" \t")); std::string strMethod = vArgs[0]; vArgs.erase(vArgs.begin()); JSONRPCRequest request; request.strMethod = strMethod; request.params = RPCConvertValues(strMethod, vArgs); request.fHelp = false; BOOST_CHECK(tableRPC[strMethod]); rpcfn_type method = tableRPC[strMethod]->actor; try { UniValue result = (*method)(request); return result; } catch (const UniValue& objError) { throw std::runtime_error(find_value(objError, "message").get_str()); } } BOOST_FIXTURE_TEST_SUITE(rpc_tests, TestingSetup) BOOST_AUTO_TEST_CASE(rpc_rawparams) { // Test raw transaction API argument handling UniValue r; BOOST_CHECK_THROW(CallRPC("getrawtransaction"), std::runtime_error); BOOST_CHECK_THROW(CallRPC("getrawtransaction not_hex"), std::runtime_error); BOOST_CHECK_THROW(CallRPC("getrawtransaction a3b807410df0b60fcb9736768df5823938b2f838694939ba45f3c0a1bff150ed not_int"), std::runtime_error); BOOST_CHECK_THROW(CallRPC("createrawtransaction"), std::runtime_error); BOOST_CHECK_THROW(CallRPC("createrawtransaction null null"), std::runtime_error); BOOST_CHECK_THROW(CallRPC("createrawtransaction not_array"), std::runtime_error); BOOST_CHECK_THROW(CallRPC("createrawtransaction [] []"), std::runtime_error); BOOST_CHECK_THROW(CallRPC("createrawtransaction {} {}"), std::runtime_error); BOOST_CHECK_NO_THROW(CallRPC("createrawtransaction [] {}")); BOOST_CHECK_THROW(CallRPC("createrawtransaction [] {} extra"), std::runtime_error); BOOST_CHECK_THROW(CallRPC("decoderawtransaction"), std::runtime_error); BOOST_CHECK_THROW(CallRPC("decoderawtransaction null"), std::runtime_error); BOOST_CHECK_THROW(CallRPC("decoderawtransaction DEADBEEF"), std::runtime_error); std::string rawtx = "0100000001a15d57094aa7a21a28cb20b59aab8fc7d1149a3bdbcddba9c622e4f5f6a99ece010000006c493046022100f93bb0e7d8db7bd46e40132d1f8242026e045f03a0efe71bbb8e3f475e970d790221009337cd7f1f929f00cc6ff01f03729b069a7c21b59b1736ddfee5db5946c5da8c0121033b9b137ee87d5a812d6f506efdd37f0affa7ffc310711c06c7f3e097c9447c52ffffffff0100e1f505000000001976a9140389035a9225b3839e2bbf32d826a1e222031fd888ac00000000"; BOOST_CHECK_NO_THROW(r = CallRPC(std::string("decoderawtransaction ")+rawtx)); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "size").get_int(), 193); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "version").get_int(), 1); BOOST_CHECK_EQUAL(find_value(r.get_obj(), "locktime").get_int(), 0); BOOST_CHECK_THROW(CallRPC(std::string("decoderawtransaction ")+rawtx+" extra"), std::runtime_error); BOOST_CHECK_NO_THROW(r = CallRPC(std::string("decoderawtransaction ")+rawtx+" false")); BOOST_CHECK_THROW(r = CallRPC(std::string("decoderawtransaction ")+rawtx+" false extra"), std::runtime_error); BOOST_CHECK_THROW(CallRPC("signrawtransaction"), std::runtime_error); BOOST_CHECK_THROW(CallRPC("signrawtransaction null"), std::runtime_error); BOOST_CHECK_THROW(CallRPC("signrawtransaction ff00"), std::runtime_error); BOOST_CHECK_NO_THROW(CallRPC(std::string("signrawtransaction ")+rawtx)); BOOST_CHECK_NO_THROW(CallRPC(std::string("signrawtransaction ")+rawtx+" null null NONE|ANYONECANPAY")); BOOST_CHECK_NO_THROW(CallRPC(std::string("signrawtransaction ")+rawtx+" [] [] NONE|ANYONECANPAY")); BOOST_CHECK_THROW(CallRPC(std::string("signrawtransaction ")+rawtx+" null null badenum"), std::runtime_error); // Only check failure cases for sendrawtransaction, there's no network to send to... BOOST_CHECK_THROW(CallRPC("sendrawtransaction"), std::runtime_error); BOOST_CHECK_THROW(CallRPC("sendrawtransaction null"), std::runtime_error); BOOST_CHECK_THROW(CallRPC("sendrawtransaction DEADBEEF"), std::runtime_error); BOOST_CHECK_THROW(CallRPC(std::string("sendrawtransaction ")+rawtx+" extra"), std::runtime_error); } BOOST_AUTO_TEST_CASE(rpc_togglenetwork) { UniValue r; r = CallRPC("getnetworkinfo"); bool netState = find_value(r.get_obj(), "networkactive").get_bool(); BOOST_CHECK_EQUAL(netState, true); BOOST_CHECK_NO_THROW(CallRPC("setnetworkactive false")); r = CallRPC("getnetworkinfo"); int numConnection = find_value(r.get_obj(), "connections").get_int(); BOOST_CHECK_EQUAL(numConnection, 0); netState = find_value(r.get_obj(), "networkactive").get_bool(); BOOST_CHECK_EQUAL(netState, false); BOOST_CHECK_NO_THROW(CallRPC("setnetworkactive true")); r = CallRPC("getnetworkinfo"); netState = find_value(r.get_obj(), "networkactive").get_bool(); BOOST_CHECK_EQUAL(netState, true); } BOOST_AUTO_TEST_CASE(rpc_rawsign) { UniValue r; // input is a 1-of-2 multisig (so is output): std::string prevout = "[{\"txid\":\"b4cc287e58f87cdae59417329f710f3ecd75a4ee1d2872b7248f50977c8493f3\"," "\"vout\":1,\"scriptPubKey\":\"a914b10c9df5f7edf436c697f02f1efdba4cf399615187\"," "\"redeemScript\":\"512103debedc17b3df2badbcdd86d5feb4562b86fe182e5998abd8bcd4f122c6155b1b21027e940bb73ab8732bfdf7f9216ecefca5b94d6df834e77e108f68e66f126044c052ae\"}]"; r = CallRPC(std::string("createrawtransaction ")+prevout+" "+ "{\"3HqAe9LtNBjnsfM4CyYaWTnvCaUYT7v4oZ\":11}"); std::string notsigned = r.get_str(); std::string privkey1 = "\"KzsXybp9jX64P5ekX1KUxRQ79Jht9uzW7LorgwE65i5rWACL6LQe\""; std::string privkey2 = "\"Kyhdf5LuKTRx4ge69ybABsiUAWjVRK4XGxAKk2FQLp2HjGMy87Z4\""; r = CallRPC(std::string("signrawtransaction ")+notsigned+" "+prevout+" "+"[]"); BOOST_CHECK(find_value(r.get_obj(), "complete").get_bool() == false); r = CallRPC(std::string("signrawtransaction ")+notsigned+" "+prevout+" "+"["+privkey1+","+privkey2+"]"); BOOST_CHECK(find_value(r.get_obj(), "complete").get_bool() == true); } BOOST_AUTO_TEST_CASE(rpc_createraw_op_return) { BOOST_CHECK_NO_THROW(CallRPC("createrawtransaction [{\"txid\":\"a3b807410df0b60fcb9736768df5823938b2f838694939ba45f3c0a1bff150ed\",\"vout\":0}] {\"data\":\"68656c6c6f776f726c64\"}")); // Allow more than one data transaction output BOOST_CHECK_NO_THROW(CallRPC("createrawtransaction [{\"txid\":\"a3b807410df0b60fcb9736768df5823938b2f838694939ba45f3c0a1bff150ed\",\"vout\":0}] {\"data\":\"68656c6c6f776f726c64\",\"data\":\"68656c6c6f776f726c64\"}")); // Key not "data" (bad address) BOOST_CHECK_THROW(CallRPC("createrawtransaction [{\"txid\":\"a3b807410df0b60fcb9736768df5823938b2f838694939ba45f3c0a1bff150ed\",\"vout\":0}] {\"somedata\":\"68656c6c6f776f726c64\"}"), std::runtime_error); // Bad hex encoding of data output BOOST_CHECK_THROW(CallRPC("createrawtransaction [{\"txid\":\"a3b807410df0b60fcb9736768df5823938b2f838694939ba45f3c0a1bff150ed\",\"vout\":0}] {\"data\":\"12345\"}"), std::runtime_error); BOOST_CHECK_THROW(CallRPC("createrawtransaction [{\"txid\":\"a3b807410df0b60fcb9736768df5823938b2f838694939ba45f3c0a1bff150ed\",\"vout\":0}] {\"data\":\"12345g\"}"), std::runtime_error); // Data 81 bytes long BOOST_CHECK_NO_THROW(CallRPC("createrawtransaction [{\"txid\":\"a3b807410df0b60fcb9736768df5823938b2f838694939ba45f3c0a1bff150ed\",\"vout\":0}] {\"data\":\"010203040506070809101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081\"}")); } BOOST_AUTO_TEST_CASE(rpc_format_monetary_values) { BOOST_CHECK(ValueFromAmount(0LL).write() == "0.00000000"); BOOST_CHECK(ValueFromAmount(1LL).write() == "0.00000001"); BOOST_CHECK(ValueFromAmount(17622195LL).write() == "0.17622195"); BOOST_CHECK(ValueFromAmount(50000000LL).write() == "0.50000000"); BOOST_CHECK(ValueFromAmount(89898989LL).write() == "0.89898989"); BOOST_CHECK(ValueFromAmount(100000000LL).write() == "1.00000000"); BOOST_CHECK(ValueFromAmount(2099999999999990LL).write() == "20999999.99999990"); BOOST_CHECK(ValueFromAmount(2099999999999999LL).write() == "20999999.99999999"); BOOST_CHECK_EQUAL(ValueFromAmount(0).write(), "0.00000000"); BOOST_CHECK_EQUAL(ValueFromAmount((COIN/10000)*123456789).write(), "12345.67890000"); BOOST_CHECK_EQUAL(ValueFromAmount(-COIN).write(), "-1.00000000"); BOOST_CHECK_EQUAL(ValueFromAmount(-COIN/10).write(), "-0.10000000"); BOOST_CHECK_EQUAL(ValueFromAmount(COIN*100000000).write(), "100000000.00000000"); BOOST_CHECK_EQUAL(ValueFromAmount(COIN*10000000).write(), "10000000.00000000"); BOOST_CHECK_EQUAL(ValueFromAmount(COIN*1000000).write(), "1000000.00000000"); BOOST_CHECK_EQUAL(ValueFromAmount(COIN*100000).write(), "100000.00000000"); BOOST_CHECK_EQUAL(ValueFromAmount(COIN*10000).write(), "10000.00000000"); BOOST_CHECK_EQUAL(ValueFromAmount(COIN*1000).write(), "1000.00000000"); BOOST_CHECK_EQUAL(ValueFromAmount(COIN*100).write(), "100.00000000"); BOOST_CHECK_EQUAL(ValueFromAmount(COIN*10).write(), "10.00000000"); BOOST_CHECK_EQUAL(ValueFromAmount(COIN).write(), "1.00000000"); BOOST_CHECK_EQUAL(ValueFromAmount(COIN/10).write(), "0.10000000"); BOOST_CHECK_EQUAL(ValueFromAmount(COIN/100).write(), "0.01000000"); BOOST_CHECK_EQUAL(ValueFromAmount(COIN/1000).write(), "0.00100000"); BOOST_CHECK_EQUAL(ValueFromAmount(COIN/10000).write(), "0.00010000"); BOOST_CHECK_EQUAL(ValueFromAmount(COIN/100000).write(), "0.00001000"); BOOST_CHECK_EQUAL(ValueFromAmount(COIN/1000000).write(), "0.00000100"); BOOST_CHECK_EQUAL(ValueFromAmount(COIN/10000000).write(), "0.00000010"); BOOST_CHECK_EQUAL(ValueFromAmount(COIN/100000000).write(), "0.00000001"); } static UniValue ValueFromString(const std::string &str) { UniValue value; BOOST_CHECK(value.setNumStr(str)); return value; } BOOST_AUTO_TEST_CASE(rpc_parse_monetary_values) { BOOST_CHECK_THROW(AmountFromValue(ValueFromString("-0.00000001")), UniValue); BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("0")), 0LL); BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("0.00000000")), 0LL); BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("0.00000001")), 1LL); BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("0.17622195")), 17622195LL); BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("0.5")), 50000000LL); BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("0.50000000")), 50000000LL); BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("0.89898989")), 89898989LL); BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("1.00000000")), 100000000LL); BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("20999999.9999999")), 2099999999999990LL); BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("20999999.99999999")), 2099999999999999LL); BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("1e-8")), COIN/100000000); BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("0.1e-7")), COIN/100000000); BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("0.01e-6")), COIN/100000000); BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("0.0000000000000000000000000000000000000000000000000000000000000000000000000001e+68")), COIN/100000000); BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("10000000000000000000000000000000000000000000000000000000000000000e-64")), COIN); BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("0.000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000e64")), COIN); BOOST_CHECK_THROW(AmountFromValue(ValueFromString("1e-9")), UniValue); //should fail BOOST_CHECK_THROW(AmountFromValue(ValueFromString("0.000000019")), UniValue); //should fail BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("0.00000001000000")), 1LL); //should pass, cut trailing 0 BOOST_CHECK_THROW(AmountFromValue(ValueFromString("19e-9")), UniValue); //should fail BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("0.19e-6")), 19); //should pass, leading 0 is present BOOST_CHECK_THROW(AmountFromValue(ValueFromString("92233720368.54775808")), UniValue); //overflow error BOOST_CHECK_THROW(AmountFromValue(ValueFromString("1e+11")), UniValue); //overflow error BOOST_CHECK_THROW(AmountFromValue(ValueFromString("1e11")), UniValue); //overflow error signless BOOST_CHECK_THROW(AmountFromValue(ValueFromString("93e+9")), UniValue); //overflow error } BOOST_AUTO_TEST_CASE(json_parse_errors) { // Valid BOOST_CHECK_EQUAL(ParseNonRFCJSONValue("1.0").get_real(), 1.0); // Valid, with leading or trailing whitespace BOOST_CHECK_EQUAL(ParseNonRFCJSONValue(" 1.0").get_real(), 1.0); BOOST_CHECK_EQUAL(ParseNonRFCJSONValue("1.0 ").get_real(), 1.0); BOOST_CHECK_THROW(AmountFromValue(ParseNonRFCJSONValue(".19e-6")), std::runtime_error); //should fail, missing leading 0, therefore invalid JSON BOOST_CHECK_EQUAL(AmountFromValue(ParseNonRFCJSONValue("0.00000000000000000000000000000000000001e+30 ")), 1); // Invalid, initial garbage BOOST_CHECK_THROW(ParseNonRFCJSONValue("[1.0"), std::runtime_error); BOOST_CHECK_THROW(ParseNonRFCJSONValue("a1.0"), std::runtime_error); // Invalid, trailing garbage BOOST_CHECK_THROW(ParseNonRFCJSONValue("1.0sds"), std::runtime_error); BOOST_CHECK_THROW(ParseNonRFCJSONValue("1.0]"), std::runtime_error); // KNOT addresses should fail parsing BOOST_CHECK_THROW(ParseNonRFCJSONValue("175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W"), std::runtime_error); BOOST_CHECK_THROW(ParseNonRFCJSONValue("3J98t1WpEZ73CNmQviecrnyiWrnqRhWNL"), std::runtime_error); } BOOST_AUTO_TEST_CASE(rpc_ban) { BOOST_CHECK_NO_THROW(CallRPC(std::string("clearbanned"))); UniValue r; BOOST_CHECK_NO_THROW(r = CallRPC(std::string("setban 127.0.0.0 add"))); BOOST_CHECK_THROW(r = CallRPC(std::string("setban 127.0.0.0:8334")), std::runtime_error); //portnumber for setban not allowed BOOST_CHECK_NO_THROW(r = CallRPC(std::string("listbanned"))); UniValue ar = r.get_array(); UniValue o1 = ar[0].get_obj(); UniValue adr = find_value(o1, "address"); BOOST_CHECK_EQUAL(adr.get_str(), "127.0.0.0/32"); BOOST_CHECK_NO_THROW(CallRPC(std::string("setban 127.0.0.0 remove"))); BOOST_CHECK_NO_THROW(r = CallRPC(std::string("listbanned"))); ar = r.get_array(); BOOST_CHECK_EQUAL(ar.size(), 0); BOOST_CHECK_NO_THROW(r = CallRPC(std::string("setban 127.0.0.0/24 add 1607731200 true"))); BOOST_CHECK_NO_THROW(r = CallRPC(std::string("listbanned"))); ar = r.get_array(); o1 = ar[0].get_obj(); adr = find_value(o1, "address"); UniValue banned_until = find_value(o1, "banned_until"); BOOST_CHECK_EQUAL(adr.get_str(), "127.0.0.0/24"); BOOST_CHECK_EQUAL(banned_until.get_int64(), 1607731200); // absolute time check BOOST_CHECK_NO_THROW(CallRPC(std::string("clearbanned"))); BOOST_CHECK_NO_THROW(r = CallRPC(std::string("setban 127.0.0.0/24 add 200"))); BOOST_CHECK_NO_THROW(r = CallRPC(std::string("listbanned"))); ar = r.get_array(); o1 = ar[0].get_obj(); adr = find_value(o1, "address"); banned_until = find_value(o1, "banned_until"); BOOST_CHECK_EQUAL(adr.get_str(), "127.0.0.0/24"); int64_t now = GetTime(); BOOST_CHECK(banned_until.get_int64() > now); BOOST_CHECK(banned_until.get_int64()-now <= 200); // must throw an exception because 127.0.0.1 is in already banned subnet range BOOST_CHECK_THROW(r = CallRPC(std::string("setban 127.0.0.1 add")), std::runtime_error); BOOST_CHECK_NO_THROW(CallRPC(std::string("setban 127.0.0.0/24 remove"))); BOOST_CHECK_NO_THROW(r = CallRPC(std::string("listbanned"))); ar = r.get_array(); BOOST_CHECK_EQUAL(ar.size(), 0); BOOST_CHECK_NO_THROW(r = CallRPC(std::string("setban 127.0.0.0/255.255.0.0 add"))); BOOST_CHECK_THROW(r = CallRPC(std::string("setban 127.0.1.1 add")), std::runtime_error); BOOST_CHECK_NO_THROW(CallRPC(std::string("clearbanned"))); BOOST_CHECK_NO_THROW(r = CallRPC(std::string("listbanned"))); ar = r.get_array(); BOOST_CHECK_EQUAL(ar.size(), 0); BOOST_CHECK_THROW(r = CallRPC(std::string("setban test add")), std::runtime_error); //invalid IP //IPv6 tests BOOST_CHECK_NO_THROW(r = CallRPC(std::string("setban FE80:0000:0000:0000:0202:B3FF:FE1E:8329 add"))); BOOST_CHECK_NO_THROW(r = CallRPC(std::string("listbanned"))); ar = r.get_array(); o1 = ar[0].get_obj(); adr = find_value(o1, "address"); BOOST_CHECK_EQUAL(adr.get_str(), "fe80::202:b3ff:fe1e:8329/128"); BOOST_CHECK_NO_THROW(CallRPC(std::string("clearbanned"))); BOOST_CHECK_NO_THROW(r = CallRPC(std::string("setban 2001:db8::/ffff:fffc:0:0:0:0:0:0 add"))); BOOST_CHECK_NO_THROW(r = CallRPC(std::string("listbanned"))); ar = r.get_array(); o1 = ar[0].get_obj(); adr = find_value(o1, "address"); BOOST_CHECK_EQUAL(adr.get_str(), "2001:db8::/30"); BOOST_CHECK_NO_THROW(CallRPC(std::string("clearbanned"))); BOOST_CHECK_NO_THROW(r = CallRPC(std::string("setban 2001:4d48:ac57:400:cacf:e9ff:fe1d:9c63/128 add"))); BOOST_CHECK_NO_THROW(r = CallRPC(std::string("listbanned"))); ar = r.get_array(); o1 = ar[0].get_obj(); adr = find_value(o1, "address"); BOOST_CHECK_EQUAL(adr.get_str(), "2001:4d48:ac57:400:cacf:e9ff:fe1d:9c63/128"); } BOOST_AUTO_TEST_CASE(rpc_convert_values_generatetoaddress) { UniValue result; BOOST_CHECK_NO_THROW(result = RPCConvertValues("generatetoaddress", {"101", "mkESjLZW66TmHhiFX8MCaBjrhZ543PPh9a"})); BOOST_CHECK_EQUAL(result[0].get_int(), 101); BOOST_CHECK_EQUAL(result[1].get_str(), "mkESjLZW66TmHhiFX8MCaBjrhZ543PPh9a"); BOOST_CHECK_NO_THROW(result = RPCConvertValues("generatetoaddress", {"101", "mhMbmE2tE9xzJYCV9aNC8jKWN31vtGrguU"})); BOOST_CHECK_EQUAL(result[0].get_int(), 101); BOOST_CHECK_EQUAL(result[1].get_str(), "mhMbmE2tE9xzJYCV9aNC8jKWN31vtGrguU"); BOOST_CHECK_NO_THROW(result = RPCConvertValues("generatetoaddress", {"1", "mkESjLZW66TmHhiFX8MCaBjrhZ543PPh9a", "9"})); BOOST_CHECK_EQUAL(result[0].get_int(), 1); BOOST_CHECK_EQUAL(result[1].get_str(), "mkESjLZW66TmHhiFX8MCaBjrhZ543PPh9a"); BOOST_CHECK_EQUAL(result[2].get_int(), 9); BOOST_CHECK_NO_THROW(result = RPCConvertValues("generatetoaddress", {"1", "mhMbmE2tE9xzJYCV9aNC8jKWN31vtGrguU", "9"})); BOOST_CHECK_EQUAL(result[0].get_int(), 1); BOOST_CHECK_EQUAL(result[1].get_str(), "mhMbmE2tE9xzJYCV9aNC8jKWN31vtGrguU"); BOOST_CHECK_EQUAL(result[2].get_int(), 9); } BOOST_AUTO_TEST_SUITE_END()
/* * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <LibGUI/Action.h> #include <LibGUI/ActionGroup.h> #include <LibGUI/Application.h> #include <LibGUI/Button.h> #include <LibGUI/MenuItem.h> #include <LibGUI/Window.h> namespace GUI { namespace CommonActions { NonnullRefPtr<Action> make_open_action(Function<void(Action&)> callback, Core::Object* parent) { return Action::create("Open...", { Mod_Ctrl, Key_O }, Gfx::Bitmap::load_from_file("/res/icons/16x16/open.png"), move(callback), parent); } NonnullRefPtr<Action> make_save_action(Function<void(Action&)> callback, Core::Object* parent) { return Action::create("Save", { Mod_Ctrl, Key_S }, Gfx::Bitmap::load_from_file("/res/icons/16x16/save.png"), move(callback), parent); } NonnullRefPtr<Action> make_save_as_action(Function<void(Action&)> callback, Core::Object* parent) { return Action::create("Save As...", { Mod_Ctrl | Mod_Shift, Key_S }, Gfx::Bitmap::load_from_file("/res/icons/16x16/save.png"), move(callback), parent); } NonnullRefPtr<Action> make_move_to_front_action(Function<void(Action&)> callback, Core::Object* parent) { return Action::create("Move to front", { Mod_Ctrl | Mod_Shift, Key_Up }, Gfx::Bitmap::load_from_file("/res/icons/16x16/move-to-front.png"), move(callback), parent); } NonnullRefPtr<Action> make_move_to_back_action(Function<void(Action&)> callback, Core::Object* parent) { return Action::create("Move to back", { Mod_Ctrl | Mod_Shift, Key_Down }, Gfx::Bitmap::load_from_file("/res/icons/16x16/move-to-back.png"), move(callback), parent); } NonnullRefPtr<Action> make_undo_action(Function<void(Action&)> callback, Core::Object* parent) { return Action::create("Undo", { Mod_Ctrl, Key_Z }, Gfx::Bitmap::load_from_file("/res/icons/16x16/undo.png"), move(callback), parent); } NonnullRefPtr<Action> make_redo_action(Function<void(Action&)> callback, Core::Object* parent) { return Action::create("Redo", { Mod_Ctrl, Key_Y }, Gfx::Bitmap::load_from_file("/res/icons/16x16/redo.png"), move(callback), parent); } NonnullRefPtr<Action> make_delete_action(Function<void(Action&)> callback, Core::Object* parent) { return Action::create("Delete", { Mod_None, Key_Delete }, Gfx::Bitmap::load_from_file("/res/icons/16x16/delete.png"), move(callback), parent); } NonnullRefPtr<Action> make_cut_action(Function<void(Action&)> callback, Core::Object* parent) { return Action::create("Cut", { Mod_Ctrl, Key_X }, Gfx::Bitmap::load_from_file("/res/icons/16x16/edit-cut.png"), move(callback), parent); } NonnullRefPtr<Action> make_copy_action(Function<void(Action&)> callback, Core::Object* parent) { return Action::create("Copy", { Mod_Ctrl, Key_C }, Gfx::Bitmap::load_from_file("/res/icons/16x16/edit-copy.png"), move(callback), parent); } NonnullRefPtr<Action> make_paste_action(Function<void(Action&)> callback, Core::Object* parent) { return Action::create("Paste", { Mod_Ctrl, Key_V }, Gfx::Bitmap::load_from_file("/res/icons/16x16/paste.png"), move(callback), parent); } NonnullRefPtr<Action> make_fullscreen_action(Function<void(Action&)> callback, Core::Object* parent) { return Action::create("Fullscreen", { Mod_None, Key_F11 }, move(callback), parent); } NonnullRefPtr<Action> make_quit_action(Function<void(Action&)> callback) { return Action::create("Quit", { Mod_Alt, Key_F4 }, move(callback)); } NonnullRefPtr<Action> make_help_action(Function<void(Action&)> callback, Core::Object* parent) { return Action::create("Contents", { Mod_None, Key_F1 }, Gfx::Bitmap::load_from_file("/res/icons/16x16/app-help.png"), move(callback), parent); } NonnullRefPtr<Action> make_go_back_action(Function<void(Action&)> callback, Core::Object* parent) { return Action::create("Go back", { Mod_Alt, Key_Left }, Gfx::Bitmap::load_from_file("/res/icons/16x16/go-back.png"), move(callback), parent); } NonnullRefPtr<Action> make_go_forward_action(Function<void(Action&)> callback, Core::Object* parent) { return Action::create("Go forward", { Mod_Alt, Key_Right }, Gfx::Bitmap::load_from_file("/res/icons/16x16/go-forward.png"), move(callback), parent); } NonnullRefPtr<Action> make_go_home_action(Function<void(Action&)> callback, Core::Object* parent) { return Action::create("Go home", { Mod_Alt, Key_Home }, Gfx::Bitmap::load_from_file("/res/icons/16x16/go-home.png"), move(callback), parent); } NonnullRefPtr<Action> make_reload_action(Function<void(Action&)> callback, Core::Object* parent) { return Action::create("Reload", { Mod_Ctrl, Key_R }, Gfx::Bitmap::load_from_file("/res/icons/16x16/reload.png"), move(callback), parent); } NonnullRefPtr<Action> make_select_all_action(Function<void(Action&)> callback, Core::Object* parent) { return Action::create("Select all", { Mod_Ctrl, Key_A }, Gfx::Bitmap::load_from_file("/res/icons/16x16/select-all.png"), move(callback), parent); } } Action::Action(const StringView& text, Function<void(Action&)> on_activation_callback, Core::Object* parent, bool checkable) : Core::Object(parent) , on_activation(move(on_activation_callback)) , m_text(text) , m_checkable(checkable) { } Action::Action(const StringView& text, RefPtr<Gfx::Bitmap>&& icon, Function<void(Action&)> on_activation_callback, Core::Object* parent, bool checkable) : Core::Object(parent) , on_activation(move(on_activation_callback)) , m_text(text) , m_icon(move(icon)) , m_checkable(checkable) { } Action::Action(const StringView& text, const Shortcut& shortcut, Function<void(Action&)> on_activation_callback, Core::Object* parent, bool checkable) : Action(text, shortcut, nullptr, move(on_activation_callback), parent, checkable) { } Action::Action(const StringView& text, const Shortcut& shortcut, RefPtr<Gfx::Bitmap>&& icon, Function<void(Action&)> on_activation_callback, Core::Object* parent, bool checkable) : Core::Object(parent) , on_activation(move(on_activation_callback)) , m_text(text) , m_icon(move(icon)) , m_shortcut(shortcut) , m_checkable(checkable) { if (parent && is<Widget>(*parent)) { m_scope = ShortcutScope::WidgetLocal; } else if (parent && is<Window>(*parent)) { m_scope = ShortcutScope::WindowLocal; } else { m_scope = ShortcutScope::ApplicationGlobal; if (auto* app = Application::the()) { app->register_global_shortcut_action({}, *this); } } } Action::~Action() { if (m_shortcut.is_valid() && m_scope == ShortcutScope::ApplicationGlobal) { if (auto* app = Application::the()) app->unregister_global_shortcut_action({}, *this); } } void Action::activate(Core::Object* activator) { if (!on_activation) return; if (activator) m_activator = activator->make_weak_ptr(); if (is_checkable()) { if (m_action_group) { if (m_action_group->is_unchecking_allowed()) set_checked(!is_checked()); else set_checked(true); } else { set_checked(!is_checked()); } } on_activation(*this); m_activator = nullptr; } void Action::register_button(Badge<Button>, Button& button) { m_buttons.set(&button); } void Action::unregister_button(Badge<Button>, Button& button) { m_buttons.remove(&button); } void Action::register_menu_item(Badge<MenuItem>, MenuItem& menu_item) { m_menu_items.set(&menu_item); } void Action::unregister_menu_item(Badge<MenuItem>, MenuItem& menu_item) { m_menu_items.remove(&menu_item); } template<typename Callback> void Action::for_each_toolbar_button(Callback callback) { for (auto& it : m_buttons) callback(*it); } template<typename Callback> void Action::for_each_menu_item(Callback callback) { for (auto& it : m_menu_items) callback(*it); } void Action::set_enabled(bool enabled) { if (m_enabled == enabled) return; m_enabled = enabled; for_each_toolbar_button([enabled](auto& button) { button.set_enabled(enabled); }); for_each_menu_item([enabled](auto& item) { item.set_enabled(enabled); }); } void Action::set_checked(bool checked) { if (m_checked == checked) return; m_checked = checked; if (m_checked && m_action_group) { m_action_group->for_each_action([this](auto& other_action) { if (this == &other_action) return IterationDecision::Continue; if (other_action.is_checkable()) other_action.set_checked(false); return IterationDecision::Continue; }); } for_each_toolbar_button([checked](auto& button) { button.set_checked(checked); }); for_each_menu_item([checked](MenuItem& item) { item.set_checked(checked); }); } void Action::set_group(Badge<ActionGroup>, ActionGroup* group) { m_action_group = group ? group->make_weak_ptr() : nullptr; } void Action::set_icon(const Gfx::Bitmap* icon) { m_icon = icon; } }
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/bind.h" #include "base/file_path.h" #include "chrome/browser/download/download_danger_prompt.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_commands.h" #include "chrome/browser/ui/browser_tabstrip.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "content/public/test/mock_download_item.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using ::testing::_; using ::testing::ByRef; using ::testing::Eq; using ::testing::Return; using ::testing::SaveArg; class DownloadDangerPromptTest : public InProcessBrowserTest { public: DownloadDangerPromptTest() : download_observer_(NULL), prompt_(NULL), expected_action_(DownloadDangerPrompt::CANCEL), did_receive_callback_(false) { } virtual ~DownloadDangerPromptTest() { } // Opens a new tab and waits for navigations to finish. If there are pending // navigations, the constrained prompt might be dismissed when the navigation // completes. void OpenNewTab() { ui_test_utils::NavigateToURLWithDisposition( browser(), GURL("about:blank"), NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB | ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION); } void SetUpExpectations(DownloadDangerPrompt::Action expected_action) { did_receive_callback_ = false; expected_action_ = expected_action; SetUpDownloadItemExpectations(); CreatePrompt(); } void VerifyExpectations() { content::RunAllPendingInMessageLoop(); // At the end of each test, we expect no more activity from the prompt. The // prompt shouldn't exist anymore either. EXPECT_TRUE(did_receive_callback_); EXPECT_FALSE(prompt_); testing::Mock::VerifyAndClearExpectations(&download_); } void SimulatePromptAction(DownloadDangerPrompt::Action action) { prompt_->InvokeActionForTesting(action); } content::MockDownloadItem& download() { return download_; } content::DownloadItem::Observer* download_observer() { return download_observer_; } DownloadDangerPrompt* prompt() { return prompt_; } private: void SetUpDownloadItemExpectations() { EXPECT_CALL(download_, GetFileNameToReportUser()).WillRepeatedly(Return( FilePath(FILE_PATH_LITERAL("evil.exe")))); EXPECT_CALL(download_, AddObserver(_)) .WillOnce(SaveArg<0>(&download_observer_)); EXPECT_CALL(download_, RemoveObserver(Eq(ByRef(download_observer_)))); } void CreatePrompt() { prompt_ = DownloadDangerPrompt::Create( &download_, browser()->tab_strip_model()->GetActiveWebContents(), base::Bind(&DownloadDangerPromptTest::PromptCallback, this, DownloadDangerPrompt::ACCEPT), base::Bind(&DownloadDangerPromptTest::PromptCallback, this, DownloadDangerPrompt::CANCEL)); content::RunAllPendingInMessageLoop(); } void PromptCallback(DownloadDangerPrompt::Action action) { EXPECT_FALSE(did_receive_callback_); EXPECT_EQ(expected_action_, action); did_receive_callback_ = true; prompt_ = NULL; } content::MockDownloadItem download_; content::DownloadItem::Observer* download_observer_; DownloadDangerPrompt* prompt_; DownloadDangerPrompt::Action expected_action_; bool did_receive_callback_; DISALLOW_COPY_AND_ASSIGN(DownloadDangerPromptTest); }; IN_PROC_BROWSER_TEST_F(DownloadDangerPromptTest, TestAll) { OpenNewTab(); // The Accept action should cause the accept callback to be invoked. SetUpExpectations(DownloadDangerPrompt::ACCEPT); SimulatePromptAction(DownloadDangerPrompt::ACCEPT); VerifyExpectations(); // The Discard action should cause the discard callback to be invoked. SetUpExpectations(DownloadDangerPrompt::CANCEL); SimulatePromptAction(DownloadDangerPrompt::CANCEL); VerifyExpectations(); // If the download is no longer in-progress, the dialog should dismiss itself. SetUpExpectations(DownloadDangerPrompt::CANCEL); EXPECT_CALL(download(), IsInProgress()).WillOnce(Return(false)); download_observer()->OnDownloadUpdated(&download()); VerifyExpectations(); // If the download is no longer dangerous (because it was accepted), the // dialog should dismiss itself. SetUpExpectations(DownloadDangerPrompt::CANCEL); EXPECT_CALL(download(), IsInProgress()).WillOnce(Return(true)); EXPECT_CALL(download(), IsDangerous()).WillOnce(Return(false)); download_observer()->OnDownloadUpdated(&download()); VerifyExpectations(); // If the containing tab is closed, the dialog should be canceled. OpenNewTab(); SetUpExpectations(DownloadDangerPrompt::CANCEL); chrome::CloseTab(browser()); VerifyExpectations(); }
// // created by Vlad Savchuk on 25/09/20. // #include <iostream> #include <cmath> #include <chrono> #include <random> #include "PrimalityTest.h" using namespace std; //return random Number in range (lower, upper) long long PrimalityTest::getRandomNumber(long long lower, long long upper) { auto seed = std::chrono::system_clock::now().time_since_epoch().count(); mt19937_64 rng(seed); uniform_int_distribution<long long> d{lower, upper}; return d(rng); } //Solovay–Strassen primality test without hints bool PrimalityTest::solovayStrassen(long long n, int k) { if (n == 2) return true; if (n < 3) return false; if (n % 2 == 0) return false; for (long long i = 0; i < k; i++) { long long a = getRandomNumber(2, n - 1); if (ModularArithmetic::gcd(a, n) > 1) return false; long long expr1 = ModularArithmetic::hornerPow(a, (n - 1) / 2, n); long long expr2 = ModularArithmetic::unsignedMod(symbols.jacobi(a, n), n); if (expr1 != expr2) return false; } return true; } //Solovay–Strassen primality test with hints bool PrimalityTest::solovayStrassenVerbose(long long n, int k) { if (n == 2) return true; if (n < 3) return false; if (n % 2 == 0) return false; for (int i = 0; i < k; i++) { long long a = getRandomNumber(2, n - 1); if (ModularArithmetic::gcd(a, n) > 1) { cout << "gcd(a, n) > 1." << endl; return false; } long long expr1 = ModularArithmetic::hornerPow(a, (n - 1) / 2, n); long long expr2 = ModularArithmetic::unsignedMod(symbols.jacobi(a, n), n); if (expr1 != expr2) { cout << "a^[(n - 1)/2] != J(a,n) (n n)." << endl; return false; } } cout << n << " is prime with accuracy (1-2^-k) = " << (1 - pow(2, -k)) << "." << endl << endl; return true; } //Fermat primality test without hints bool PrimalityTest::fermat(long long n, int k) { if (n < 2) return false; for (int i = 0; i < k; ++i) { long long a = getRandomNumber(1, n); while (ModularArithmetic::gcd(a, n) != 1) a = getRandomNumber(1, n); long long result = ModularArithmetic::hornerPow(a, n-1, n); if (result != 1) return false; } return true; } //Fermat primality test with hints bool PrimalityTest::fermatVerbose(long long int n, int k) { if (n < 2) return false; for (int i = 0; i < k; ++i) { long long a = getRandomNumber(1, n); while (ModularArithmetic::gcd(a, n) != 1) a = getRandomNumber(1, n); long long result = ModularArithmetic::hornerPow(a, n-1, n); if (result != 1) return false; } cout << n << " is prime with accuracy (1-2^-k) = " << (1 - pow(2, -k)) << ",\nbut don't forgive about Carmichael numbers." << endl << endl; return true; } //Lehmann`s primality test without hints bool PrimalityTest::lehmann(long long n, int k) { if (n < 2) return false; for (int i = 0; i < k; ++i) { long long a = getRandomNumber(1, n-1); long long result = ModularArithmetic::hornerPow(a, (n-1)/2, n); if (abs(result) != 1 && result != n-1) return false; } return true; } //Lehmann's primality test with hints bool PrimalityTest::lehmannVerbose(long long int n, int k) { if (n < 2) return false; for (int i = 0; i < k; ++i) { long long a = getRandomNumber(1, n-1); long long result = ModularArithmetic::hornerPow(a, (n-1)/2, n); if (abs(result) != 1 && result != n-1) return false; } cout << n << " is prime with accuracy (1-2^-k) = " << (1 - pow(2, -k)) << "." << endl << endl; return true; }
/* Find the distance in feet that the projectile travels Example Input, velocity and angle in degrees. 63.9 65 -1 Program Output: 97.2198 */ #include <string> #include <iostream> using namespace std; int main( int argc, char* argv[] ) { float velocity, angle, distance; cout << "Enter velocity, then angle." << endl; cin >> velocity; // while (velocity >=0) // { cin >> angle; distance = velocity*velocity * sin(2*(3.14159265)*angle/180) / 9.80665; cout << distance << endl; // cin >> velocity; // } }
#include "exchs.h" #include <cmath> const double ExchS::m_alpha = 2./3; const double ExchS::m_c = pow(3. / (4. * M_PI), 1./3.); // // Construktor // ExchS::ExchS(void) { } // // Destructor // ExchS::~ExchS(void) { } /// // Returns density of exchange energy per one electron // rhoa - electron density alpha // rhob - electron density beta // gaa - gamma_{\alpha \alpha} not used // gab - gamma_{\alpha \beta} not used // gbb - gamma_{\beta \beta} not used // double ExchS::E(double rhoa, double rhob, double /*gaa*/, double /*gab*/, double /*gbb*/) const { const double f = -(9./4.) * m_alpha * m_c; // return f * (pow(rhoa, 4./3.) + pow(rhob, 4./3.)) / (rhoa + rhob); return f * (pow(rhoa, 4./3.) + pow(rhob, 4./3.)); } // // Returns derivative of functional $\rho_{\alpha}$. // rhoa - electron density alpha // rhob - electron density beta not used // gaa - gamma_{\alpha \alpha}; not used // gab - gamma_{\alpha \beta}; not used // gbb - gamma_{\beta \beta}; not used // double ExchS::Vrhoa(double rhoa, double /*rhob*/, double /*gaa*/, double /*gab*/, double /*gbb*/) const { const double f = -3. * m_alpha * m_c; return f * pow(rhoa, 1./3.); } // // Returns derivative of functional $\rho_{\beta}$. // rhoa - electron density alpha not used // rhob - electron density beta // gaa - gamma_{\alpha \alpha}; not used // gab - gamma_{\alpha \beta}; not used // gbb - gamma_{\beta \beta}; not used // double ExchS::Vrhob(double /*rhoa*/, double rhob, double /*gaa*/, double /*gab*/, double /*gbb*/) const { const double f = -3. * m_alpha * m_c; return f * pow(rhob, 1./3.); } // // Returns derivative of functional $\gamma_{\alpha \alpha}$. // rhoa - electron density alpha not used // rhob - electron density beta not used // gaa - gamma_{\alpha \alpha}; not used // gab - gamma_{\alpha \beta}; not used // gbb - gamma_{\beta \beta}; not used // double ExchS::Vgaa(double /*rhoa*/, double /*rhob*/, double /*gaa*/, double /*gab*/, double /*gbb*/) const { return 0.; } // // Returns derivative of functional $\gamma_{\beta \beta}$. // rhoa - electron density alpha not used // rhob - electron density beta not used // gaa - gamma_{\alpha \alpha}; not used // gab - gamma_{\alpha \beta}; not used // gbb - gamma_{\beta \beta}; not used // double ExchS::Vgbb(double /*rhoa*/, double /*rhob*/, double /*gaa*/, double /*gab*/, double /*gbb*/) const { return 0.; } // // Returns derivative of functional $\gamma_{\alpha \beta}$. // rhoa - electron density alpha not used // rhob - electron density beta not used // gaa - gamma_{\alpha \alpha}; not used // gab - gamma_{\alpha \beta}; not used // gbb - gamma_{\beta \beta}; not used // double ExchS::Vgab(double /*rhoa*/, double /*rhob*/, double /*gaa*/, double /*gab*/, double /*gbb*/) const { return 0; }
// MRegKey.hpp -- Win32API registry key manipulator -*- C++ -*- // This file is part of MZC4. See file "ReadMe.txt" and "License.txt". //////////////////////////////////////////////////////////////////////////// #ifndef MZC4_MREGKEY_HPP_ #define MZC4_MREGKEY_HPP_ 8 /* Version 8 */ #ifndef HKCR #define HKCR HKEY_CLASSES_ROOT #define HKCU HKEY_CURRENT_USER #define HKLM HKEY_LOCAL_MACHINE #define HKU HKEY_USERS #define HKPD HKEY_PERFORMANCE_DATA #define HKCC HKEY_CURRENT_CONFIG #define HKDD HKEY_DYN_DATA #endif class MRegKey; //////////////////////////////////////////////////////////////////////////// #ifndef _INC_WINDOWS #include <windows.h> // Win32API #endif #include <cassert> // assert #include <new> // std::nothrow //////////////////////////////////////////////////////////////////////////// // NOTE: RegDeleteTreeDx deletes all value entries if pszSubKey == NULL. // NOTE: RegDeleteTreeDx cannot delete opening keys. LONG RegDeleteTreeDx(HKEY hKey, LPCTSTR pszSubKey/* = NULL*/); //////////////////////////////////////////////////////////////////////////// class MRegKey { public: MRegKey(); MRegKey(HKEY hKey); MRegKey(MRegKey& key); MRegKey(HKEY hBaseKey, LPCTSTR pszSubKey, BOOL bCreate = FALSE); virtual ~MRegKey(); operator HKEY() const; bool operator!() const; bool operator==(HKEY hKey) const; bool operator!=(HKEY hKey) const; MRegKey& operator=(HKEY hKey); MRegKey& operator=(MRegKey& key); BOOL Attach(HKEY hKey); HKEY Detach(); HKEY Handle() const; LONG RegCreateKeyEx(HKEY hBaseKey, LPCTSTR pszSubKey, DWORD dwReserved = 0, LPTSTR lpClass = NULL, DWORD dwOptions = 0, REGSAM samDesired = KEY_ALL_ACCESS, LPSECURITY_ATTRIBUTES lpsa = NULL, LPDWORD lpdwDisposition = NULL); LONG RegOpenKeyEx(HKEY hBaseKey, LPCTSTR pszSubKey, DWORD dwOptions = 0, REGSAM samDesired = KEY_READ); LONG RegConnectRegistry(LPCTSTR lpMachineName, HKEY hBaseKey); LONG RegCloseKey(); LONG RegQueryValueEx(LPCTSTR pszValueName = NULL, LPDWORD lpReserved = NULL, LPDWORD lpType = NULL, LPBYTE lpData = NULL, LPDWORD lpcbData = NULL); LONG QueryBinary(LPCTSTR pszValueName, LPVOID pvValue, DWORD cb); LONG QueryDword(LPCTSTR pszValueName, DWORD& dw); LONG QueryDwordLE(LPCTSTR pszValueName, DWORD& dw); LONG QueryDwordBE(LPCTSTR pszValueName, DWORD& dw); LONG QuerySz(LPCTSTR pszValueName, LPTSTR pszValue, DWORD cchValue); LONG QueryExpandSz(LPCTSTR pszValueName, LPTSTR pszValue, DWORD cchValue); LONG QueryMultiSz(LPCTSTR pszValueName, LPTSTR pszzValues, DWORD cchValues); template <typename T_CONTAINER> LONG QueryMultiSz(LPCTSTR pszValueName, T_CONTAINER& container); template <typename T_STRUCT> LONG QueryStruct(LPCTSTR pszValueName, T_STRUCT& data); template <typename T_STRING> LONG QuerySz(LPCTSTR pszValueName, T_STRING& strValue); template <typename T_STRING> LONG QueryExpandSz(LPCTSTR pszValueName, T_STRING& strValue); LONG RegSetValueEx(LPCTSTR pszValueName, DWORD dwReserved, DWORD dwType, CONST BYTE *lpData, DWORD cbData); LONG SetBinary(LPCTSTR pszValueName, LPCVOID pvValue, DWORD cb); LONG SetDword(LPCTSTR pszValueName, DWORD dw); LONG SetDwordLE(LPCTSTR pszValueName, DWORD dw); LONG SetDwordBE(LPCTSTR pszValueName, DWORD dw); LONG SetSz(LPCTSTR pszValueName, LPCTSTR pszValue, DWORD cchValue); LONG SetSz(LPCTSTR pszValueName, LPCTSTR pszValue); LONG SetExpandSz(LPCTSTR pszValueName, LPCTSTR pszValue, DWORD cchValue); LONG SetExpandSz(LPCTSTR pszValueName, LPCTSTR pszValue); LONG SetMultiSz(LPCTSTR pszValueName, LPCTSTR pszzValues); LONG SetMultiSz(LPCTSTR pszValueName, LPCTSTR pszzValues, DWORD cchValues); template <typename T_CONTAINER> LONG SetMultiSz(LPCTSTR pszValueName, const T_CONTAINER& container); template <typename T_STRUCT> LONG SetStruct(LPCTSTR pszValueName, const T_STRUCT& data); LONG RegDeleteValue(LPCTSTR pszValueName); LONG RegDeleteTreeDx(LPCTSTR pszSubKey); LONG RegEnumKeyEx(DWORD dwIndex, LPTSTR lpName, LPDWORD lpcchName, LPDWORD lpReserved = NULL, LPTSTR lpClass = NULL, LPDWORD lpcchClass = NULL, PFILETIME lpftLastWriteTime = NULL); LONG RegEnumValue(DWORD dwIndex, LPTSTR lpName, LPDWORD lpcchName, LPDWORD lpReserved = NULL, LPDWORD lpType = NULL, LPBYTE lpData = NULL, LPDWORD lpcbData = NULL); LONG RegFlushKey(); LONG RegGetKeySecurity(SECURITY_INFORMATION si, PSECURITY_DESCRIPTOR pSD, LPDWORD pcbSD); LONG RegNotifyChangeKeyValue(BOOL bWatchSubTree = TRUE, DWORD dwFilter = REG_LEGAL_CHANGE_FILTER, HANDLE hEvent = NULL, BOOL bAsyncronous = FALSE); LONG RegQueryInfoKey(LPTSTR lpClass = NULL, LPDWORD lpcchClass = NULL, LPDWORD lpReserved = NULL, LPDWORD lpcSubKeys = NULL, LPDWORD lpcchMaxSubKeyLen = NULL, LPDWORD lpcchMaxClassLen = NULL, LPDWORD lpcValues = NULL, LPDWORD lpcchMaxValueNameLen = NULL, LPDWORD lpcbMaxValueLen = NULL, LPDWORD lpcbSecurityDescriptor = NULL, PFILETIME lpftLastWriteTime = NULL); LONG RegQueryMultipleValues(PVALENT val_list, DWORD num_vals, LPTSTR lpValueBuf, LPDWORD lpdwTotsize); LONG RegSetKeySecurity(SECURITY_INFORMATION si, PSECURITY_DESCRIPTOR psd); static LONG RegLoadKey(HKEY hKey, LPCTSTR pszSubKey, LPCTSTR pszFile); static LONG RegUnLoadKey(HKEY hKey, LPCTSTR pszSubKey); static LONG RegSaveKey(HKEY hKey, LPCTSTR pszFile, LPSECURITY_ATTRIBUTES lpsa = NULL); static LONG RegRestoreKey(HKEY hKey, LPCTSTR pszFile, DWORD dwFlags); static LONG RegReplaceKey(HKEY hKey, LPCTSTR pszSubKey, LPCTSTR pszNewFile, LPCTSTR pszOldFile); static LONG RegDeleteTreeDx(HKEY hKey, LPCTSTR pszSubKey); static DWORD MultiSzSizeDx(LPCTSTR pszz); static HKEY CloneHandleDx(HKEY hKey); protected: HKEY m_hKey; }; //////////////////////////////////////////////////////////////////////////// template <typename T_STRUCT> inline LONG MRegKey::QueryStruct(LPCTSTR pszValueName, T_STRUCT& data) { assert(m_hKey); DWORD cbData = static_cast<DWORD>(sizeof(data)); LONG result = ::RegQueryValueEx(m_hKey, pszValueName, NULL, NULL, reinterpret_cast<LPBYTE>(&data), &cbData); if (result == ERROR_SUCCESS && cbData != sizeof(data)) result = ERROR_INVALID_DATA; return result; } template <typename T_STRUCT> inline LONG MRegKey::SetStruct(LPCTSTR pszValueName, const T_STRUCT& data) { assert(m_hKey); const DWORD cbData = static_cast<DWORD>(sizeof(data)); return ::RegSetValueEx(m_hKey, pszValueName, 0, REG_BINARY, reinterpret_cast<const BYTE *>(&data), cbData); } template <typename T_CONTAINER> LONG MRegKey::QueryMultiSz(LPCTSTR pszValueName, T_CONTAINER& container) { container.clear(); LONG result; #ifndef NDEBUG DWORD dwType; result = RegQueryValueEx(pszValueName, NULL, &dwType, NULL, NULL); assert(result == ERROR_SUCCESS); assert(dwType == REG_MULTI_SZ); #endif DWORD cbData; result = RegQueryValueEx(pszValueName, NULL, NULL, NULL, &cbData); if (result != ERROR_SUCCESS) return result; const DWORD cch = static_cast<DWORD>(cbData / sizeof(TCHAR) + 1); LPTSTR pszz = new(std::nothrow) TCHAR[cch]; if (pszz) { result = QueryMultiSz(pszValueName, pszz, cch); if (result == ERROR_SUCCESS) { for (LPTSTR pch = pszz; *pch; pch += lstrlen(pch) + 1) { #if (__cplusplus >= 201103L) container.emplace_back(pch); #else container.push_back(pch); #endif } } delete[] pszz; } else result = ERROR_OUTOFMEMORY; return result; } template <typename T_CONTAINER> inline LONG MRegKey::SetMultiSz( LPCTSTR pszValueName, const T_CONTAINER& container) { typename T_CONTAINER::value_type str; typename T_CONTAINER::const_iterator it, end; it = container.begin(); end = container.end(); if (it != end) { for (; it != end; ++it) { str += *it; str += TEXT('\0'); } } else { str += TEXT('\0'); } const DWORD cchValues = static_cast<DWORD>(str.size() + 1); return SetMultiSz(pszValueName, str.c_str(), cchValues); } template <typename T_STRING> LONG MRegKey::QuerySz(LPCTSTR pszValueName, T_STRING& strValue) { LONG result; strValue.clear(); #ifndef NDEBUG DWORD dwType; result = RegQueryValueEx(pszValueName, NULL, &dwType, NULL, NULL); assert(result == ERROR_SUCCESS); assert(dwType == REG_SZ); #endif DWORD cbData; result = RegQueryValueEx(pszValueName, NULL, NULL, NULL, &cbData); if (result != ERROR_SUCCESS) return result; LPTSTR psz = new(std::nothrow) TCHAR[cbData / sizeof(TCHAR) + 1]; assert(psz); if (psz) { result = RegQueryValueEx(pszValueName, NULL, NULL, reinterpret_cast<LPBYTE>(psz), &cbData); if (result != ERROR_SUCCESS) { strValue = psz; } delete[] psz; } return result; } template <typename T_STRING> LONG MRegKey::QueryExpandSz(LPCTSTR pszValueName, T_STRING& strValue) { LONG result; strValue.clear(); #ifndef NDEBUG DWORD dwType; result = RegQueryValueEx(pszValueName, NULL, &dwType, NULL, NULL); assert(result == ERROR_SUCCESS); assert(dwType == REG_EXPAND_SZ); #endif DWORD cbData; result = RegQueryValueEx(pszValueName, NULL, NULL, NULL, &cbData); if (result != ERROR_SUCCESS) return result; LPTSTR psz = new(std::nothrow) TCHAR[cbData / sizeof(TCHAR) + 1]; assert(psz); if (psz) { result = RegQueryValueEx(pszValueName, NULL, NULL, reinterpret_cast<LPBYTE>(psz), &cbData); if (result != ERROR_SUCCESS) { strValue = psz; } delete[] psz; } return result; } inline MRegKey::MRegKey() : m_hKey(NULL) { } inline MRegKey::MRegKey(HKEY hKey) : m_hKey(hKey) { } inline MRegKey::MRegKey( HKEY hBaseKey, LPCTSTR pszSubKey, BOOL bCreate/* = FALSE*/) : m_hKey(NULL) { if (bCreate) RegCreateKeyEx(hBaseKey, pszSubKey); else RegOpenKeyEx(hBaseKey, pszSubKey); } inline MRegKey::MRegKey(MRegKey& key) : m_hKey(CloneHandleDx(key)) { } inline /*virtual*/ MRegKey::~MRegKey() { RegCloseKey(); } inline HKEY MRegKey::Handle() const { return m_hKey; } inline MRegKey::operator HKEY() const { return Handle(); } inline bool MRegKey::operator!() const { return Handle() == NULL; } inline bool MRegKey::operator==(HKEY hKey) const { return Handle() == hKey; } inline bool MRegKey::operator!=(HKEY hKey) const { return Handle() != hKey; } inline MRegKey& MRegKey::operator=(HKEY hKey) { if (Handle() != hKey) { Attach(hKey); } return *this; } inline MRegKey& MRegKey::operator=(MRegKey& key) { if (Handle() != key.m_hKey) { HKEY hKey = CloneHandleDx(key); Attach(hKey); } return *this; } inline BOOL MRegKey::Attach(HKEY hKey) { RegCloseKey(); m_hKey = hKey; return m_hKey != NULL; } inline HKEY MRegKey::Detach() { HKEY hKey = m_hKey; m_hKey = NULL; return hKey; } inline LONG MRegKey::RegCreateKeyEx(HKEY hBaseKey, LPCTSTR pszSubKey, DWORD dwReserved/* = 0*/, LPTSTR lpClass/* = NULL*/, DWORD dwOptions/* = 0*/, REGSAM samDesired/* = KEY_ALL_ACCESS*/, LPSECURITY_ATTRIBUTES lpsa/* = NULL*/, LPDWORD lpdwDisposition/* = NULL*/) { assert(m_hKey == NULL); return ::RegCreateKeyEx(hBaseKey, pszSubKey, dwReserved, lpClass, dwOptions, samDesired, lpsa, &m_hKey, lpdwDisposition); } inline LONG MRegKey::RegOpenKeyEx(HKEY hBaseKey, LPCTSTR pszSubKey, DWORD dwOptions/* = 0*/, REGSAM samDesired/* = KEY_READ*/) { assert(m_hKey == NULL); return ::RegOpenKeyEx(hBaseKey, pszSubKey, dwOptions, samDesired, &m_hKey); } inline LONG MRegKey::RegConnectRegistry(LPCTSTR lpMachineName, HKEY hBaseKey) { assert(m_hKey == NULL); return ::RegConnectRegistry(lpMachineName, hBaseKey, &m_hKey); } inline LONG MRegKey::RegCloseKey() { if (Handle()) { LONG result = ::RegCloseKey(Detach()); return result; } return ERROR_INVALID_HANDLE; } inline LONG MRegKey::RegQueryValueEx(LPCTSTR pszValueName/* = NULL*/, LPDWORD lpReserved/* = NULL*/, LPDWORD lpType/* = NULL*/, LPBYTE lpData/* = NULL*/, LPDWORD lpcbData/* = NULL*/) { assert(m_hKey); return ::RegQueryValueEx(m_hKey, pszValueName, lpReserved, lpType, lpData, lpcbData); } inline LONG MRegKey::QueryBinary( LPCTSTR pszValueName, LPVOID pvValue, DWORD cb) { #ifndef NDEBUG DWORD dwType; LONG result = RegQueryValueEx(pszValueName, NULL, &dwType, NULL, NULL); assert(result == ERROR_SUCCESS); assert(dwType == REG_BINARY); #endif DWORD cbData = cb; return RegQueryValueEx(pszValueName, NULL, NULL, reinterpret_cast<LPBYTE>(pvValue), &cbData); } inline LONG MRegKey::QueryDword(LPCTSTR pszValueName, DWORD& dw) { #ifndef NDEBUG DWORD dwType; LONG result = RegQueryValueEx(pszValueName, NULL, &dwType, NULL, NULL); assert(result == ERROR_SUCCESS); assert(dwType == REG_DWORD); #endif DWORD cbData = sizeof(DWORD); return RegQueryValueEx(pszValueName, NULL, NULL, reinterpret_cast<LPBYTE>(&dw), &cbData); } inline LONG MRegKey::QueryDwordLE(LPCTSTR pszValueName, DWORD& dw) { #ifndef NDEBUG DWORD dwType; LONG result = RegQueryValueEx(pszValueName, NULL, &dwType, NULL, NULL); assert(result == ERROR_SUCCESS); assert(dwType == REG_DWORD_LITTLE_ENDIAN); #endif DWORD cbData = sizeof(DWORD); return RegQueryValueEx(pszValueName, NULL, NULL, reinterpret_cast<LPBYTE>(&dw), &cbData); } inline LONG MRegKey::QueryDwordBE(LPCTSTR pszValueName, DWORD& dw) { #ifndef NDEBUG DWORD dwType; LONG result = RegQueryValueEx(pszValueName, NULL, &dwType, NULL, NULL); assert(result == ERROR_SUCCESS); assert(dwType == REG_DWORD_BIG_ENDIAN); #endif DWORD cbData = sizeof(DWORD); return RegQueryValueEx(pszValueName, NULL, NULL, reinterpret_cast<LPBYTE>(&dw), &cbData); } inline LONG MRegKey::QuerySz(LPCTSTR pszValueName, LPTSTR pszValue, DWORD cchValue) { #ifndef NDEBUG DWORD dwType; LONG result = RegQueryValueEx(pszValueName, NULL, &dwType, NULL, NULL); assert(result == ERROR_SUCCESS); assert(dwType == REG_SZ); #endif DWORD cbData = cchValue * sizeof(TCHAR); return RegQueryValueEx(pszValueName, NULL, NULL, reinterpret_cast<LPBYTE>(pszValue), &cbData); } inline LONG MRegKey::QueryExpandSz( LPCTSTR pszValueName, LPTSTR pszValue, DWORD cchValue) { #ifndef NDEBUG DWORD dwType; LONG result = RegQueryValueEx(pszValueName, NULL, &dwType, NULL, NULL); assert(result == ERROR_SUCCESS); assert(dwType == REG_EXPAND_SZ); #endif DWORD cbData = cchValue * sizeof(TCHAR); return RegQueryValueEx(pszValueName, NULL, NULL, reinterpret_cast<LPBYTE>(pszValue), &cbData); } inline LONG MRegKey::QueryMultiSz( LPCTSTR pszValueName, LPTSTR pszzValues, DWORD cchValues) { #ifndef NDEBUG DWORD dwType; LONG result = RegQueryValueEx(pszValueName, NULL, &dwType, NULL, NULL); assert(result == ERROR_SUCCESS); assert(dwType == REG_MULTI_SZ); #endif DWORD cbData = sizeof(TCHAR) * cchValues; return RegQueryValueEx(pszValueName, NULL, NULL, reinterpret_cast<LPBYTE>(pszzValues), &cbData); } inline LONG MRegKey::RegSetValueEx(LPCTSTR pszValueName, DWORD dwReserved, DWORD dwType, CONST BYTE *lpData, DWORD cbData) { assert(m_hKey); return ::RegSetValueEx(m_hKey, pszValueName, dwReserved, dwType, lpData, cbData); } inline LONG MRegKey::SetBinary(LPCTSTR pszValueName, LPCVOID pvValue, DWORD cb) { return RegSetValueEx(pszValueName, 0, REG_BINARY, reinterpret_cast<const BYTE *>(pvValue), cb); } inline LONG MRegKey::SetDword(LPCTSTR pszValueName, DWORD dw) { DWORD dwValue = dw; return RegSetValueEx(pszValueName, 0, REG_DWORD, reinterpret_cast<const BYTE *>(&dwValue), sizeof(DWORD)); } inline LONG MRegKey::SetDwordLE(LPCTSTR pszValueName, DWORD dw) { DWORD dwValue = dw; return RegSetValueEx(pszValueName, 0, REG_DWORD_LITTLE_ENDIAN, reinterpret_cast<const BYTE *>(&dwValue), sizeof(DWORD)); } inline LONG MRegKey::SetDwordBE(LPCTSTR pszValueName, DWORD dw) { DWORD dwValue = dw; return RegSetValueEx(pszValueName, 0, REG_DWORD_BIG_ENDIAN, reinterpret_cast<const BYTE *>(&dwValue), sizeof(DWORD)); } inline LONG MRegKey::SetSz(LPCTSTR pszValueName, LPCTSTR pszValue, DWORD cchValue) { return RegSetValueEx(pszValueName, 0, REG_SZ, reinterpret_cast<const BYTE *>(pszValue), cchValue * sizeof(TCHAR)); } inline LONG MRegKey::SetExpandSz(LPCTSTR pszValueName, LPCTSTR pszValue, DWORD cchValue) { return RegSetValueEx(pszValueName, 0, REG_EXPAND_SZ, reinterpret_cast<const BYTE *>(pszValue), cchValue * sizeof(TCHAR)); } inline LONG MRegKey::SetMultiSz(LPCTSTR pszValueName, LPCTSTR pszzValues) { return RegSetValueEx(pszValueName, 0, REG_MULTI_SZ, reinterpret_cast<const BYTE *>(pszzValues), MRegKey::MultiSzSizeDx(pszzValues)); } inline LONG MRegKey::SetMultiSz(LPCTSTR pszValueName, LPCTSTR pszzValues, DWORD cchValues) { DWORD cb = static_cast<DWORD>(sizeof(TCHAR) * cchValues); return RegSetValueEx(pszValueName, 0, REG_MULTI_SZ, reinterpret_cast<const BYTE *>(pszzValues), cb); } inline LONG MRegKey::RegDeleteValue(LPCTSTR pszValueName) { assert(m_hKey); return ::RegDeleteValue(m_hKey, pszValueName); } inline LONG MRegKey::RegEnumKeyEx(DWORD dwIndex, LPTSTR lpName, LPDWORD lpcchName, LPDWORD lpReserved/* = NULL*/, LPTSTR lpClass/* = NULL*/, LPDWORD lpcchClass/* = NULL*/, PFILETIME lpftLastWriteTime/* = NULL*/) { assert(m_hKey); return ::RegEnumKeyEx(m_hKey, dwIndex, lpName, lpcchName, lpReserved, lpClass, lpcchClass, lpftLastWriteTime); } inline LONG MRegKey::RegEnumValue(DWORD dwIndex, LPTSTR lpName, LPDWORD lpcchName, LPDWORD lpReserved/* = NULL*/, LPDWORD lpType/* = NULL*/, LPBYTE lpData/* = NULL*/, LPDWORD lpcbData/* = NULL*/) { assert(m_hKey); return ::RegEnumValue(m_hKey, dwIndex, lpName, lpcchName, lpReserved, lpType, lpData, lpcbData); } inline LONG MRegKey::RegFlushKey() { assert(m_hKey); return ::RegFlushKey(m_hKey); } inline LONG MRegKey::RegGetKeySecurity(SECURITY_INFORMATION si, PSECURITY_DESCRIPTOR pSD, LPDWORD pcbSD) { assert(m_hKey); return ::RegGetKeySecurity(m_hKey, si, pSD, pcbSD); } inline LONG MRegKey::RegNotifyChangeKeyValue(BOOL bWatchSubTree/* = TRUE*/, DWORD dwFilter/* = REG_LEGAL_CHANGE_FILTER*/, HANDLE hEvent/* = NULL*/, BOOL bAsyncronous/* = FALSE*/) { assert(m_hKey); return ::RegNotifyChangeKeyValue(m_hKey, bWatchSubTree, dwFilter, hEvent, bAsyncronous); } inline LONG MRegKey::RegQueryInfoKey(LPTSTR lpClass/* = NULL*/, LPDWORD lpcchClass/* = NULL*/, LPDWORD lpReserved/* = NULL*/, LPDWORD lpcSubKeys/* = NULL*/, LPDWORD lpcchMaxSubKeyLen/* = NULL*/, LPDWORD lpcchMaxClassLen/* = NULL*/, LPDWORD lpcValues/* = NULL*/, LPDWORD lpcchMaxValueNameLen/* = NULL*/, LPDWORD lpcbMaxValueLen/* = NULL*/, LPDWORD lpcbSecurityDescriptor/* = NULL*/, PFILETIME lpftLastWriteTime/* = NULL*/) { assert(m_hKey); return ::RegQueryInfoKey(m_hKey, lpClass, lpcchClass, lpReserved, lpcSubKeys, lpcchMaxSubKeyLen, lpcchMaxClassLen, lpcValues, lpcchMaxValueNameLen, lpcbMaxValueLen, lpcbSecurityDescriptor, lpftLastWriteTime); } inline LONG MRegKey::RegQueryMultipleValues(PVALENT val_list, DWORD num_vals, LPTSTR lpValueBuf, LPDWORD lpdwTotsize) { assert(m_hKey); return ::RegQueryMultipleValues( m_hKey, val_list, num_vals, lpValueBuf, lpdwTotsize); } inline LONG MRegKey::RegSetKeySecurity(SECURITY_INFORMATION si, PSECURITY_DESCRIPTOR psd) { assert(m_hKey); return ::RegSetKeySecurity(m_hKey, si, psd); } inline /*static*/ LONG MRegKey::RegLoadKey(HKEY hKey, LPCTSTR pszSubKey, LPCTSTR pszFile) { assert(pszSubKey); assert(pszFile); return ::RegLoadKey(hKey, pszSubKey, pszFile); } inline /*static*/ LONG MRegKey::RegUnLoadKey(HKEY hKey, LPCTSTR pszSubKey) { assert(pszSubKey); return ::RegUnLoadKey(hKey, pszSubKey); } inline /*static*/ LONG MRegKey::RegSaveKey(HKEY hKey, LPCTSTR pszFile, LPSECURITY_ATTRIBUTES lpsa/* = NULL*/) { assert(pszFile); return ::RegSaveKey(hKey, pszFile, lpsa); } inline /*static*/ LONG MRegKey::RegRestoreKey(HKEY hKey, LPCTSTR pszFile, DWORD dwFlags) { assert(pszFile); return ::RegRestoreKey(hKey, pszFile, dwFlags); } inline /*static*/ LONG MRegKey::RegReplaceKey( HKEY hKey, LPCTSTR pszSubKey, LPCTSTR pszNewFile, LPCTSTR pszOldFile) { assert(pszNewFile); assert(pszOldFile); return ::RegReplaceKey(hKey, pszSubKey, pszNewFile, pszOldFile); } inline /*static*/ LONG MRegKey::RegDeleteTreeDx(HKEY hKey, LPCTSTR pszSubKey) { return ::RegDeleteTreeDx(hKey, pszSubKey); } inline LONG MRegKey::SetSz(LPCTSTR pszValueName, LPCTSTR pszValue) { return SetSz(pszValueName, pszValue, lstrlen(pszValue) + 1); } inline LONG MRegKey::SetExpandSz(LPCTSTR pszValueName, LPCTSTR pszValue) { return SetExpandSz(pszValueName, pszValue, lstrlen(pszValue) + 1); } inline LONG MRegKey::RegDeleteTreeDx(LPCTSTR pszSubKey) { assert(m_hKey); return RegDeleteTreeDx(m_hKey, pszSubKey); } inline LONG RegDeleteTreeDx(HKEY hKey, LPCTSTR pszSubKey/* = NULL*/) { LONG ret; DWORD cchSubKeyMax, cchValueMax; DWORD cchMax, cch; TCHAR szNameBuf[MAX_PATH], *pszName = szNameBuf; HKEY hSubKey = hKey; if (pszSubKey != NULL) { ret = ::RegOpenKeyEx(hKey, pszSubKey, 0, KEY_READ, &hSubKey); if (ret) return ret; } ret = ::RegQueryInfoKey(hSubKey, NULL, NULL, NULL, NULL, &cchSubKeyMax, NULL, NULL, &cchValueMax, NULL, NULL, NULL); if (ret) goto cleanup; cchSubKeyMax++; cchValueMax++; if (cchSubKeyMax < cchValueMax) cchMax = cchValueMax; else cchMax = cchSubKeyMax; if (cchMax > sizeof(szNameBuf) / sizeof(TCHAR)) { pszName = new(std::nothrow) TCHAR[cchMax * sizeof(TCHAR)]; if (pszName == NULL) goto cleanup; } for(;;) { cch = cchMax; if (::RegEnumKeyEx(hSubKey, 0, pszName, &cch, NULL, NULL, NULL, NULL)) { break; } ret = RegDeleteTreeDx(hSubKey, pszName); if (ret) goto cleanup; } if (pszSubKey != NULL) { ret = ::RegDeleteKey(hKey, pszSubKey); } else { // NOTE: if pszSubKey was NULL, then delete value entries. for (;;) { cch = cchMax; if (::RegEnumValue(hKey, 0, pszName, &cch, NULL, NULL, NULL, NULL)) { break; } ret = ::RegDeleteValue(hKey, pszName); if (ret) goto cleanup; } } cleanup: if (pszSubKey != NULL) ::RegCloseKey(hSubKey); if (pszName != szNameBuf) delete[] pszName; return ret; } inline /*static*/ DWORD MRegKey::MultiSzSizeDx(LPCTSTR pszz) { DWORD siz = 0; if (*pszz) { do { INT len = lstrlen(pszz); siz += len + 1; pszz += len + 1; } while (*pszz); } else { ++siz; } ++siz; siz *= static_cast<DWORD>(sizeof(TCHAR)); return siz; } inline /*static*/ HKEY MRegKey::CloneHandleDx(HKEY hKey) { if (hKey == NULL) return NULL; HANDLE hProcess = ::GetCurrentProcess(); HANDLE hDup = NULL; ::DuplicateHandle(hProcess, hKey, hProcess, &hDup, 0, FALSE, DUPLICATE_SAME_ACCESS); return reinterpret_cast<HKEY>(hDup); } //////////////////////////////////////////////////////////////////////////// #endif // ndef MZC4_MREGKEY_HPP_
// Copyright (c) 2014 Antony Arciuolo. See License.txt regarding use. #include <oBase/concurrent_registry.h> #include <oBase/assert.h> #include <oBase/macros.h> #include <oMemory/byte.h> namespace ouro { namespace state { enum value { invalid = 0, failed, making, made, unmaking, unmaking_to_failed };} concurrent_registry::concurrent_registry() : entries(nullptr) , missing(nullptr) , failed(nullptr) , making(nullptr) , owns_memory(false) {} concurrent_registry::concurrent_registry(concurrent_registry&& _That) : entries(_That.entries) , missing(_That.missing) , failed(_That.failed) , making(_That.making) , owns_memory(_That.owns_memory) { _That.entries = nullptr; _That.missing = nullptr; _That.failed = nullptr; _That.making = nullptr; _That.owns_memory = false; pool = std::move(_That.pool); lookup = std::move(_That.lookup); makes = std::move(_That.makes); unmakes = std::move(_That.unmakes); lifetime = std::move(_That.lifetime); } concurrent_registry::concurrent_registry(void* memory, size_type capacity , const lifetime_t& lifetime , placeholder_source_t& placeholder_source) { if (!initialize(memory, capacity, lifetime, placeholder_source)) throw std::invalid_argument("concurrent_registry initialize failed"); } concurrent_registry::concurrent_registry(size_type capacity, const lifetime_t& lifetime, placeholder_source_t& placeholder_source) { if (!initialize(capacity, lifetime, placeholder_source)) throw std::invalid_argument("concurrent_registry initialize failed"); } concurrent_registry::~concurrent_registry() { deinitialize(); } concurrent_registry& concurrent_registry::operator=(concurrent_registry&& _That) { if (this != &_That) { pool = std::move(_That.pool); lookup = std::move(_That.lookup); makes = std::move(_That.makes); unmakes = std::move(_That.unmakes); lifetime = std::move(_That.lifetime); oMOVE0(entries); oMOVE0(missing); oMOVE0(failed); oMOVE0(making); oMOVE0(owns_memory); } return *this; } concurrent_registry::size_type concurrent_registry::initialize(void* memory, size_type capacity, const lifetime_t& lifetime, placeholder_source_t& placeholder_source) { const size_type pool_req = byte_align(pool.calc_size(capacity), oDEFAULT_MEMORY_ALIGNMENT); const size_type lookup_req = byte_align(lookup.calc_size(capacity), oDEFAULT_MEMORY_ALIGNMENT); const size_type entries_req = capacity * sizeof(void*); if (!pool_req || !lookup_req) return 0; const size_type total_req = pool_req + lookup_req + entries_req; if (memory) { // if so, pool is already initialized void* p = byte_add(memory, pool_req); lookup.initialize(p, capacity); p = byte_add(p, lookup_req); entries = (void**)p; this->lifetime = lifetime; missing = lifetime.create(placeholder_source.compiled_missing, "missing_placeholder"); failed = lifetime.create(placeholder_source.compiled_failed, "failed_placeholder"); making = lifetime.create(placeholder_source.compiled_making, "making_placeholder"); for (index_type i = 0; i < capacity; i++) entries[i] = missing; } return total_req; } concurrent_registry::size_type concurrent_registry::initialize(size_type capacity, const lifetime_t& lifetime, placeholder_source_t& placeholder_source) { size_type req = initialize(nullptr, capacity, lifetime, placeholder_source); void* memory = default_allocate(req, 0); owns_memory = true; return initialize(memory, capacity, lifetime, placeholder_source); } void* concurrent_registry::deinitialize() { void* p = nullptr; if (entries) { if (!makes.empty() || !unmakes.empty()) throw std::exception("concurrent_registry should have been flushed before destruction"); unmake_all(); if (missing) { lifetime.destroy(missing); missing = nullptr; } if (failed) { lifetime.destroy(failed); failed = nullptr; } if (making) { lifetime.destroy(making); making = nullptr; } memset(entries, 0, sizeof(void*) * pool.capacity()); entries = nullptr; lifetime = lifetime_t(); lookup.deinitialize(); p = pool.deinitialize(); if (owns_memory) { default_deallocate(p); owns_memory = false; p = nullptr; } } return p; } void concurrent_registry::unmake_all() { size_type remaining = flush(~0u); if (remaining) throw std::exception("did not flush all outstanding items"); const size_type n = capacity(); for (size_type i = 0; i < n; i++) { void** e = entries + i; if (*e && *e != missing && *e != failed && *e != making) { lifetime.destroy(*e); auto f = pool.typed_pointer(i); *e = f->state == state::unmaking ? missing : failed; pool.destroy(f); } } } concurrent_registry::size_type concurrent_registry::flush(size_type max_operations) { size_type n = max_operations; file_info* f = nullptr; while (n && unmakes.pop(&f)) { // a call to make saved this asset if (f->state != state::unmaking && f->state != state::unmaking_to_failed) continue; index_type index = pool.index(f); void** e = entries + index; lifetime.destroy(*e); *e = f->state == state::unmaking ? missing : failed; pool.destroy(f); n--; } size_type EstHashesToReclaim = max_operations - n; while (n && makes.pop(&f)) { index_type index = pool.index(f); void** e = entries + index; // free any prior asset (should this count as an operation n--?) if (*e && *e != missing && *e != failed && *e != making) lifetime.destroy(*e); if (!f->compiled) { *e = failed; f->state.store(state::failed); } else { try { *e = lifetime.create(std::ref(f->compiled), f->name); f->state.store(state::made); } catch (std::exception& ex) { *e = failed; f->state.store(state::failed); oTRACEA("failed: %s", ex.what()); } n--; } } if (EstHashesToReclaim <= n) lookup.reclaim(); return makes.size() + unmakes.size(); } concurrent_registry::hash_type concurrent_registry::hash(const char* name) { return fnv1a<hash_type>(name); } concurrent_registry::entry_type concurrent_registry::get(hash_type key) const { auto index = lookup.get(key); return index == lookup.nullidx ? &missing : entries + index; } const char* concurrent_registry::name(entry_type entry) const { if (!in_range(entry, entries, byte_add(entry, pool.capacity()))) return ""; index_type index = (index_type)index_of(entry, entries); auto f = pool.typed_pointer(index); return f->state.load() == state::invalid ? "" : f->name; } concurrent_registry::entry_type concurrent_registry::make(hash_type key, const char* name, scoped_allocation& compiled, const path& path, bool force) { // Truth Table // n/c n/c/f n n/f // <no entry> ins/q/making ins/q/making ins/err ins/err // failed q/making q/making noop noop // making noop noop noop noop // made noop q/making noop q/unm_to_err // unmaking made q/making q/unm_to_err q/unm_to_err // unm_to_err q/making q/making noop noop void** e = nullptr; index_type index = lookup.get(key); file_info* f = nullptr; if (index != lookup.nullidx) { e = entries + index; f = pool.typed_pointer(index); int old = f->state; // handle noop cases if (old == state::making || (old == state::made && !force) || ((old == state::failed || old == state::unmaking_to_failed) && !compiled)) return e; bool HasCompiled = !!compiled; // try to take this to making old = f->state.exchange(HasCompiled ? state::making : state::failed); if (old == state::making) // let the other one do the making return e; if (!HasCompiled && (force || old == state::unmaking)) { f->state.store(state::unmaking_to_failed); unmakes.push(f); } // anything else is some sort of making which is flagged oASSERT(force || old != state::made, "unexpected state"); if (old == state::unmaking && !force) f->state.store(state::made); else { f->compiled = std::move(compiled); makes.push(f); } } else { void* placeholder = !!compiled ? making : failed; // initialize a new entry f = pool.create(); if (f) { f->state = !compiled ? state::failed : state::making; f->name = name; f->path = path; f->compiled = std::move(compiled); index = (index_type)pool.index(f); } else return &missing; // oom asset? e = entries + index; // another thread is trying to do this same thing, so let it if (lookup.nullidx != lookup.set(key, index)) pool.destroy(f); else if (f->state == state::failed) *e = failed; } makes.push(f); return e; } bool concurrent_registry::unmake(entry_type entry) { // Truth Table // entry // <no entry> retf // failed q/unmaking // making q/unmaking // made q/unmaking // unmaking noop // unm_to_err unmaking if (!in_range(entry, entries, pool.capacity())) return false; index_type index = (index_type)index_of(entry, entries); auto f = pool.typed_pointer(index); int old = f->state.exchange(state::unmaking); if (old == state::failed || old == state::making || old == state::made) unmakes.push(f); return true; } }
// boost/chrono/stopwatches/collectors/last_lap.hpp // Copyright 2011 Vicente J. Botet Escriba // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or // copy at http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org/libs/chrono/stopwatches for documentation. #ifndef BOOST_CHRONO_STOPWATCHES_MEMORIES_LAST_LAP_HPP #define BOOST_CHRONO_STOPWATCHES_MEMORIES_LAST_LAP_HPP namespace boost { namespace chrono { template<typename Duration> struct last_lap { typedef Duration duration; duration last_; void store(duration const& d) { last_ = d; } void reset() { last_ = duration::zero(); } duration last() const { return last_; } duration elapsed() const { return duration::zero(); } }; } // namespace chrono } // namespace boost #endif
//////////////////////////////////////////////////////////////////////////////// //3456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 // // lowfat - an "engine" for natural document viewing for free desktop-systems // // copyright (c) 2007 Mirco Müller // // lowfat is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // lowfat is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Foobar; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // //////////////////////////////////////////////////////////////////////////////// #include <algorithm> #include <list> #include <stdexcept> #include "SDL.h" #include "include/lfdisplay.h" #include "include/image.h" #include "include/key.h" #include "include/lfwindow.h" #include "include/photo_observer.h" using std::list; static const float gap (16); static const float maximal (8); LfWindow::LfWindow () : lastX_ (0), lastY_ (0) { } void LfWindow::addImage (ImagePtr image) { images_.push_back (image); } void LfWindow::toFront (ImagePtr image) { removeImage (image); addImage (image); } void LfWindow::removeImage (ImagePtr image) { ImageSeq::iterator it (std::find (images_.begin (), images_.end(), image)); if (it == images_.end ()) throw std::runtime_error ("missing image"); images_.erase (it); } ImagePtr LfWindow::getImage (int x, int y) { ImageSeq::reverse_iterator it; for (it = images_.rbegin (); it != images_.rend (); it++) { ImagePtr image = *it; if (image->isInside (x, y)) return image; } return ImagePtr (0); } LfWindow::~LfWindow () { } void LfWindow::sort (SortMode mode, std::list<ImagePtr>& selection) { const float border (3 * gap + maximal); sort (mode, Vec2f (border, border), getSize() - Vec2f (border, border), selection); } void LfWindow::sort (SortMode mode, const Vec2f& topLeft, const Vec2f& bottomRight, std::list<ImagePtr>& selection) { ImageSeq copyOfImgs (images_); if (selection.size () > 0) { copyOfImgs.clear (); for (std::list<ImagePtr>::iterator it = selection.begin(); it != selection.end(); it++) copyOfImgs.push_back (*it); } realSort (copyOfImgs, mode); float curSize (1000); float deltaSize (curSize); const float maxIteration (10); float bestSizeSoFar(0); for (int iteration (0); iteration < maxIteration; ++iteration) { if (sort(copyOfImgs, curSize, topLeft, bottomRight)) { if (curSize > bestSizeSoFar) bestSizeSoFar = curSize; curSize += deltaSize; } else curSize -= deltaSize; deltaSize /= 2; } sort (copyOfImgs, bestSizeSoFar, topLeft, bottomRight); } bool sortByName (const ImagePtr& a, const ImagePtr& b) { return a->getFilename () < b->getFilename (); } static float aspectRatio (const ImagePtr& a) { return a->getWidth () / a->getHeight (); } bool sortByAspectRatio (const ImagePtr& a, const ImagePtr& b) { return aspectRatio (a) < aspectRatio (b); } bool sortByDate (const ImagePtr& a, const ImagePtr& b) { return a->getDate () < b->getDate (); } void LfWindow::realSort (ImageSeq& images, SortMode mode) { switch (mode) { case nameSortMode: std::sort (images.begin (), images.end (), sortByName); break; case aspectRatioSortMode: std::sort (images.begin (), images.end (), sortByAspectRatio); break; case dateSortMode: std::sort (images.begin (), images.end (), sortByDate); break; default: throw std::runtime_error ("not implemented yet"); break; }; } // returns true, if all images fit in window bool LfWindow::sort (ImageSeq& images, const float maxSize, const Vec2f& topLeft, const Vec2f& bottomRight) { const float hGap (8); const float vGap (hGap); const float maxW (bottomRight.x); const float maxH (bottomRight.y); ImageSeq::iterator it; const float leftBorder (topLeft.x + hGap); const float topBorder (topLeft.y + vGap); Vec2f pos (leftBorder, topBorder); ImageSeq::iterator firstInRow (images.begin ()); float maxSizeSoFar (0); typedef list<ImagePtr> ImageSeq; for (it = images.begin (); it != images.end (); ++it) { ImagePtr img (*it); Vec2f defaultSize (img->getTexture()->getWidth (), img->getTexture()->getHeight ()); const float aspect (defaultSize.x / defaultSize.y); Vec2f size (aspect * maxSize, maxSize); if (pos.x + size.x + hGap > maxW) { pos.x = leftBorder; pos.y += vGap + maxSize; } if (size.y > maxSizeSoFar) maxSizeSoFar = size.y; const float dy (maxSize - size.y); Vec2f trans (pos + Vec2f (0, dy) / 2 + size / 2); img->setTransition (trans, size, 0); pos.x += size.x + hGap; if ((trans.y + size.y) > maxH) return false; } return true; } LfWindowPtr LfWindow::make() { return LfWindowPtr (new LfWindow ()); } void LfWindow::wobbleTrashcan () { trashcan_->wobble (); trashcanFront_->wobble (); } void LfWindow::paint (LfDisplay& display) { trashcan_->paint (display); for (ImageSeq::iterator it(images_.begin ()); it != images_.end (); ++it) if (!(*it)->getStatus () == Image::normalStatus) (*it)->paint (display); for (ImageSeq::iterator it (images_.begin ()); it != images_.end ();) { if ((*it)->getStatus() == Image::deleteMeStatus) { images_.erase(it); it = images_.begin(); wobbleTrashcan(); } else ++it; } trashcanFront_->paint (display); for (ImageSeq::iterator it(images_.begin ()); it != images_.end (); ++it) if ((*it)->getStatus () == Image::normalStatus) (*it)->paint (display); } std::list<ImagePtr> LfWindow::getImages (Vec2f topLeft, Vec2f bottomRight, int intersection) const { std::list<ImagePtr> list; for (ImageSeq::const_iterator it(images_.begin ()); it != images_.end(); ++it) if ((*it)->intersectBox (topLeft, bottomRight ) >= intersection) list.push_back ((*it)); return list; } void LfWindow::setImages (const ImageList& list) { images_.clear (); for (ImageList::const_iterator it (list.begin ()); it != list.end(); ++it) images_.push_back (*it); } LfWindow::ImageList LfWindow::getImages () const { ImageList list; for (ImageSeq::const_iterator it (images_.begin ()); it != images_.end(); ++it) list.push_back (*it); return list; } void LfWindow::advance (unsigned int t) { for (ImageSeq::iterator it(images_.begin ()); it != images_.end(); ++it) { ImagePtr image (*it); image->advance (t); } }
#pragma once template <typename T> class CopyCol{ private: public: CopyCol(){} ~CopyCol(){} class sstd::mat_c<T>* pMxs; uint CopyColNum; class CopyCol<T> operator=(class CopyCol<T> CC); }; template <typename T> inline class CopyCol<T> CopyCol<T>::operator=(class CopyCol<T> CC) { for(uint p=0; p<this->pMxs->rows(); p++){ (*(this->pMxs))(p, this->CopyColNum) = (*(CC.pMxs))(p, CC.CopyColNum); } return *this; } // 列のコピー, 例: MatB(':', 1) = MatB(':', 0) = MatA(':', 0); template <typename T> inline class CopyCol<T> OpCopyCol(sstd::mat_c<T>* pthis, const char& c_dummy, uint q) { class CopyCol<T> CC; CC.pMxs = pthis; CC.CopyColNum = q; return CC; }
// Copyright (c) 2005-2014 Code Synthesis Tools CC // // This program was generated by CodeSynthesis XSD, an XML Schema to // C++ data binding compiler. // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 as // published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // // In addition, as a special exception, Code Synthesis Tools CC gives // permission to link this program with the Xerces-C++ library (or with // modified versions of Xerces-C++ that use the same license as Xerces-C++), // and distribute linked combinations including the two. You must obey // the GNU General Public License version 2 in all respects for all of // the code used other than Xerces-C++. If you modify this copy of the // program, you may extend this exception to your version of the program, // but you are not obligated to do so. If you do not wish to do so, delete // this exception statement from your version. // // Furthermore, Code Synthesis Tools CC makes a special exception for // the Free/Libre and Open Source Software (FLOSS) which is described // in the accompanying FLOSSE file. // // Begin prologue. // // // End prologue. #include <xsd/cxx/pre.hxx> #include "SimAppObjNameDefault_SpatialZone_CeilingPlenumZone.hxx" namespace schema { namespace simxml { namespace ResourcesGeneral { // SimAppObjNameDefault_SpatialZone_CeilingPlenumZone // } } } #include <xsd/cxx/xml/dom/parsing-source.hxx> #include <xsd/cxx/tree/type-factory-map.hxx> namespace _xsd { static const ::xsd::cxx::tree::type_factory_plate< 0, char > type_factory_plate_init; } namespace schema { namespace simxml { namespace ResourcesGeneral { // SimAppObjNameDefault_SpatialZone_CeilingPlenumZone // SimAppObjNameDefault_SpatialZone_CeilingPlenumZone:: SimAppObjNameDefault_SpatialZone_CeilingPlenumZone () : ::schema::simxml::ResourcesGeneral::SimAppObjNameDefault_SpatialZone () { } SimAppObjNameDefault_SpatialZone_CeilingPlenumZone:: SimAppObjNameDefault_SpatialZone_CeilingPlenumZone (const RefId_type& RefId) : ::schema::simxml::ResourcesGeneral::SimAppObjNameDefault_SpatialZone (RefId) { } SimAppObjNameDefault_SpatialZone_CeilingPlenumZone:: SimAppObjNameDefault_SpatialZone_CeilingPlenumZone (const SimAppObjNameDefault_SpatialZone_CeilingPlenumZone& x, ::xml_schema::flags f, ::xml_schema::container* c) : ::schema::simxml::ResourcesGeneral::SimAppObjNameDefault_SpatialZone (x, f, c) { } SimAppObjNameDefault_SpatialZone_CeilingPlenumZone:: SimAppObjNameDefault_SpatialZone_CeilingPlenumZone (const ::xercesc::DOMElement& e, ::xml_schema::flags f, ::xml_schema::container* c) : ::schema::simxml::ResourcesGeneral::SimAppObjNameDefault_SpatialZone (e, f, c) { } SimAppObjNameDefault_SpatialZone_CeilingPlenumZone* SimAppObjNameDefault_SpatialZone_CeilingPlenumZone:: _clone (::xml_schema::flags f, ::xml_schema::container* c) const { return new class SimAppObjNameDefault_SpatialZone_CeilingPlenumZone (*this, f, c); } SimAppObjNameDefault_SpatialZone_CeilingPlenumZone:: ~SimAppObjNameDefault_SpatialZone_CeilingPlenumZone () { } } } } #include <istream> #include <xsd/cxx/xml/sax/std-input-source.hxx> #include <xsd/cxx/tree/error-handler.hxx> namespace schema { namespace simxml { namespace ResourcesGeneral { } } } #include <xsd/cxx/post.hxx> // Begin epilogue. // // // End epilogue.
// for vasprintf() on Linux #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #define _DEFAULT_SOURCE #include <dirent.h> #include <sys/stat.h> #include <sys/types.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sqlite3.h> #include <limits.h> #include <getopt.h> #include <vector> #include <string> #include <map> #include <set> #include <zlib.h> #include <math.h> #include <pthread.h> #include "mvt.hpp" #include "projection.hpp" #include "pool.hpp" #include "mbtiles.hpp" #include "geometry.hpp" #include "dirtiles.hpp" #include "evaluator.hpp" #include "csv.hpp" #include <fstream> #include <sstream> #include <algorithm> #include <functional> #include "jsonpull/jsonpull.h" #include "milo/dtoa_milo.h" int pk = false; int pC = false; int pg = false; int pe = false; size_t CPUS; int quiet = false; int maxzoom = 32; int minzoom = 0; std::map<std::string, std::string> renames; bool exclude_all = false; struct stats { int minzoom; int maxzoom; double midlat, midlon; double minlat, minlon, maxlat, maxlon; }; void aprintf(std::string *buf, const char *format, ...) { va_list ap; char *tmp; va_start(ap, format); if (vasprintf(&tmp, format, ap) < 0) { fprintf(stderr, "memory allocation failure\n"); exit(EXIT_FAILURE); } va_end(ap); buf->append(tmp, strlen(tmp)); free(tmp); } void handle(std::string message, int z, unsigned x, unsigned y, std::map<std::string, layermap_entry> &layermap, std::vector<std::string> &header, std::map<std::string, std::vector<std::string>> &mapping, std::set<std::string> &exclude, std::set<std::string> &keep_layers, std::set<std::string> &remove_layers, int ifmatched, mvt_tile &outtile, json_object *filter) { mvt_tile tile; int features_added = 0; bool was_compressed; if (!tile.decode(message, was_compressed)) { fprintf(stderr, "Couldn't decompress tile %d/%u/%u\n", z, x, y); exit(EXIT_FAILURE); } for (size_t l = 0; l < tile.layers.size(); l++) { mvt_layer &layer = tile.layers[l]; auto found = renames.find(layer.name); if (found != renames.end()) { layer.name = found->second; } if (keep_layers.size() > 0 && keep_layers.count(layer.name) == 0) { continue; } if (remove_layers.count(layer.name) != 0) { continue; } size_t ol; for (ol = 0; ol < outtile.layers.size(); ol++) { if (tile.layers[l].name == outtile.layers[ol].name) { break; } } if (ol == outtile.layers.size()) { outtile.layers.push_back(mvt_layer()); outtile.layers[ol].name = layer.name; outtile.layers[ol].version = layer.version; outtile.layers[ol].extent = layer.extent; } mvt_layer &outlayer = outtile.layers[ol]; if (layer.extent != outlayer.extent) { if (layer.extent > outlayer.extent) { for (size_t i = 0; i < outlayer.features.size(); i++) { for (size_t j = 0; j < outlayer.features[i].geometry.size(); j++) { outlayer.features[i].geometry[j].x = outlayer.features[i].geometry[j].x * layer.extent / outlayer.extent; outlayer.features[i].geometry[j].y = outlayer.features[i].geometry[j].y * layer.extent / outlayer.extent; } } outlayer.extent = layer.extent; } } auto file_keys = layermap.find(layer.name); for (size_t f = 0; f < layer.features.size(); f++) { mvt_feature feat = layer.features[f]; std::set<std::string> exclude_attributes; if (filter != NULL) { std::map<std::string, mvt_value> attributes; for (size_t t = 0; t + 1 < feat.tags.size(); t += 2) { std::string key = layer.keys[feat.tags[t]]; mvt_value &val = layer.values[feat.tags[t + 1]]; attributes.insert(std::pair<std::string, mvt_value>(key, val)); } if (feat.has_id) { mvt_value v; v.type = mvt_uint; v.numeric_value.uint_value = feat.id; attributes.insert(std::pair<std::string, mvt_value>("$id", v)); } mvt_value v; v.type = mvt_string; if (feat.type == mvt_point) { v.string_value = "Point"; } else if (feat.type == mvt_linestring) { v.string_value = "LineString"; } else if (feat.type == mvt_polygon) { v.string_value = "Polygon"; } attributes.insert(std::pair<std::string, mvt_value>("$type", v)); mvt_value v2; v2.type = mvt_uint; v2.numeric_value.uint_value = z; attributes.insert(std::pair<std::string, mvt_value>("$zoom", v2)); if (!evaluate(attributes, layer.name, filter, exclude_attributes)) { continue; } } mvt_feature outfeature; int matched = 0; if (feat.has_id) { outfeature.has_id = true; outfeature.id = feat.id; } std::map<std::string, std::pair<mvt_value, type_and_string>> attributes; std::vector<std::string> key_order; for (size_t t = 0; t + 1 < feat.tags.size(); t += 2) { const char *key = layer.keys[feat.tags[t]].c_str(); mvt_value &val = layer.values[feat.tags[t + 1]]; std::string value; int type = -1; if (val.type == mvt_string) { value = val.string_value; type = mvt_string; } else if (val.type == mvt_int) { aprintf(&value, "%lld", (long long) val.numeric_value.int_value); type = mvt_double; } else if (val.type == mvt_double) { aprintf(&value, "%s", milo::dtoa_milo(val.numeric_value.double_value).c_str()); type = mvt_double; } else if (val.type == mvt_float) { aprintf(&value, "%s", milo::dtoa_milo(val.numeric_value.float_value).c_str()); type = mvt_double; } else if (val.type == mvt_bool) { aprintf(&value, "%s", val.numeric_value.bool_value ? "true" : "false"); type = mvt_bool; } else if (val.type == mvt_sint) { aprintf(&value, "%lld", (long long) val.numeric_value.sint_value); type = mvt_double; } else if (val.type == mvt_uint) { aprintf(&value, "%llu", (long long) val.numeric_value.uint_value); type = mvt_double; } else { continue; } if (type < 0) { continue; } if (!exclude_all && exclude.count(std::string(key)) == 0 && exclude_attributes.count(std::string(key)) == 0) { type_and_string tas; tas.type = type; tas.string = value; attributes.insert(std::pair<std::string, std::pair<mvt_value, type_and_string>>(key, std::pair<mvt_value, type_and_string>(val, tas))); key_order.push_back(key); } if (header.size() > 0 && strcmp(key, header[0].c_str()) == 0) { std::map<std::string, std::vector<std::string>>::iterator ii = mapping.find(value); if (ii != mapping.end()) { std::vector<std::string> fields = ii->second; matched = 1; for (size_t i = 1; i < fields.size(); i++) { std::string joinkey = header[i]; std::string joinval = fields[i]; int attr_type = mvt_string; if (joinval.size() > 0) { if (joinval[0] == '"') { joinval = csv_dequote(joinval); } else if (is_number(joinval)) { attr_type = mvt_double; } } else if (pe) { attr_type = mvt_null; } const char *sjoinkey = joinkey.c_str(); if (!exclude_all && exclude.count(joinkey) == 0 && exclude_attributes.count(joinkey) == 0 && attr_type != mvt_null) { mvt_value outval; if (attr_type == mvt_string) { outval.type = mvt_string; outval.string_value = joinval; } else { outval.type = mvt_double; outval.numeric_value.double_value = atof(joinval.c_str()); } auto fa = attributes.find(sjoinkey); if (fa != attributes.end()) { attributes.erase(fa); } type_and_string tas; tas.type = outval.type; tas.string = joinval; // Convert from double to int if the joined attribute is an integer outval = stringified_to_mvt_value(outval.type, joinval.c_str()); attributes.insert(std::pair<std::string, std::pair<mvt_value, type_and_string>>(joinkey, std::pair<mvt_value, type_and_string>(outval, tas))); key_order.push_back(joinkey); } } } } } if (matched || !ifmatched) { if (file_keys == layermap.end()) { layermap.insert(std::pair<std::string, layermap_entry>(layer.name, layermap_entry(layermap.size()))); file_keys = layermap.find(layer.name); file_keys->second.minzoom = z; file_keys->second.maxzoom = z; } // To keep attributes in their original order instead of alphabetical for (auto k : key_order) { auto fa = attributes.find(k); if (fa != attributes.end()) { outlayer.tag(outfeature, k, fa->second.first); add_to_file_keys(file_keys->second.file_keys, k, fa->second.second); attributes.erase(fa); } } outfeature.type = feat.type; outfeature.geometry = feat.geometry; if (layer.extent != outlayer.extent) { for (size_t i = 0; i < outfeature.geometry.size(); i++) { outfeature.geometry[i].x = outfeature.geometry[i].x * outlayer.extent / layer.extent; outfeature.geometry[i].y = outfeature.geometry[i].y * outlayer.extent / layer.extent; } } features_added++; outlayer.features.push_back(outfeature); if (z < file_keys->second.minzoom) { file_keys->second.minzoom = z; } if (z > file_keys->second.maxzoom) { file_keys->second.maxzoom = z; } if (feat.type == mvt_point) { file_keys->second.points++; } else if (feat.type == mvt_linestring) { file_keys->second.lines++; } else if (feat.type == mvt_polygon) { file_keys->second.polygons++; } } } } if (features_added == 0) { return; } } double min(double a, double b) { if (a < b) { return a; } else { return b; } } double max(double a, double b) { if (a > b) { return a; } else { return b; } } struct reader { long long zoom = 0; long long x = 0; long long sorty = 0; long long y = 0; int z_flag = 0; std::string data = ""; std::vector<zxy> dirtiles; std::string dirbase; std::string name; sqlite3 *db = NULL; sqlite3_stmt *stmt = NULL; struct reader *next = NULL; bool operator<(const struct reader &r) const { if (zoom < r.zoom) { return true; } if (zoom > r.zoom) { return false; } if (x < r.x) { return true; } if (x > r.x) { return false; } if (sorty < r.sorty) { return true; } if (sorty > r.sorty) { return false; } if (data < r.data) { return true; } return false; } }; struct reader *begin_reading(char *fname) { struct reader *r = new reader; r->name = fname; struct stat st; if (stat(fname, &st) == 0 && (st.st_mode & S_IFDIR) != 0) { r->db = NULL; r->stmt = NULL; r->next = NULL; r->dirtiles = enumerate_dirtiles(fname); r->dirbase = fname; if (r->dirtiles.size() == 0) { r->zoom = 32; } else { r->zoom = r->dirtiles[0].z; r->x = r->dirtiles[0].x; r->y = r->dirtiles[0].y; r->sorty = (1LL << r->zoom) - 1 - r->y; r->data = dir_read_tile(r->dirbase, r->dirtiles[0]); r->dirtiles.erase(r->dirtiles.begin()); } } else { sqlite3 *db; if (sqlite3_open(fname, &db) != SQLITE_OK) { fprintf(stderr, "%s: %s\n", fname, sqlite3_errmsg(db)); exit(EXIT_FAILURE); } char *err = NULL; if (sqlite3_exec(db, "PRAGMA integrity_check;", NULL, NULL, &err) != SQLITE_OK) { fprintf(stderr, "%s: integrity_check: %s\n", fname, err); exit(EXIT_FAILURE); } const char *sql = "SELECT zoom_level, tile_column, tile_row, tile_data from tiles order by zoom_level, tile_column, tile_row;"; sqlite3_stmt *stmt; if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) != SQLITE_OK) { fprintf(stderr, "%s: select failed: %s\n", fname, sqlite3_errmsg(db)); exit(EXIT_FAILURE); } r->db = db; r->stmt = stmt; r->next = NULL; if (sqlite3_step(stmt) == SQLITE_ROW) { r->zoom = sqlite3_column_int(stmt, 0); r->x = sqlite3_column_int(stmt, 1); r->sorty = sqlite3_column_int(stmt, 2); r->y = (1LL << r->zoom) - 1 - r->sorty; const char *data = (const char *) sqlite3_column_blob(stmt, 3); size_t len = sqlite3_column_bytes(stmt, 3); r->data = std::string(data, len); } else { r->zoom = 32; } } return r; } struct arg { std::map<zxy, std::vector<std::string>> inputs{}; std::map<zxy, std::string> outputs{}; std::map<std::string, layermap_entry> *layermap = NULL; std::vector<std::string> *header = NULL; std::map<std::string, std::vector<std::string>> *mapping = NULL; std::set<std::string> *exclude = NULL; std::set<std::string> *keep_layers = NULL; std::set<std::string> *remove_layers = NULL; int ifmatched = 0; json_object *filter = NULL; }; void *join_worker(void *v) { arg *a = (arg *) v; for (auto ai = a->inputs.begin(); ai != a->inputs.end(); ++ai) { mvt_tile tile; for (size_t i = 0; i < ai->second.size(); i++) { handle(ai->second[i], ai->first.z, ai->first.x, ai->first.y, *(a->layermap), *(a->header), *(a->mapping), *(a->exclude), *(a->keep_layers), *(a->remove_layers), a->ifmatched, tile, a->filter); } ai->second.clear(); bool anything = false; mvt_tile outtile; for (size_t i = 0; i < tile.layers.size(); i++) { if (tile.layers[i].features.size() > 0) { outtile.layers.push_back(tile.layers[i]); anything = true; } } if (anything) { std::string pbf = outtile.encode(); std::string compressed; if (!pC) { compress(pbf, compressed); } else { compressed = pbf; } if (!pk && compressed.size() > 500000) { fprintf(stderr, "Tile %lld/%lld/%lld size is %lld, >500000. Skipping this tile\n.", ai->first.z, ai->first.x, ai->first.y, (long long) compressed.size()); } else { a->outputs.insert(std::pair<zxy, std::string>(ai->first, compressed)); } } } return NULL; } void handle_tasks(std::map<zxy, std::vector<std::string>> &tasks, std::vector<std::map<std::string, layermap_entry>> &layermaps, sqlite3 *outdb, const char *outdir, std::vector<std::string> &header, std::map<std::string, std::vector<std::string>> &mapping, std::set<std::string> &exclude, int ifmatched, std::set<std::string> &keep_layers, std::set<std::string> &remove_layers, json_object *filter) { pthread_t pthreads[CPUS]; std::vector<arg> args; for (size_t i = 0; i < CPUS; i++) { args.push_back(arg()); args[i].layermap = &layermaps[i]; args[i].header = &header; args[i].mapping = &mapping; args[i].exclude = &exclude; args[i].keep_layers = &keep_layers; args[i].remove_layers = &remove_layers; args[i].ifmatched = ifmatched; args[i].filter = filter; } size_t count = 0; // This isn't careful about distributing tasks evenly across CPUs, // but, from testing, it actually takes a little longer to do // the proper allocation than is saved by perfectly balanced threads. for (auto ai = tasks.begin(); ai != tasks.end(); ++ai) { args[count].inputs.insert(*ai); count = (count + 1) % CPUS; if (ai == tasks.begin()) { if (!quiet) { fprintf(stderr, "%lld/%lld/%lld \r", ai->first.z, ai->first.x, ai->first.y); } } } for (size_t i = 0; i < CPUS; i++) { if (pthread_create(&pthreads[i], NULL, join_worker, &args[i]) != 0) { perror("pthread_create"); exit(EXIT_FAILURE); } } for (size_t i = 0; i < CPUS; i++) { void *retval; if (pthread_join(pthreads[i], &retval) != 0) { perror("pthread_join"); } for (auto ai = args[i].outputs.begin(); ai != args[i].outputs.end(); ++ai) { if (outdb != NULL) { mbtiles_write_tile(outdb, ai->first.z, ai->first.x, ai->first.y, ai->second.data(), ai->second.size()); } else if (outdir != NULL) { dir_write_tile(outdir, ai->first.z, ai->first.x, ai->first.y, ai->second); } } } } void handle_vector_layers(json_object *vector_layers, std::map<std::string, layermap_entry> &layermap, std::map<std::string, std::string> &attribute_descriptions) { if (vector_layers != NULL && vector_layers->type == JSON_ARRAY) { for (size_t i = 0; i < vector_layers->length; i++) { if (vector_layers->array[i]->type == JSON_HASH) { json_object *id = json_hash_get(vector_layers->array[i], "id"); json_object *desc = json_hash_get(vector_layers->array[i], "description"); if (id != NULL && desc != NULL && id->type == JSON_STRING && desc->type == JSON_STRING) { std::string sid = id->string; std::string sdesc = desc->string; if (sdesc.size() != 0) { auto f = layermap.find(sid); if (f != layermap.end()) { f->second.description = sdesc; } } } json_object *fields = json_hash_get(vector_layers->array[i], "fields"); if (fields != NULL && fields->type == JSON_HASH) { for (size_t j = 0; j < fields->length; j++) { if (fields->keys[j]->type == JSON_STRING && fields->values[j]->type) { const char *desc2 = fields->values[j]->string; if (strcmp(desc2, "Number") != 0 && strcmp(desc2, "String") != 0 && strcmp(desc2, "Boolean") != 0 && strcmp(desc2, "Mixed") != 0) { attribute_descriptions.insert(std::pair<std::string, std::string>(fields->keys[j]->string, desc2)); } } } } } } } } void decode(struct reader *readers, std::map<std::string, layermap_entry> &layermap, sqlite3 *outdb, const char *outdir, struct stats *st, std::vector<std::string> &header, std::map<std::string, std::vector<std::string>> &mapping, std::set<std::string> &exclude, int ifmatched, std::string &attribution, std::string &description, std::set<std::string> &keep_layers, std::set<std::string> &remove_layers, std::string &name, json_object *filter, std::map<std::string, std::string> &attribute_descriptions) { std::vector<std::map<std::string, layermap_entry>> layermaps; for (size_t i = 0; i < CPUS; i++) { layermaps.push_back(std::map<std::string, layermap_entry>()); } std::map<zxy, std::vector<std::string>> tasks; double minlat = INT_MAX; double minlon = INT_MAX; double maxlat = INT_MIN; double maxlon = INT_MIN; int zoom_for_bbox = -1; while (readers != NULL && readers->zoom < 32) { reader *r = readers; readers = readers->next; r->next = NULL; if (r->zoom != zoom_for_bbox) { // Only use highest zoom for bbox calculation // to avoid z0 always covering the world minlat = minlon = INT_MAX; maxlat = maxlon = INT_MIN; zoom_for_bbox = r->zoom; } double lat1, lon1, lat2, lon2; tile2lonlat(r->x, r->y, r->zoom, &lon1, &lat1); tile2lonlat(r->x + 1, r->y + 1, r->zoom, &lon2, &lat2); minlat = min(lat2, minlat); minlon = min(lon1, minlon); maxlat = max(lat1, maxlat); maxlon = max(lon2, maxlon); if (r->zoom >= minzoom && r->zoom <= maxzoom) { zxy tile = zxy(r->zoom, r->x, r->y); if (tasks.count(tile) == 0) { tasks.insert(std::pair<zxy, std::vector<std::string>>(tile, std::vector<std::string>())); } auto f = tasks.find(tile); f->second.push_back(r->data); } if (readers == NULL || readers->zoom != r->zoom || readers->x != r->x || readers->y != r->y) { if (tasks.size() > 100 * CPUS) { handle_tasks(tasks, layermaps, outdb, outdir, header, mapping, exclude, ifmatched, keep_layers, remove_layers, filter); tasks.clear(); } } if (r->db != NULL) { if (sqlite3_step(r->stmt) == SQLITE_ROW) { r->zoom = sqlite3_column_int(r->stmt, 0); r->x = sqlite3_column_int(r->stmt, 1); r->sorty = sqlite3_column_int(r->stmt, 2); r->y = (1LL << r->zoom) - 1 - r->sorty; const char *data = (const char *) sqlite3_column_blob(r->stmt, 3); size_t len = sqlite3_column_bytes(r->stmt, 3); r->data = std::string(data, len); } else { r->zoom = 32; } } else { if (r->dirtiles.size() == 0) { r->zoom = 32; } else { r->zoom = r->dirtiles[0].z; r->x = r->dirtiles[0].x; r->y = r->dirtiles[0].y; r->sorty = (1LL << r->zoom) - 1 - r->y; r->data = dir_read_tile(r->dirbase, r->dirtiles[0]); r->dirtiles.erase(r->dirtiles.begin()); } } struct reader **rr; for (rr = &readers; *rr != NULL; rr = &((*rr)->next)) { if (*r < **rr) { break; } } r->next = *rr; *rr = r; } st->minlon = min(minlon, st->minlon); st->maxlon = max(maxlon, st->maxlon); st->minlat = min(minlat, st->minlat); st->maxlat = max(maxlat, st->maxlat); handle_tasks(tasks, layermaps, outdb, outdir, header, mapping, exclude, ifmatched, keep_layers, remove_layers, filter); layermap = merge_layermaps(layermaps); struct reader *next; for (struct reader *r = readers; r != NULL; r = next) { next = r->next; sqlite3 *db = r->db; if (db == NULL) { db = dirmeta2tmp(r->dirbase.c_str()); } else { sqlite3_finalize(r->stmt); } if (sqlite3_prepare_v2(db, "SELECT value from metadata where name = 'minzoom'", -1, &r->stmt, NULL) == SQLITE_OK) { if (sqlite3_step(r->stmt) == SQLITE_ROW) { int minz = max(sqlite3_column_int(r->stmt, 0), minzoom); st->minzoom = min(st->minzoom, minz); } sqlite3_finalize(r->stmt); } if (sqlite3_prepare_v2(db, "SELECT value from metadata where name = 'maxzoom'", -1, &r->stmt, NULL) == SQLITE_OK) { if (sqlite3_step(r->stmt) == SQLITE_ROW) { int maxz = min(sqlite3_column_int(r->stmt, 0), maxzoom); if (st->maxzoom >= 0 && maxz != st->maxzoom) { fprintf(stderr, "Warning: mismatched maxzooms: %d in %s vs previous %d\n", maxz, r->name.c_str(), st->maxzoom); } st->maxzoom = max(st->maxzoom, maxz); } sqlite3_finalize(r->stmt); } if (sqlite3_prepare_v2(db, "SELECT value from metadata where name = 'center'", -1, &r->stmt, NULL) == SQLITE_OK) { if (sqlite3_step(r->stmt) == SQLITE_ROW) { const unsigned char *s = sqlite3_column_text(r->stmt, 0); if (s != NULL) { sscanf((char *) s, "%lf,%lf", &st->midlon, &st->midlat); } } sqlite3_finalize(r->stmt); } if (sqlite3_prepare_v2(db, "SELECT value from metadata where name = 'attribution'", -1, &r->stmt, NULL) == SQLITE_OK) { if (sqlite3_step(r->stmt) == SQLITE_ROW) { const unsigned char *s = sqlite3_column_text(r->stmt, 0); if (s != NULL) { attribution = std::string((char *) s); } } sqlite3_finalize(r->stmt); } if (sqlite3_prepare_v2(db, "SELECT value from metadata where name = 'description'", -1, &r->stmt, NULL) == SQLITE_OK) { if (sqlite3_step(r->stmt) == SQLITE_ROW) { const unsigned char *s = sqlite3_column_text(r->stmt, 0); if (s != NULL) { description = std::string((char *) s); } } sqlite3_finalize(r->stmt); } if (sqlite3_prepare_v2(db, "SELECT value from metadata where name = 'name'", -1, &r->stmt, NULL) == SQLITE_OK) { if (sqlite3_step(r->stmt) == SQLITE_ROW) { const unsigned char *s = sqlite3_column_text(r->stmt, 0); if (s != NULL) { if (name.size() == 0) { name = std::string((char *) s); } else { std::string proposed = name + " + " + std::string((char *) s); if (proposed.size() < 255) { name = proposed; } } } } sqlite3_finalize(r->stmt); } if (sqlite3_prepare_v2(db, "SELECT value from metadata where name = 'bounds'", -1, &r->stmt, NULL) == SQLITE_OK) { if (sqlite3_step(r->stmt) == SQLITE_ROW) { const unsigned char *s = sqlite3_column_text(r->stmt, 0); if (s != NULL) { if (sscanf((char *) s, "%lf,%lf,%lf,%lf", &minlon, &minlat, &maxlon, &maxlat) == 4) { st->minlon = min(minlon, st->minlon); st->maxlon = max(maxlon, st->maxlon); st->minlat = min(minlat, st->minlat); st->maxlat = max(maxlat, st->maxlat); } } } sqlite3_finalize(r->stmt); } if (sqlite3_prepare_v2(db, "SELECT value from metadata where name = 'json'", -1, &r->stmt, NULL) == SQLITE_OK) { if (sqlite3_step(r->stmt) == SQLITE_ROW) { const unsigned char *s = sqlite3_column_text(r->stmt, 0); if (s != NULL) { json_pull *jp = json_begin_string((const char *) s); json_object *o = json_read_tree(jp); if (o != NULL && o->type == JSON_HASH) { json_object *vector_layers = json_hash_get(o, "vector_layers"); handle_vector_layers(vector_layers, layermap, attribute_descriptions); json_free(o); } json_end(jp); } } sqlite3_finalize(r->stmt); } // Closes either real db or temp mirror of metadata.json if (sqlite3_close(db) != SQLITE_OK) { fprintf(stderr, "Could not close database: %s\n", sqlite3_errmsg(db)); exit(EXIT_FAILURE); } delete r; } } void usage(char **argv) { fprintf(stderr, "Usage: %s [-f] [-i] [-pk] [-pC] [-c joins.csv] [-X] [-x exclude ...] -o new.mbtiles source.mbtiles ...\n", argv[0]); exit(EXIT_FAILURE); } int main(int argc, char **argv) { char *out_mbtiles = NULL; char *out_dir = NULL; sqlite3 *outdb = NULL; char *csv = NULL; int force = 0; int ifmatched = 0; json_object *filter = NULL; CPUS = sysconf(_SC_NPROCESSORS_ONLN); const char *TIPPECANOE_MAX_THREADS = getenv("TIPPECANOE_MAX_THREADS"); if (TIPPECANOE_MAX_THREADS != NULL) { CPUS = atoi(TIPPECANOE_MAX_THREADS); } if (CPUS < 1) { CPUS = 1; } std::vector<std::string> header; std::map<std::string, std::vector<std::string>> mapping; std::set<std::string> exclude; std::set<std::string> keep_layers; std::set<std::string> remove_layers; std::string set_name, set_description, set_attribution; struct option long_options[] = { {"output", required_argument, 0, 'o'}, {"output-to-directory", required_argument, 0, 'e'}, {"force", no_argument, 0, 'f'}, {"if-matched", no_argument, 0, 'i'}, {"attribution", required_argument, 0, 'A'}, {"name", required_argument, 0, 'n'}, {"description", required_argument, 0, 'N'}, {"prevent", required_argument, 0, 'p'}, {"csv", required_argument, 0, 'c'}, {"exclude", required_argument, 0, 'x'}, {"exclude-all", no_argument, 0, 'X'}, {"layer", required_argument, 0, 'l'}, {"exclude-layer", required_argument, 0, 'L'}, {"quiet", no_argument, 0, 'q'}, {"maximum-zoom", required_argument, 0, 'z'}, {"minimum-zoom", required_argument, 0, 'Z'}, {"feature-filter-file", required_argument, 0, 'J'}, {"feature-filter", required_argument, 0, 'j'}, {"rename-layer", required_argument, 0, 'R'}, {"no-tile-size-limit", no_argument, &pk, 1}, {"no-tile-compression", no_argument, &pC, 1}, {"empty-csv-columns-are-null", no_argument, &pe, 1}, {"no-tile-stats", no_argument, &pg, 1}, {0, 0, 0, 0}, }; std::string getopt_str; for (size_t lo = 0; long_options[lo].name != NULL; lo++) { if (long_options[lo].val > ' ') { getopt_str.push_back(long_options[lo].val); if (long_options[lo].has_arg == required_argument) { getopt_str.push_back(':'); } } } extern int optind; extern char *optarg; int i; while ((i = getopt_long(argc, argv, getopt_str.c_str(), long_options, NULL)) != -1) { switch (i) { case 0: break; case 'o': out_mbtiles = optarg; break; case 'e': out_dir = optarg; break; case 'f': force = 1; break; case 'i': ifmatched = 1; break; case 'A': set_attribution = optarg; break; case 'n': set_name = optarg; break; case 'N': set_description = optarg; break; case 'z': maxzoom = atoi(optarg); break; case 'Z': minzoom = atoi(optarg); break; case 'J': filter = read_filter(optarg); break; case 'j': filter = parse_filter(optarg); break; case 'p': if (strcmp(optarg, "k") == 0) { pk = true; } else if (strcmp(optarg, "C") == 0) { pC = true; } else if (strcmp(optarg, "g") == 0) { pg = true; } else if (strcmp(optarg, "e") == 0) { pe = true; } else { fprintf(stderr, "%s: Unknown option for -p%s\n", argv[0], optarg); exit(EXIT_FAILURE); } break; case 'c': if (csv != NULL) { fprintf(stderr, "Only one -c for now\n"); exit(EXIT_FAILURE); } csv = optarg; readcsv(csv, header, mapping); break; case 'x': exclude.insert(std::string(optarg)); break; case 'X': exclude_all = true; break; case 'l': keep_layers.insert(std::string(optarg)); break; case 'L': remove_layers.insert(std::string(optarg)); break; case 'R': { char *cp = strchr(optarg, ':'); if (cp == NULL || cp == optarg) { fprintf(stderr, "%s: -R requires old:new\n", argv[0]); exit(EXIT_FAILURE); } std::string before = std::string(optarg).substr(0, cp - optarg); std::string after = std::string(cp + 1); renames.insert(std::pair<std::string, std::string>(before, after)); break; } case 'q': quiet = true; break; default: usage(argv); } } if (argc - optind < 1) { usage(argv); } if (out_mbtiles == NULL && out_dir == NULL) { fprintf(stderr, "%s: must specify -o out.mbtiles or -e directory\n", argv[0]); usage(argv); } if (out_mbtiles != NULL && out_dir != NULL) { fprintf(stderr, "%s: Options -o and -e cannot be used together\n", argv[0]); usage(argv); } if (minzoom > maxzoom) { fprintf(stderr, "%s: Minimum zoom -Z%d cannot be greater than maxzoom -z%d\n", argv[0], minzoom, maxzoom); exit(EXIT_FAILURE); } if (out_mbtiles != NULL) { if (force) { unlink(out_mbtiles); } outdb = mbtiles_open(out_mbtiles, argv, 0); } if (out_dir != NULL) { check_dir(out_dir, argv, force, false); } struct stats st; memset(&st, 0, sizeof(st)); st.minzoom = st.minlat = st.minlon = INT_MAX; st.maxzoom = st.maxlat = st.maxlon = INT_MIN; std::map<std::string, layermap_entry> layermap; std::string attribution; std::string description; std::string name; struct reader *readers = NULL; for (i = optind; i < argc; i++) { reader *r = begin_reading(argv[i]); struct reader **rr; for (rr = &readers; *rr != NULL; rr = &((*rr)->next)) { if (*r < **rr) { break; } } r->next = *rr; *rr = r; } std::map<std::string, std::string> attribute_descriptions; decode(readers, layermap, outdb, out_dir, &st, header, mapping, exclude, ifmatched, attribution, description, keep_layers, remove_layers, name, filter, attribute_descriptions); if (set_attribution.size() != 0) { attribution = set_attribution; } if (set_description.size() != 0) { description = set_description; } if (set_name.size() != 0) { name = set_name; } mbtiles_write_metadata(outdb, out_dir, name.c_str(), st.minzoom, st.maxzoom, st.minlat, st.minlon, st.maxlat, st.maxlon, st.midlat, st.midlon, 0, attribution.size() != 0 ? attribution.c_str() : NULL, layermap, true, description.c_str(), !pg, attribute_descriptions, "tile-join"); if (outdb != NULL) { mbtiles_close(outdb, argv[0]); } if (filter != NULL) { json_free(filter); } return 0; }
// ---------------------------------------------------- // Timer.cpp // Body for CPU Tick Timer class // ---------------------------------------------------- #include "Timer.h" // --------------------------------------------- Timer::Timer() { Start(); } // --------------------------------------------- void Timer::Start() { running = true; started_at = SDL_GetTicks(); } // --------------------------------------------- void Timer::Stop() { running = false; stopped_at = SDL_GetTicks(); } // --------------------------------------------- Uint32 Timer::Read() { if (running == true) { return SDL_GetTicks() - started_at; } else { return stopped_at - started_at; } } float Timer::ReadSec() const { return float(SDL_GetTicks() - started_at) / 1000.0f; } void Timer::Resume() { running = true; resumed_at = SDL_GetTicks(); //started_at = started_at + (resumed_at - stopped_at); resumed_at = 0; stopped_at = 0; } void Timer::Reset() { started_at = 0; stopped_at = 0; resumed_at = 0; }
#include <iostream> #include <string> #include <algorithm> bool zScanner(const std::string& str, int i) { for (int j = 0; j < str.size(); ++j) { if (str[j] != 'z') // if j = z then it will return false // { return false; } } return true; } int main() { std::string str = "aaaaaaaa"; std::string meeps = "z"; std::cout << str << std::endl; for (int i = 0; i < str.size(); i++) { if (!zScanner(str, i) || i != str.size() - 1) // if zscanner is false then it will go back into the loop. If the size does not equel to the string -1(Because in a string it adds a empty character to the end ) it will go back to the loop. { for (int a = 0; a < str.size(); a++) { continue; } } str[i]++; // Adds to the value. Ex: a-z std::cout << str << std::endl; for (i = 0; i < 20;) // { str[i]++; std::cout << str << std::endl; char c = str[i]; if (c == 'z') // if a character = z then it will reset to a { str[i] = 'a'; i++; if (i == str.size()-1) { i = 0; } if (!zScanner(str, i)) { str[i]++; } } } } }
/* * Copyright (c) 2000-2001,2011,2014 Apple Inc. All Rights Reserved. * * The contents of this file constitute Original Code as defined in and are * subject to the Apple Public Source License Version 1.2 (the 'License'). * You may not use this file except in compliance with the License. Please obtai n * a copy of the License at http://www.apple.com/publicsource and read it before * using this file. * * This Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the * specific language governing rights and limitations under the License. */ // // Produce the "genuine plugin version" of the Apple "file DL" // #include <AppleFileDL.h> // // Create the plugin object and generate the C layer hookup // static ModuleNexus<AppleFileDL> plugin; #define SPINAME(s) s ## __apple_file_dl #include <security_cdsa_plugin/pluginspi.h>
/*========================================================================= Program: Visualization Toolkit Module: vtkBSplineTransform.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkBSplineTransform.h" #include "vtkImageData.h" #include "vtkMath.h" #include "vtkStreamingDemandDrivenPipeline.h" #include "vtkTrivialProducer.h" #include "vtkObjectFactory.h" #include <cmath> vtkStandardNewMacro(vtkBSplineTransform); class vtkBSplineTransformConnectionHolder: public vtkAlgorithm { public: static vtkBSplineTransformConnectionHolder *New(); vtkTypeMacro(vtkBSplineTransformConnectionHolder,vtkAlgorithm); vtkBSplineTransformConnectionHolder() { this->SetNumberOfInputPorts(1); } }; vtkStandardNewMacro(vtkBSplineTransformConnectionHolder); namespace { //------------------------------------------------------------- // The b-spline provides continuity of the first and second // derivatives with a piecewise cubic polynomial. The polynomial // does not pass through the knots. inline void vtkBSplineTransformWeights(double F[4], double G[4], double f) { const double sixth = 1.0/6.0; const double half = 0.5; double f2 = f*f; F[3] = f2*f*sixth; F[0] = (f2 - f)*half - F[3] + sixth; F[2] = f + F[0] - F[3]*2; F[1] = 1 - F[0] - F[2] - F[3]; // weights for derivative G[3] = f2*half; G[0] = f - half - G[3]; G[2] = 1 + G[0] - G[3]*2; G[1] = -G[0] - G[2] - G[3]; } //------------------------------------------------------------- // if the support region for the b-spline is not fully within // the bounds, take action here according to the BorderMode static int vtkBSplineTransformBorder( int gridId0[3], int gridId1[3], int gridId2[3], int gridId3[3], double *ff[3], double *gg[3], int ext[3], int borderMode) { int pointIsInvalid = 0; switch (borderMode) { case VTK_BSPLINE_EDGE: // coefficient at edge continues infinitely past edge // (this is continuous and smooth) break; case VTK_BSPLINE_ZERO: // coefficients past edge are all zero // (this is continuous and smooth) for (int i = 0; i < 3; i++) { // note: "ext" is just the size subtract one if (ext[i] != 0) { if (gridId1[i] == 0) { ff[i][0] = 0.0; gg[i][0] = 0.0; } else if (gridId2[i] == 0) { ff[i][0] = 0.0; ff[i][1] = 0.0; gg[i][0] = 0.0; gg[i][1] = 0.0; } else if (gridId3[i] == 0) { ff[i][0] = 0.0; ff[i][1] = 0.0; ff[i][2] = 0.0; gg[i][0] = 0.0; gg[i][1] = 0.0; gg[i][2] = 0.0; } else if (gridId3[i] < 0) { pointIsInvalid = 1; } if (gridId2[i] == ext[i]) { ff[i][3] = 0.0; gg[i][3] = 0.0; } else if (gridId1[i] == ext[i]) { ff[i][2] = 0.0; ff[i][3] = 0.0; gg[i][2] = 0.0; gg[i][3] = 0.0; } else if (gridId0[i] == ext[i]) { ff[i][1] = 0.0; ff[i][2] = 0.0; ff[i][3] = 0.0; gg[i][1] = 0.0; gg[i][2] = 0.0; gg[i][3] = 0.0; } else if (gridId0[i] > ext[i]) { pointIsInvalid = 1; } } } break; case VTK_BSPLINE_ZERO_AT_BORDER: // adjust weights to achieve zero displacement at one // grid-spacing past the bounds of the grid // (this is continuous but not smooth) for (int j = 0; j < 3; j++) { // note: "ext" is just the size subtract one if (ext[j] != 0) { if (gridId1[j] == 0) { ff[j][0] = 0.0; if (gg[j]) { gg[j][0] = 0.0; } } else if (gridId2[j] == 0) { ff[j][2] -= ff[j][0]; ff[j][0] = 0.0; ff[j][1] = 0.0; gg[j][2] -= gg[j][0]; gg[j][0] = 0.0; gg[j][1] = 0.0; } else if (gridId2[j] < 0) { pointIsInvalid = 1; } if (gridId2[j] == ext[j]) { ff[j][3] = 0.0; gg[j][3] = 0.0; } else if (gridId1[j] == ext[j]) { ff[j][1] -= ff[j][3]; ff[j][2] = 0.0; ff[j][3] = 0.0; gg[j][1] -= gg[j][3]; gg[j][2] = 0.0; gg[j][3] = 0.0; } else if (gridId1[j] > ext[j]) { pointIsInvalid = 1; } } } break; } for (int k = 0; k < 3; k++) { // clamp to the boundary limits int emax = ext[k]; if (gridId0[k] < 0) { gridId0[k] = 0; } if (gridId0[k] > emax) { gridId0[k] = emax; } if (gridId1[k] < 0) { gridId1[k] = 0; } if (gridId1[k] > emax) { gridId1[k] = emax; } if (gridId2[k] < 0) { gridId2[k] = 0; } if (gridId2[k] > emax) { gridId2[k] = emax; } if (gridId3[k] < 0) { gridId3[k] = 0; } if (gridId3[k] > emax) { gridId3[k] = emax; } } return pointIsInvalid; } //------------------------------------------------------------- template <class T> class vtkBSplineTransformFunction { public: static void Cubic( const double point[3], double displacement[3], double derivatives[3][3], void *gridPtrVoid, int gridExt[6], vtkIdType gridInc[3], int borderMode); }; template<class T> void vtkBSplineTransformFunction<T>::Cubic( const double point[3], double displacement[3], double derivatives[3][3], void *gridPtrVoid, int gridExt[6], vtkIdType gridInc[3], int borderMode) { // the interpolation weights double fX[4] = { 0, 1, 0, 0 }; double fY[4] = { 0, 1, 0, 0 }; double fZ[4] = { 0, 1, 0, 0 }; double gX[4] = { 0, 0, 0, 0 }; double gY[4] = { 0, 0, 0, 0 }; double gZ[4] = { 0, 0, 0, 0 }; double *ff[3]; double *gg[3]; ff[0] = fX; ff[1] = fY; ff[2] = fZ; gg[0] = gX; gg[1] = gY; gg[2] = gZ; // initialize the knot positions int gridId0[3] = { 0, 0, 0 }; int gridId1[3] = { 0, 0, 0 }; int gridId2[3] = { 0, 0, 0 }; int gridId3[3] = { 0, 0, 0 }; // "ext" is the size subtract one int ext[3]; // compute the weights for (int i = 0; i < 3; i++) { ext[i] = gridExt[2*i + 1] - gridExt[2*i]; if (ext[i] != 0) { // change point into integer plus fraction int idx = vtkMath::Floor(point[i]); double f = point[i] - idx; idx -= gridExt[2*i]; idx--; gridId0[i] = idx++; gridId1[i] = idx++; gridId2[i] = idx++; gridId3[i] = idx++; vtkBSplineTransformWeights(ff[i], gg[i], f); } } // do bounds check, most points will be inside so optimize for that int pointIsInvalid = 0; if ((gridId0[0] | (ext[0] - gridId3[0]) | gridId0[1] | (ext[1] - gridId3[1]) | gridId0[2] | (ext[2] - gridId3[2])) < 0) { pointIsInvalid = vtkBSplineTransformBorder( gridId0, gridId1, gridId2, gridId3, ff, gg, ext, borderMode); } // Compute the indices into the data vtkIdType factX[4],factY[4],factZ[4]; factX[0] = gridId0[0]*gridInc[0]; factX[1] = gridId1[0]*gridInc[0]; factX[2] = gridId2[0]*gridInc[0]; factX[3] = gridId3[0]*gridInc[0]; factY[0] = gridId0[1]*gridInc[1]; factY[1] = gridId1[1]*gridInc[1]; factY[2] = gridId2[1]*gridInc[1]; factY[3] = gridId3[1]*gridInc[1]; factZ[0] = gridId0[2]*gridInc[2]; factZ[1] = gridId1[2]*gridInc[2]; factZ[2] = gridId2[2]*gridInc[2]; factZ[3] = gridId3[2]*gridInc[2]; // initialize displacement and derivatives to zero displacement[0] = 0.0; displacement[1] = 0.0; displacement[2] = 0.0; if (derivatives) { for (int i = 0; i < 3; i++) { derivatives[i][0] = 0.0; derivatives[i][1] = 0.0; derivatives[i][2] = 0.0; } } // if point is valid, do the interpolation if (!pointIsInvalid) { T *gridPtr = static_cast<T *>(gridPtrVoid); // shortcut for 1D and 2D images (ext is size subtract 1) int singleZ = (ext[2] == 0); int jl = singleZ; int jm = 4 - 2*singleZ; int singleY = (ext[1] == 0); int kl = singleY; int km = 4 - 2*singleY; // here is the tricubic interpolation double vY[3],vZ[3]; displacement[0] = 0; displacement[1] = 0; displacement[2] = 0; for (int j = jl; j < jm; j++) { T *gridPtr1 = gridPtr + factZ[j]; vZ[0] = 0; vZ[1] = 0; vZ[2] = 0; for (int k = kl; k < km; k++) { T *gridPtr2 = gridPtr1 + factY[k]; vY[0] = 0; vY[1] = 0; vY[2] = 0; if (!derivatives) { for (int l = 0; l < 4; l++) { T *gridPtr3 = gridPtr2 + factX[l]; double f = fX[l]; vY[0] += gridPtr3[0] * f; vY[1] += gridPtr3[1] * f; vY[2] += gridPtr3[2] * f; } } else { for (int l = 0; l < 4; l++) { T *gridPtr3 = gridPtr2 + factX[l]; double f = fX[l]; double gff = gX[l]*fY[k]*fZ[j]; double fgf = fX[l]*gY[k]*fZ[j]; double ffg = fX[l]*fY[k]*gZ[j]; double inVal = gridPtr3[0]; vY[0] += inVal * f; derivatives[0][0] += inVal * gff; derivatives[0][1] += inVal * fgf; derivatives[0][2] += inVal * ffg; inVal = gridPtr3[1]; vY[1] += inVal * f; derivatives[1][0] += inVal * gff; derivatives[1][1] += inVal * fgf; derivatives[1][2] += inVal * ffg; inVal = gridPtr3[2]; vY[2] += inVal * f; derivatives[2][0] += inVal * gff; derivatives[2][1] += inVal * fgf; derivatives[2][2] += inVal * ffg; } } vZ[0] += vY[0]*fY[k]; vZ[1] += vY[1]*fY[k]; vZ[2] += vY[2]*fY[k]; } displacement[0] += vZ[0]*fZ[j]; displacement[1] += vZ[1]*fZ[j]; displacement[2] += vZ[2]*fZ[j]; } } } } // end anonymous namespace //---------------------------------------------------------------------------- vtkBSplineTransform::vtkBSplineTransform() { this->ConnectionHolder = vtkBSplineTransformConnectionHolder::New(); this->BorderMode = VTK_BSPLINE_EDGE; this->InverseTolerance = 1e-6; this->DisplacementScale = 1.0; this->CalculateSpline = 0; this->GridPointer = 0; } //---------------------------------------------------------------------------- vtkBSplineTransform::~vtkBSplineTransform() { this->ConnectionHolder->Delete(); this->ConnectionHolder = 0; } //---------------------------------------------------------------------------- void vtkBSplineTransform::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "BorderMode: " << this->GetBorderModeAsString() << "\n"; os << indent << "DisplacementScale: " << this->DisplacementScale << "\n"; } //---------------------------------------------------------------------------- const char *vtkBSplineTransform::GetBorderModeAsString() { switch (this->BorderMode) { case VTK_BSPLINE_EDGE: return "Edge"; case VTK_BSPLINE_ZERO: return "Zero"; case VTK_BSPLINE_ZERO_AT_BORDER: return "ZeroAtBorder"; default: break; } return "Unknown"; } //---------------------------------------------------------------------------- // need to check the input image data to determine MTime unsigned long vtkBSplineTransform::GetMTime() { unsigned long mtime,result; result = vtkWarpTransform::GetMTime(); if (this->GetCoefficientData()) { vtkAlgorithm* inputAlgorithm = this->ConnectionHolder->GetInputAlgorithm(0, 0); inputAlgorithm->UpdateInformation(); vtkStreamingDemandDrivenPipeline* sddp = vtkStreamingDemandDrivenPipeline::SafeDownCast( inputAlgorithm->GetExecutive()); mtime = sddp->GetPipelineMTime(); result = ( mtime > result ? mtime : result ); } return result; } //---------------------------------------------------------------------------- void vtkBSplineTransform::ForwardTransformPoint(const double inPoint[3], double outPoint[3]) { if (!this->GridPointer || !this->CalculateSpline) { outPoint[0] = inPoint[0]; outPoint[1] = inPoint[1]; outPoint[2] = inPoint[2]; return; } void *gridPtr = this->GridPointer; double *spacing = this->GridSpacing; double *origin = this->GridOrigin; int *extent = this->GridExtent; vtkIdType *increments = this->GridIncrements; double scale = this->DisplacementScale; double point[3]; double displacement[3]; displacement[0] = 0.0; displacement[1] = 0.0; displacement[2] = 0.0; // Convert the inPoint to i,j,k indices into the deformation grid // plus fractions point[0] = (inPoint[0] - origin[0])/spacing[0]; point[1] = (inPoint[1] - origin[1])/spacing[1]; point[2] = (inPoint[2] - origin[2])/spacing[2]; this->CalculateSpline(point, displacement, 0, gridPtr, extent, increments, this->BorderMode); outPoint[0] = inPoint[0] + displacement[0]*scale; outPoint[1] = inPoint[1] + displacement[1]*scale; outPoint[2] = inPoint[2] + displacement[2]*scale; } //---------------------------------------------------------------------------- // convert float to double, transform, and back again void vtkBSplineTransform::ForwardTransformPoint(const float point[3], float output[3]) { double fpoint[3]; fpoint[0] = point[0]; fpoint[1] = point[1]; fpoint[2] = point[2]; this->ForwardTransformPoint(fpoint,fpoint); output[0] = static_cast<float>(fpoint[0]); output[1] = static_cast<float>(fpoint[1]); output[2] = static_cast<float>(fpoint[2]); } //---------------------------------------------------------------------------- // calculate the derivative of the transform void vtkBSplineTransform::ForwardTransformDerivative(const double inPoint[3], double outPoint[3], double derivative[3][3]) { if (!this->GridPointer || !this->CalculateSpline) { outPoint[0] = inPoint[0]; outPoint[1] = inPoint[1]; outPoint[2] = inPoint[2]; vtkMath::Identity3x3(derivative); return; } void *gridPtr = this->GridPointer; double *spacing = this->GridSpacing; double *origin = this->GridOrigin; int *extent = this->GridExtent; vtkIdType *increments = this->GridIncrements; double scale = this->DisplacementScale; double point[3]; double displacement[3]; // convert the inPoint to i,j,k indices plus fractions point[0] = (inPoint[0] - origin[0])/spacing[0]; point[1] = (inPoint[1] - origin[1])/spacing[1]; point[2] = (inPoint[2] - origin[2])/spacing[2]; this->CalculateSpline(point,displacement,derivative, gridPtr,extent,increments, this->BorderMode); for (int i = 0; i < 3; i++) { derivative[i][0] = derivative[i][0]*scale/spacing[0]; derivative[i][1] = derivative[i][1]*scale/spacing[1]; derivative[i][2] = derivative[i][2]*scale/spacing[2]; derivative[i][i] += 1.0; } outPoint[0] = inPoint[0] + displacement[0]*scale; outPoint[1] = inPoint[1] + displacement[1]*scale; outPoint[2] = inPoint[2] + displacement[2]*scale; } //---------------------------------------------------------------------------- // convert double to double void vtkBSplineTransform::ForwardTransformDerivative(const float point[3], float output[3], float derivative[3][3]) { double fpoint[3]; double fderivative[3][3]; fpoint[0] = point[0]; fpoint[1] = point[1]; fpoint[2] = point[2]; this->ForwardTransformDerivative(fpoint,fpoint,fderivative); for (int i = 0; i < 3; i++) { derivative[i][0] = static_cast<float>(fderivative[i][0]); derivative[i][1] = static_cast<float>(fderivative[i][1]); derivative[i][2] = static_cast<float>(fderivative[i][2]); output[i] = static_cast<float>(fpoint[i]); } } //---------------------------------------------------------------------------- // We use Newton's method to iteratively invert the transformation. // This is actally quite robust as long as the Jacobian matrix is never // singular. // Note that this is similar to vtkWarpTransform::InverseTransformPoint() // but has been optimized specifically for uniform grid transforms. void vtkBSplineTransform::InverseTransformDerivative(const double inPoint[3], double outPoint[3], double derivative[3][3]) { if (!this->GridPointer || !this->CalculateSpline) { outPoint[0] = inPoint[0]; outPoint[1] = inPoint[1]; outPoint[2] = inPoint[2]; return; } void *gridPtr = this->GridPointer; double *spacing = this->GridSpacing; double *origin = this->GridOrigin; int *extent = this->GridExtent; vtkIdType *increments = this->GridIncrements; double invSpacing[3]; invSpacing[0] = 1.0/spacing[0]; invSpacing[1] = 1.0/spacing[1]; invSpacing[2] = 1.0/spacing[2]; double scale = this->DisplacementScale; double point[3], inverse[3], lastInverse[3]; double deltaP[3], deltaI[3]; double functionValue = 0; double functionDerivative = 0; double lastFunctionValue = VTK_DOUBLE_MAX; double errorSquared = 0.0; double toleranceSquared = this->InverseTolerance; toleranceSquared *= toleranceSquared; double f = 1.0; double a; // convert the inPoint to i,j,k indices plus fractions point[0] = (inPoint[0] - origin[0])*invSpacing[0]; point[1] = (inPoint[1] - origin[1])*invSpacing[1]; point[2] = (inPoint[2] - origin[2])*invSpacing[2]; // first guess at inverse point, just subtract displacement // (the inverse point is given in i,j,k indices plus fractions) this->CalculateSpline(point, deltaP, 0, gridPtr, extent, increments, this->BorderMode); inverse[0] = point[0] - deltaP[0]*scale*invSpacing[0]; inverse[1] = point[1] - deltaP[1]*scale*invSpacing[1]; inverse[2] = point[2] - deltaP[2]*scale*invSpacing[2]; lastInverse[0] = inverse[0]; lastInverse[1] = inverse[1]; lastInverse[2] = inverse[2]; // do a maximum 500 iterations, usually less than 10 are required int n = this->InverseIterations; int i, j; for (i = 0; i < n; i++) { this->CalculateSpline(inverse, deltaP, derivative, gridPtr, extent, increments, this->BorderMode); // convert displacement deltaP[0] = (inverse[0] - point[0])*spacing[0] + deltaP[0]*scale; deltaP[1] = (inverse[1] - point[1])*spacing[1] + deltaP[1]*scale; deltaP[2] = (inverse[2] - point[2])*spacing[2] + deltaP[2]*scale; // convert derivative for (j = 0; j < 3; j++) { derivative[j][0] = derivative[j][0]*scale*invSpacing[0]; derivative[j][1] = derivative[j][1]*scale*invSpacing[1]; derivative[j][2] = derivative[j][2]*scale*invSpacing[2]; derivative[j][j] += 1.0; } // get the current function value functionValue = (deltaP[0]*deltaP[0] + deltaP[1]*deltaP[1] + deltaP[2]*deltaP[2]); // if the function value is decreasing, do next Newton step if (i == 0 || functionValue < lastFunctionValue) { // here is the critical step in Newton's method vtkMath::LinearSolve3x3(derivative,deltaP,deltaI); // get the error value in the output coord space errorSquared = (deltaI[0]*deltaI[0] + deltaI[1]*deltaI[1] + deltaI[2]*deltaI[2]); // break if less than tolerance in both coordinate systems if (errorSquared < toleranceSquared && functionValue < toleranceSquared) { break; } // save the last inverse point lastInverse[0] = inverse[0]; lastInverse[1] = inverse[1]; lastInverse[2] = inverse[2]; // save error at last inverse point lastFunctionValue = functionValue; // derivative of functionValue at last inverse point functionDerivative = (deltaP[0]*derivative[0][0]*deltaI[0] + deltaP[1]*derivative[1][1]*deltaI[1] + deltaP[2]*derivative[2][2]*deltaI[2])*2; // calculate new inverse point inverse[0] -= deltaI[0]*invSpacing[0]; inverse[1] -= deltaI[1]*invSpacing[1]; inverse[2] -= deltaI[2]*invSpacing[2]; // reset f to 1.0 f = 1.0; continue; } // the error is increasing, so take a partial step // (see Numerical Recipes 9.7 for rationale, this code // is a simplification of the algorithm provided there) // quadratic approximation to find best fractional distance a = -functionDerivative/(2*(functionValue - lastFunctionValue - functionDerivative)); // clamp to range [0.1,0.5] f *= (a < 0.1 ? 0.1 : (a > 0.5 ? 0.5 : a)); // re-calculate inverse using fractional distance inverse[0] = lastInverse[0] - f*deltaI[0]*invSpacing[0]; inverse[1] = lastInverse[1] - f*deltaI[1]*invSpacing[1]; inverse[2] = lastInverse[2] - f*deltaI[2]*invSpacing[2]; } if (i >= n) { // didn't converge: back up to last good result inverse[0] = lastInverse[0]; inverse[1] = lastInverse[1]; inverse[2] = lastInverse[2]; vtkWarningMacro("InverseTransformPoint: no convergence (" << inPoint[0] << ", " << inPoint[1] << ", " << inPoint[2] << ") error = " << sqrt(errorSquared) << " after " << i << " iterations."); } // convert point outPoint[0] = inverse[0]*spacing[0] + origin[0]; outPoint[1] = inverse[1]*spacing[1] + origin[1]; outPoint[2] = inverse[2]*spacing[2] + origin[2]; } //---------------------------------------------------------------------------- // convert double to double and back again void vtkBSplineTransform::InverseTransformDerivative(const float point[3], float output[3], float derivative[3][3]) { double fpoint[3]; double fderivative[3][3]; fpoint[0] = point[0]; fpoint[1] = point[1]; fpoint[2] = point[2]; this->InverseTransformDerivative(fpoint,fpoint,fderivative); for (int i = 0; i < 3; i++) { output[i] = static_cast<float>(fpoint[i]); derivative[i][0] = static_cast<float>(fderivative[i][0]); derivative[i][1] = static_cast<float>(fderivative[i][1]); derivative[i][2] = static_cast<float>(fderivative[i][2]); } } //---------------------------------------------------------------------------- void vtkBSplineTransform::InverseTransformPoint(const double point[3], double output[3]) { // the derivative won't be used, but it is required for Newton's method double derivative[3][3]; this->InverseTransformDerivative(point,output,derivative); } //---------------------------------------------------------------------------- // convert double to double and back again void vtkBSplineTransform::InverseTransformPoint(const float point[3], float output[3]) { double fpoint[3]; double fderivative[3][3]; fpoint[0] = point[0]; fpoint[1] = point[1]; fpoint[2] = point[2]; this->InverseTransformDerivative(fpoint,fpoint,fderivative); output[0] = static_cast<float>(fpoint[0]); output[1] = static_cast<float>(fpoint[1]); output[2] = static_cast<float>(fpoint[2]); } //---------------------------------------------------------------------------- void vtkBSplineTransform::InternalDeepCopy(vtkAbstractTransform *transform) { vtkBSplineTransform *gridTransform = (vtkBSplineTransform *)transform; this->SetInverseTolerance(gridTransform->InverseTolerance); this->SetInverseIterations(gridTransform->InverseIterations); this->CalculateSpline = gridTransform->CalculateSpline; this->ConnectionHolder->SetInputConnection( 0, gridTransform->ConnectionHolder->GetNumberOfInputConnections(0) ? gridTransform->ConnectionHolder->GetInputConnection(0, 0) : 0); this->SetDisplacementScale(gridTransform->DisplacementScale); this->SetBorderMode(gridTransform->BorderMode); if (this->InverseFlag != gridTransform->InverseFlag) { this->InverseFlag = gridTransform->InverseFlag; this->Modified(); } } //---------------------------------------------------------------------------- void vtkBSplineTransform::InternalUpdate() { vtkImageData *grid = this->GetCoefficientData(); this->GridPointer = 0; if (grid == 0) { return; } vtkAlgorithm* inputAlgorithm = this->ConnectionHolder->GetInputAlgorithm(0, 0); inputAlgorithm->Update(); // In case output changed. grid = this->GetCoefficientData(); if (grid->GetNumberOfScalarComponents() != 3) { vtkErrorMacro(<< "TransformPoint: displacement grid must have 3 components"); return; } // get the correct spline calculation function according to the grid type switch (grid->GetScalarType()) { case VTK_FLOAT: this->CalculateSpline = &(vtkBSplineTransformFunction<float>::Cubic); break; case VTK_DOUBLE: this->CalculateSpline = &(vtkBSplineTransformFunction<double>::Cubic); break; default: this->CalculateSpline = 0; vtkErrorMacro("InternalUpdate: grid type must be float or double"); break; } this->GridPointer = grid->GetScalarPointer(); grid->GetSpacing(this->GridSpacing); grid->GetOrigin(this->GridOrigin); grid->GetExtent(this->GridExtent); grid->GetIncrements(this->GridIncrements); } //---------------------------------------------------------------------------- vtkAbstractTransform *vtkBSplineTransform::MakeTransform() { return vtkBSplineTransform::New(); } //---------------------------------------------------------------------------- void vtkBSplineTransform::SetCoefficientConnection( vtkAlgorithmOutput* output) { this->ConnectionHolder->SetInputConnection(output); } //---------------------------------------------------------------------------- void vtkBSplineTransform::SetCoefficientData(vtkImageData* grid) { vtkTrivialProducer* tp = vtkTrivialProducer::New(); tp->SetOutput(grid); this->SetCoefficientConnection(tp->GetOutputPort()); tp->Delete(); } //---------------------------------------------------------------------------- vtkImageData* vtkBSplineTransform::GetCoefficientData() { return vtkImageData::SafeDownCast( this->ConnectionHolder->GetInputDataObject(0, 0)); }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * \file graph_executor.cc */ #include "graph_executor.h" #include <tvm/runtime/container/map.h> #include <tvm/runtime/container/string.h> #include <tvm/runtime/data_type.h> #include <tvm/runtime/device_api.h> #include <tvm/runtime/ndarray.h> #include <tvm/runtime/packed_func.h> #include <tvm/runtime/profiling.h> #include <tvm/runtime/registry.h> #include <tvm/runtime/serializer.h> #include <algorithm> #include <functional> #include <memory> #include <numeric> #include <string> #include <unordered_set> #include <utility> #include <vector> #include "../file_utils.h" namespace tvm { namespace runtime { namespace details { inline size_t GetDataAlignment(const DLTensor& arr) { size_t align = (arr.dtype.bits / 8) * arr.dtype.lanes; if (align < kAllocAlignment) return kAllocAlignment; return align; } } // namespace details /*! * \brief Run all the operations one by one. */ void GraphExecutor::Run() { // setup the array and requirements. for (size_t i = 0; i < op_execs_.size(); ++i) { if (op_execs_[i]) op_execs_[i](); } } /*! * \brief Initialize the graph executor with graph and device. * \param graph_json The execution graph. * \param module The module containing the compiled functions for the host * processor. * \param devs The devices of the host and devices where graph nodes will be * executed on. * \param lookup_linked_param_func Linked parameter lookup function. Default is nullptr. */ void GraphExecutor::Init(const std::string& graph_json, tvm::runtime::Module module, const std::vector<Device>& devs, const PackedFunc lookup_linked_param_func) { std::istringstream is(graph_json); dmlc::JSONReader reader(&is); this->Load(&reader); module_ = module; devices_ = devs; lookup_linked_param_ = lookup_linked_param_func; if (lookup_linked_param_ == nullptr) { lookup_linked_param_ = PackedFunc( [this](TVMArgs args, TVMRetValue* rv) { this->DefaultLookupLinkedParam(args, rv); }); } this->SetupStorage(); this->SetupOpExecs(); for (size_t i = 0; i < input_nodes_.size(); i++) { const uint32_t nid = input_nodes_[i]; std::string& name = nodes_[nid].name; input_map_[name] = i; } for (size_t i = 0; i < outputs_.size(); i++) { const uint32_t nid = outputs_[i].node_id; std::string& name = nodes_[nid].name; output_map_[name] = i; } } /*! * \brief Get the input index given the name of input. * \param name The name of the input. * \return The index of input. */ int GraphExecutor::GetInputIndex(const std::string& name) { auto it = input_map_.find(name); if (it != input_map_.end()) { return it->second; } return -1; } /*! * \brief Get the input info of Graph by parsing the input nodes. * \return The shape and dtype tuple. */ std::tuple<GraphExecutor::ShapeInfo, GraphExecutor::DtypeInfo> GraphExecutor::GetInputInfo() const { GraphExecutor::ShapeInfo shape_dict; GraphExecutor::DtypeInfo dtype_dict; for (uint32_t nid : input_nodes_) { CHECK_LE(nid, nodes_.size()); std::string name = nodes_[nid].name; if (param_names_.find(name) == param_names_.end()) { CHECK_LE(nid, attrs_.shape.size()); auto shape = attrs_.shape[nid]; shape_dict.Set(name, ShapeTuple(shape)); CHECK_LE(nid, attrs_.dltype.size()); auto dtype = attrs_.dltype[nid]; dtype_dict.Set(name, String(dtype)); } } return std::make_tuple(shape_dict, dtype_dict); } /*! * \brief Get the output index given the name of output. * \param name The name of the output. * \return The index of output. */ int GraphExecutor::GetOutputIndex(const std::string& name) { auto it = output_map_.find(name); if (it != output_map_.end()) { return it->second; } return -1; } /*! * \brief set index-th input to the graph. * \param index The input index. * \param data_in The input data. */ void GraphExecutor::SetInput(int index, DLTensor* data_in) { ICHECK_LT(static_cast<size_t>(index), input_nodes_.size()); uint32_t eid = this->entry_id(input_nodes_[index], 0); data_entry_[eid].CopyFrom(data_in); } /*! * \brief Check the legality of external DLTensor*. * \param external The external DLTensor*. * \param eid The data_enrty_ index. */ void GraphExecutor::CheckExternalDLTensor(const DLTensor* external, uint32_t eid) const { const DLTensor* internal = data_entry_[eid].operator->(); ICHECK_EQ(data_alignment_[eid], details::GetDataAlignment(*external)); ICHECK_EQ(reinterpret_cast<size_t>(external->data) % kAllocAlignment, 0); ICHECK_EQ(internal->ndim, static_cast<size_t>(external->ndim)); ICHECK_EQ(internal->device.device_type, external->device.device_type); ICHECK_EQ(internal->device.device_id, external->device.device_id); for (auto i = 0; i < external->ndim; ++i) { ICHECK_EQ(internal->shape[i], external->shape[i]); } } /*! * \brief set index-th input to the graph without copying the data. * \param index The input index. * \param data_ref The input data that is referred. */ void GraphExecutor::SetInputZeroCopy(int index, DLTensor* data_ref) { ICHECK_LT(static_cast<size_t>(index), input_nodes_.size()); uint32_t eid = this->entry_id(input_nodes_[index], 0); // check the consistency of input CheckExternalDLTensor(data_ref, eid); // Update the data pointer for each argument of each op for (DLTensor* t : input_dltensors_[eid]) { t->data = data_ref->data; } } /*! * \brief set index-th output to the graph without copying the data. * \param index The output index. * \param data_ref The output data that is referred. */ void GraphExecutor::SetOutputZeroCopy(int index, DLTensor* data_ref) { ICHECK_LT(static_cast<size_t>(index), outputs_.size()); ICHECK_LT(static_cast<size_t>(index), output_dltensors_.size()); const NodeEntry& output_node = outputs_[index]; uint32_t output_node_eid = this->entry_id(output_node); // check the consistency of output CheckExternalDLTensor(data_ref, output_node_eid); // Update the data pointer for output op for (DLTensor* t : output_dltensors_[output_node_eid]) { t->data = data_ref->data; } // Update the input of the op connected to the output for (DLTensor* t : both_output_opinput_dltensors_[output_node_eid]) { t->data = data_ref->data; } } /*! * \brief Get the number of outputs * * \return The number of outputs from graph. */ int GraphExecutor::NumOutputs() const { return outputs_.size(); } /*! * \brief Get the number of inputs * * \return The number of inputs to the graph. */ int GraphExecutor::NumInputs() const { return input_nodes_.size(); } /*! * \brief Return NDArray for given input index. * \param index The input index. * * \return NDArray corresponding to given input node index. */ NDArray GraphExecutor::GetInput(int index) const { ICHECK_LT(static_cast<size_t>(index), input_nodes_.size()); uint32_t eid = this->entry_id(input_nodes_[index], 0); return data_entry_[eid]; } /*! * \brief Return NDArray for given output index. * \param index The output index. * * \return NDArray corresponding to given output node index. */ NDArray GraphExecutor::GetOutput(int index) const { ICHECK_LT(static_cast<size_t>(index), outputs_.size()); uint32_t eid = this->entry_id(outputs_[index]); return data_entry_[eid]; } /*! * \brief Copy index-th output to data_out. * \param index The output index. * \param data_out the output data. */ void GraphExecutor::CopyOutputTo(int index, DLTensor* data_out) { ICHECK_LT(static_cast<size_t>(index), outputs_.size()); uint32_t eid = this->entry_id(outputs_[index]); // Check the shapes to avoid receiving in different dimension but same size. const NDArray& data = data_entry_[eid]; ICHECK_EQ(data->ndim, data_out->ndim); for (int32_t j = 0; j < data->ndim; ++j) { ICHECK_EQ(data->shape[j], data_out->shape[j]); } data_entry_[eid].CopyTo(data_out); } /*! * \brief Load parameters from parameter blob. * \param param_blob A binary blob of parameter. */ void GraphExecutor::LoadParams(const std::string& param_blob) { dmlc::MemoryStringStream strm(const_cast<std::string*>(&param_blob)); this->LoadParams(&strm); } void GraphExecutor::LoadParams(dmlc::Stream* strm) { Map<String, NDArray> params = ::tvm::runtime::LoadParams(strm); for (auto& p : params) { param_names_.insert(p.first); int in_idx = GetInputIndex(p.first); if (in_idx < 0) continue; uint32_t eid = this->entry_id(input_nodes_[in_idx], 0); data_entry_[eid].CopyFrom(p.second); } } void GraphExecutor::ShareParams(const GraphExecutor& other, dmlc::Stream* strm) { uint64_t header, reserved; ICHECK(strm->Read(&header)) << "Invalid parameters file format"; ICHECK(header == kTVMNDArrayListMagic) << "Invalid parameters file format"; ICHECK(strm->Read(&reserved)) << "Invalid parameters file format"; std::vector<std::string> names; ICHECK(strm->Read(&names)) << "Invalid parameters file format"; uint64_t sz; strm->Read(&sz); size_t size = static_cast<size_t>(sz); ICHECK(size == names.size()) << "Invalid parameters file format"; for (size_t i = 0; i < size; ++i) { int in_idx = GetInputIndex(names[i]); if (in_idx < 0) continue; uint32_t eid = this->entry_id(input_nodes_[in_idx], 0); ICHECK_LT(eid, data_entry_.size()); ICHECK_EQ(data_entry_[eid].use_count(), 1); data_entry_[eid] = other.GetInput(GetInputIndex(names[i])); ICHECK_GT(data_entry_[eid].use_count(), 1); const DLTensor* tmp = data_entry_[eid].operator->(); data_alignment_[eid] = details::GetDataAlignment(*tmp); } this->SetupOpExecs(); } void GraphExecutor::LinkedNDArrayDeleter(Object* container) { // container is the NDArray::Container which needs to get deleted. // The data member points to global const memory, so it does not need deleting. delete static_cast<NDArray::Container*>(container); } void GraphExecutor::DefaultLookupLinkedParam(TVMArgs args, TVMRetValue* rv) { Module mod = args[0]; int64_t storage_id = args[1]; DLTensor* template_tensor = args[2]; Device dev = args[3]; // Get pre-linked parameter lookup function, if it was generated. When pf == nullptr, no linked // params are present. if (!module_lookup_linked_param_valid_) { module_lookup_linked_param_ = mod.GetFunction(::tvm::runtime::symbol::tvm_lookup_linked_param, true); } if (module_lookup_linked_param_ == nullptr) { *rv = nullptr; return; } TVMRetValue opaque_handle = module_lookup_linked_param_(storage_id); if (opaque_handle.type_code() == kTVMNullptr) { *rv = nullptr; return; } std::vector<int64_t> shape_vec{template_tensor->shape, template_tensor->shape + template_tensor->ndim}; auto* container = new NDArray::Container(static_cast<void*>(opaque_handle), shape_vec, template_tensor->dtype, dev); container->SetDeleter(GraphExecutor::LinkedNDArrayDeleter); *rv = NDArray(GetObjectPtr<Object>(container)); } void GraphExecutor::SetupStorage() { // Grab saved optimization plan from graph. std::vector<DLDataType> vtype; for (const std::string& s_type : attrs_.dltype) { vtype.push_back(tvm::runtime::String2DLDataType(s_type)); } // Size and device type of each storage pool entry. std::vector<PoolEntry> pool_entry; // Find the maximum space size. for (size_t i = 0; i < attrs_.shape.size(); ++i) { int storage_id = attrs_.storage_id[i]; // Use the fallback device if no device index is available. int device_type = static_cast<int>(devices_[0].device_type); if (!attrs_.device_index.empty()) { device_type = attrs_.device_index[i]; } size_t size = 1; for (int64_t sz : attrs_.shape[i]) { size *= static_cast<size_t>(sz); } ICHECK_GE(storage_id, 0) << "Do not support runtime shape op"; DLDataType t = vtype[i]; size_t bits = t.bits * t.lanes; ICHECK(bits % 8U == 0U || bits == 1U || bits == 4U); size_t bytes = ((bits + 7U) / 8U) * size; uint32_t sid = static_cast<uint32_t>(storage_id); if (sid >= pool_entry.size()) { pool_entry.resize(sid + 1, {0, -1}); } else { ICHECK(pool_entry[sid].device_type == -1 || pool_entry[sid].device_type == device_type) << "The same pool entry cannot be assigned to multiple devices"; } TVMRetValue lookup_rv; { std::vector<int64_t> shape_vec{attrs_.shape[i].begin(), attrs_.shape[i].end()}; DLTensor template_tensor{nullptr, Device{kDLCPU, 0}, static_cast<int>(shape_vec.size()), vtype[i], shape_vec.data(), nullptr, 0}; lookup_rv = lookup_linked_param_(module_, sid, &template_tensor, devices_[0]); } if (lookup_rv.type_code() != kTVMNullptr) { pool_entry[sid].linked_param = lookup_rv; } pool_entry[sid].param_data_entry = i; pool_entry[sid].size = std::max(pool_entry[sid].size, bytes); pool_entry[sid].device_type = device_type; } // Allocate the space. for (const auto& pit : pool_entry) { // This for loop is very fast since there are usually only a couple of // devices available on the same hardware. const auto& cit = std::find_if(devices_.begin(), devices_.end(), [&pit](const Device& d) { return pit.device_type == static_cast<int>(d.device_type); }); Device dev = cit == devices_.end() ? devices_[0] : *cit; if (pit.linked_param.defined()) { storage_pool_.push_back(pit.linked_param); } else { std::vector<int64_t> shape; shape.push_back(static_cast<int64_t>(pit.size + 3) / 4); storage_pool_.push_back(NDArray::Empty(shape, DLDataType{kDLFloat, 32, 1}, dev)); } } // Assign the pooled entries. A unified memory pool is used to simplifiy // memory assignment for each node entry. The allocated memory on each device // is mapped to this pool. data_entry_.resize(num_node_entries()); data_alignment_.resize(num_node_entries()); for (size_t i = 0; i < data_entry_.size(); ++i) { int storage_id = attrs_.storage_id[i]; ICHECK_LT(static_cast<size_t>(storage_id), storage_pool_.size()); data_entry_[i] = storage_pool_[storage_id].CreateView(attrs_.shape[i], vtype[i]); const DLTensor* tmp = data_entry_[i].operator->(); data_alignment_[i] = details::GetDataAlignment(*tmp); } } void GraphExecutor::SetupOpExecs() { op_execs_.resize(this->GetNumOfNodes()); input_dltensors_.resize(num_node_entries()); output_dltensors_.resize(num_node_entries()); both_output_opinput_dltensors_.resize(num_node_entries()); std::unordered_set<uint32_t> input_node_eids; for (size_t i = 0; i < input_nodes_.size(); i++) { uint32_t nid = input_nodes_[i]; input_node_eids.insert(entry_id(nid, 0)); } std::unordered_set<uint32_t> output_node_eids; for (size_t i = 0; i < outputs_.size(); i++) { output_node_eids.insert(entry_id(outputs_[i])); } // setup the array and requirements. for (uint32_t nid = 0; nid < this->GetNumOfNodes(); ++nid) { const auto& inode = nodes_[nid]; if (inode.op_type == "null") continue; std::vector<DLTensor> args; for (const auto& e : inode.inputs) { uint32_t eid = this->entry_id(e); args.push_back(*(data_entry_[eid].operator->())); } for (uint32_t index = 0; index < inode.param.num_outputs; ++index) { uint32_t eid = this->entry_id(nid, index); args.push_back(*(data_entry_[eid].operator->())); } ICHECK(inode.op_type == "tvm_op") << "Can only take tvm_op as op"; std::shared_ptr<OpArgs> op_args = nullptr; std::tie(op_execs_[nid], op_args) = CreateTVMOp(inode.param, args); for (size_t i = 0; i < inode.inputs.size(); i++) { uint32_t input_eid = this->entry_id(inode.inputs[i]); // check if op input is model input if (input_node_eids.count(input_eid) > 0) { input_dltensors_[input_eid].push_back( static_cast<DLTensor*>(op_args->arg_values[i].v_handle)); } // check if any model output is the input of the op if (output_node_eids.count(input_eid) > 0) { both_output_opinput_dltensors_[input_eid].push_back( static_cast<DLTensor*>(op_args->arg_values[i].v_handle)); } } for (uint32_t i = inode.inputs.size(); i < inode.inputs.size() + inode.param.num_outputs; ++i) { uint32_t output_eid = this->entry_id(nid, i - inode.inputs.size()); // check if op output is model output if (output_node_eids.count(output_eid) > 0) { output_dltensors_[output_eid].push_back( static_cast<DLTensor*>(op_args->arg_values[i].v_handle)); } } } } std::pair<std::function<void()>, std::shared_ptr<GraphExecutor::OpArgs> > GraphExecutor::CreateTVMOp(const TVMOpParam& param, const std::vector<DLTensor>& args) { std::shared_ptr<GraphExecutor::OpArgs> arg_ptr = std::make_shared<GraphExecutor::OpArgs>(); // setup address. arg_ptr->args = args; if (param.flatten_data) { arg_ptr->shape_data.resize(arg_ptr->args.size()); } for (size_t i = 0; i < arg_ptr->args.size(); ++i) { TVMValue v; DLTensor* t = &arg_ptr->args[i]; v.v_handle = t; arg_ptr->arg_values.push_back(v); arg_ptr->arg_tcodes.push_back(kTVMDLTensorHandle); if (param.flatten_data) { arg_ptr->shape_data[i] = std::accumulate(t->shape, t->shape + t->ndim, 1, std::multiplies<int64_t>()); t->ndim = 1; t->shape = &(arg_ptr->shape_data[i]); } } if (param.func_name == "__nop") { return {[]() {}, arg_ptr}; } else if (param.func_name == "__copy") { // Perform cross device data copy. // Directly copy data from the input to the output. // TODO(mbs): device_copy cleanup. auto fexec = [arg_ptr]() { DLTensor* from = static_cast<DLTensor*>(arg_ptr->arg_values[0].v_handle); DLTensor* to = static_cast<DLTensor*>(arg_ptr->arg_values[1].v_handle); TVM_CCALL(TVMArrayCopyFromTo(from, to, nullptr)); }; return {fexec, arg_ptr}; } // Get compiled function from the module that contains both host and device // code. tvm::runtime::PackedFunc pf = module_.GetFunction(param.func_name, true); ICHECK(pf != nullptr) << "no such function in module: " << param.func_name; auto fexec = [arg_ptr, pf]() { TVMRetValue rv; TVMArgs targs(arg_ptr->arg_values.data(), arg_ptr->arg_tcodes.data(), static_cast<int>(arg_ptr->arg_values.size())); pf.CallPacked(targs, &rv); }; return {fexec, arg_ptr}; } PackedFunc GraphExecutor::GetFunction(const std::string& name, const ObjectPtr<Object>& sptr_to_self) { // Return member functions during query. if (name == "set_input") { return PackedFunc([sptr_to_self, this](TVMArgs args, TVMRetValue* rv) { if (String::CanConvertFrom(args[0])) { int in_idx = this->GetInputIndex(args[0].operator String()); if (in_idx >= 0) this->SetInput(in_idx, args[1]); } else { this->SetInput(args[0], args[1]); } }); } else if (name == "set_input_zero_copy") { return PackedFunc([sptr_to_self, this](TVMArgs args, TVMRetValue* rv) { if (String::CanConvertFrom(args[0])) { int in_idx = this->GetInputIndex(args[0].operator String()); if (in_idx >= 0) this->SetInputZeroCopy(in_idx, args[1]); } else { this->SetInputZeroCopy(args[0], args[1]); } }); } else if (name == "set_output_zero_copy") { return PackedFunc([sptr_to_self, this](TVMArgs args, TVMRetValue* rv) { if (String::CanConvertFrom(args[0])) { int out_idx = this->GetOutputIndex(args[0].operator String()); if (out_idx >= 0) this->SetOutputZeroCopy(out_idx, args[1]); } else { this->SetOutputZeroCopy(args[0], args[1]); } }); } else if (name == "get_output") { return PackedFunc([sptr_to_self, this](TVMArgs args, TVMRetValue* rv) { if (args.num_args == 2) { this->CopyOutputTo(args[0], args[1]); } else { *rv = this->GetOutput(args[0]); } }); } else if (name == "get_input") { return PackedFunc([sptr_to_self, this](TVMArgs args, TVMRetValue* rv) { int in_idx = 0; if (String::CanConvertFrom(args[0])) { in_idx = this->GetInputIndex(args[0].operator String()); } else { in_idx = args[0]; } if (in_idx >= 0) { *rv = this->GetInput(in_idx); } }); } else if (name == "get_num_outputs") { return PackedFunc( [sptr_to_self, this](TVMArgs args, TVMRetValue* rv) { *rv = this->NumOutputs(); }); } else if (name == "get_num_inputs") { return PackedFunc( [sptr_to_self, this](TVMArgs args, TVMRetValue* rv) { *rv = this->NumInputs(); }); } else if (name == "run") { return PackedFunc([sptr_to_self, this](TVMArgs args, TVMRetValue* rv) { this->Run(); }); } else if (name == "run_from_inputs") { return PackedFunc( [sptr_to_self, this](TVMArgs args, TVMRetValue* rv) { CHECK(args.size() % 2 == 0) << "Number of arguments to run_from_inputs must be an even number of key-value pairs"; Device host{static_cast<DLDeviceType>(args[0].operator int()), args[1].operator int()}; for (int i = 2; i < args.size(); i += 2) { if (String::CanConvertFrom(args[i])) { int in_idx = this->GetInputIndex(args[i].operator String()); if (in_idx >= 0) { this->SetInput(in_idx, args[i + 1]); } else { LOG(FATAL) << args[i].operator String() << " is not a valid input name"; } } else { this->SetInput(args[i], args[i + 1]); } } this->Run(); Array<NDArray> outputs; for (int i = 0; i < this->NumOutputs(); i++) { NDArray out = this->GetOutput(i); NDArray a = NDArray::Empty(out.Shape(), out.DataType(), host); a.CopyFrom(out); outputs.push_back(a); } *rv = outputs; }); } else if (name == "load_params") { return PackedFunc([sptr_to_self, this](TVMArgs args, TVMRetValue* rv) { this->LoadParams(args[0].operator std::string()); }); } else if (name == "share_params") { return PackedFunc([sptr_to_self, this](TVMArgs args, TVMRetValue* rv) { const auto& module = args[0].operator Module(); ICHECK_EQ(module.operator->()->type_key(), std::string("GraphExecutor")); const auto& param_blob = args[1].operator std::string(); dmlc::MemoryStringStream strm(const_cast<std::string*>(&param_blob)); this->ShareParams(dynamic_cast<const GraphExecutor&>(*module.operator->()), &strm); }); } else if (name == "get_input_index") { return PackedFunc([sptr_to_self, this](TVMArgs args, TVMRetValue* rv) { CHECK(String::CanConvertFrom(args[0])) << "Input key is not a string"; *rv = this->GetInputIndex(args[0].operator String()); }); } else if (name == "get_input_info") { return PackedFunc([sptr_to_self, this](TVMArgs args, TVMRetValue* rv) { GraphExecutor::ShapeInfo shape_info; GraphExecutor::DtypeInfo dtype_info; std::tie(shape_info, dtype_info) = this->GetInputInfo(); Map<String, ObjectRef> input_info; input_info.Set("shape", shape_info); input_info.Set("dtype", dtype_info); *rv = input_info; }); } else { return PackedFunc(); } } Module GraphExecutorCreate(const std::string& sym_json, const tvm::runtime::Module& m, const std::vector<Device>& devs, const PackedFunc lookup_linked_param_func) { auto exec = make_object<GraphExecutor>(); exec->Init(sym_json, m, devs, lookup_linked_param_func); return Module(exec); } // Get all devices for the host and other runtime devices. std::vector<Device> GetAllDevice(const TVMArgs& args, int dev_start_arg) { // Reserve the first item as the fallback device. std::vector<Device> ret; Device dev; for (int i = dev_start_arg; i < args.num_args; i += 2) { int dev_type = args[i]; dev.device_type = static_cast<DLDeviceType>(dev_type); dev.device_id = args[i + 1]; ret.push_back(dev); } return ret; } // 4-argument version is currently reserved to keep support of calling // from tvm4j and javascript, since they don't have heterogeneous // execution support yet. For heterogenenous execution, at least 5 arguments will // be passed in. The third one is the number of devices. // Eventually, we will only probably pass Device for all the languages. TVM_REGISTER_GLOBAL("tvm.graph_executor.create").set_body([](TVMArgs args, TVMRetValue* rv) { ICHECK_GE(args.num_args, 4) << "The expected number of arguments for graph_executor.create is " "at least 4, but it has " << args.num_args; PackedFunc lookup_linked_param_func; int dev_start_arg = 2; if (args[2].type_code() == kTVMPackedFuncHandle) { lookup_linked_param_func = args[2]; dev_start_arg++; } const auto& devices = GetAllDevice(args, dev_start_arg); *rv = GraphExecutorCreate(args[0], args[1], devices, lookup_linked_param_func); }); } // namespace runtime } // namespace tvm
/*============================================================================= NifTK: A software platform for medical image computing. Copyright (c) University College London (UCL). All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt in the top level directory for details. =============================================================================*/ #ifndef __itkVnlIterationUpdateCommand_cxx #define __itkVnlIterationUpdateCommand_cxx #include <sstream> #include "itkVnlIterationUpdateCommand.h" #include <itkUCLMacro.h> namespace itk { /** * Constructor. */ VnlIterationUpdateCommand::VnlIterationUpdateCommand() { niftkitkDebugMacro("VnlIterationUpdateCommand():Constructed"); } void VnlIterationUpdateCommand::DoExecute(const itk::Object * object, const itk::EventObject & event) { if( ! itk::IterationEvent().CheckEvent( &event ) ) { return; } OptimizerPointer optimizer; try { optimizer = dynamic_cast< OptimizerPointer >( object ); } catch( std::exception & err ) { std::string msg = "Failed to dynamic_cast optimizer"; niftkitkErrorMacro(<< msg); throw err; } if (optimizer == 0) { std::string msg = "Failed to cast optimizer, pointer is null"; niftkitkErrorMacro(<< msg); } // To track registraiton, we used the cached value. // When the VNL optimizer exits, it sets the normal // values so GetCurrentValue and GetCurrentPosition will work. ParametersType parameters = optimizer->GetCachedCurrentPosition(); MeasureType measure = optimizer->GetCachedValue(); if (parameters.GetSize() > 20) { niftkitkInfoMacro(<<"DoExecute():" << measure ); } else { niftkitkInfoMacro(<<"DoExecute():" << measure << " : " << parameters); } } } // end namespace #endif
// System Includes #include <string.h> // 3rdParty Includes #include "catch2/catch.hpp" #include "kirke/string.h" #include "kirke/system_allocator.h" // Internal Includes #include "word_search/grid.h" class WordSearch__Grid__TestFixture { protected: WordSearch__Grid__TestFixture(){ system_allocator__initialize( &system_allocator, NULL ); String* entries = string__clone( &ENTRIES, system_allocator.allocator ); word_search__grid__initialize( &grid, system_allocator.allocator, GRID_DIM, GRID_DIM, entries ); allocator__free( system_allocator.allocator, entries ); } ~WordSearch__Grid__TestFixture(){ word_search__grid__clear( &grid, system_allocator.allocator ); system_allocator__deinitialize( &system_allocator ); } SystemAllocator system_allocator; const long GRID_DIM = 15; String ENTRIES = { .data = (char[]) { 'U', 'M', 'K', 'H', 'U', 'L', 'K', 'I', 'N', 'V', 'J', 'O', 'C', 'W', 'E', 'L', 'L', 'S', 'H', 'K', 'Z', 'Z', 'W', 'Z', 'C', 'G', 'J', 'U', 'Y', 'G', 'H', 'S', 'U', 'P', 'J', 'P', 'R', 'J', 'D', 'H', 'S', 'B', 'X', 'T', 'G', 'B', 'R', 'J', 'S', 'O', 'E', 'Q', 'E', 'T', 'I', 'K', 'K', 'G', 'L', 'E', 'A', 'Y', 'O', 'A', 'G', 'C', 'I', 'R', 'D', 'Q', 'H', 'R', 'T', 'C', 'D', 'S', 'C', 'O', 'T', 'T', 'Y', 'K', 'Z', 'R', 'E', 'P', 'P', 'X', 'P', 'F', 'B', 'L', 'Q', 'S', 'L', 'N', 'E', 'E', 'E', 'V', 'U', 'L', 'F', 'M', 'Z', 'O', 'K', 'R', 'I', 'K', 'A', 'M', 'M', 'R', 'M', 'F', 'B', 'A', 'P', 'P', 'N', 'U', 'I', 'I', 'Y', 'H', 'Q', 'M', 'E', 'M', 'Q', 'R', 'Y', 'F', 'S', 'E', 'Y', 'Z', 'Y', 'G', 'K', 'Q', 'J', 'P', 'C', 'Q', 'W', 'Y', 'A', 'K', 'S', 'J', 'F', 'Z', 'M', 'Q', 'I', 'B', 'D', 'B', 'R', 'M', 'K', 'W', 'D', 'T', 'G', 'L', 'B', 'H', 'C', 'B', 'E', 'C', 'E', 'T', 'O', 'Y', 'I', 'F', 'O', 'J', 'Y', 'E', 'U', 'L', 'N', 'C', 'K', 'L', 'Y', 'B', 'Z', 'R', 'H', 'W', 'Z', 'M', 'I', 'S', 'U', 'K', 'I', 'R', 'B', 'I', 'D', 'O', 'X', 'S', 'K', 'Y', 'L', 'B', 'Q', 'Q', 'R', 'M', 'D', 'F', 'C', 'W', 'E', 'A', 'B' }, .length = 225, .capacity = 225, .element_size = 1 }; String WORDS[ 10 ] = { string__literal( "SCOTTY" ), string__literal( "SPOCK" ), string__literal( "BONES" ), string__literal( "UHURA" ), string__literal( "KIRK" ), string__literal( "SULU" ), string__literal( "KHAN" ), string__literal( "RIKER" ), string__literal( "WORF" ), string__literal( "ABCDEFG" ) }; WordSearch__Grid grid; }; TEST_CASE_METHOD( WordSearch__Grid__TestFixture, "word_search__grid__contains", "[word_search__grid]" ){ WordSearch__GridCoordinates current_coordinates; current_coordinates = { .row = 0, .column = 0 }; REQUIRE( word_search__grid__contains( &grid, &current_coordinates ) == 1 ); current_coordinates = { .row = 0, .column = 1 }; REQUIRE( word_search__grid__contains( &grid, &current_coordinates ) == 1 ); current_coordinates = { .row = 1, .column = 0 }; REQUIRE( word_search__grid__contains( &grid, &current_coordinates ) == 1 ); current_coordinates = { .row = 1, .column = 1 }; REQUIRE( word_search__grid__contains( &grid, &current_coordinates ) == 1 ); current_coordinates = { .row = -1, .column = 0 }; REQUIRE( word_search__grid__contains( &grid, &current_coordinates ) == 0 ); current_coordinates = { .row = 0, .column = -1 }; REQUIRE( word_search__grid__contains( &grid, &current_coordinates ) == 0 ); current_coordinates = { .row = 15, .column = 0 }; REQUIRE( word_search__grid__contains( &grid, &current_coordinates ) == 0 ); current_coordinates = { .row = 0, .column = 15 }; REQUIRE( word_search__grid__contains( &grid, &current_coordinates ) == 0 ); } TEST_CASE_METHOD( WordSearch__Grid__TestFixture, "word_search__grid__entry", "[word_search__grid]" ){ WordSearch__GridCoordinates current_coordinates; current_coordinates = { .row = 0, .column = 0 }; REQUIRE( word_search__grid__entry( &grid, &current_coordinates ) == 'U' ); current_coordinates = { .row = 0, .column = 1 }; REQUIRE( word_search__grid__entry( &grid, &current_coordinates ) == 'M' ); current_coordinates = { .row = 1, .column = 0 }; REQUIRE( word_search__grid__entry( &grid, &current_coordinates ) == 'L' ); current_coordinates = { .row = 1, .column = 1 }; REQUIRE( word_search__grid__entry( &grid, &current_coordinates ) == 'L' ); current_coordinates = { .row = 14, .column = 14 }; REQUIRE( word_search__grid__entry( &grid, &current_coordinates ) == 'B' ); current_coordinates = { .row = 15, .column = 15 }; REQUIRE( word_search__grid__entry( &grid, &current_coordinates ) == 0 ); } TEST_CASE_METHOD( WordSearch__Grid__TestFixture, "word_search__grid__lookup_sequence_entry", "[word_search__grid]" ){ WordSearch__GridSequence sequence = { .start = { .row = 0, .column = 0 }, .span = { .magnitude = 15, .direction = WordSearch__Direction__SouthEast } }; char entry; for( unsigned long entry_index = 0; entry_index < GRID_DIM; entry_index++ ){ REQUIRE( word_search__grid__lookup_sequence_entry( &grid, &sequence, entry_index, &entry ) ); REQUIRE( entry == ENTRIES.data[ entry_index * GRID_DIM + entry_index ] ); } // Test whether index >= sequence.span.magnitude returns 0. REQUIRE_FALSE( word_search__grid__lookup_sequence_entry( &grid, &sequence, GRID_DIM + 1, &entry ) ); // Test whether off-grid entries return 0. sequence.start = (WordSearch__GridCoordinates) { -1, -1 }; REQUIRE_FALSE( word_search__grid__lookup_sequence_entry( &grid, &sequence, 0, &entry ) ); // Just for fun, make sure that even if part of the sequence is off the grid, if the entry we want is on the grid, // we still get the desired value. REQUIRE( word_search__grid__lookup_sequence_entry( &grid, &sequence, 1, &entry ) ); REQUIRE( entry == ENTRIES.data[ 0 ] ); } TEST_CASE_METHOD( WordSearch__Grid__TestFixture, "word_search__grid__sequence_matches_word", "[word_search__grid]" ){ WordSearch__GridSequence sequences[] = { // SCOTTY { .start = { .row = 5, .column = 0 }, .span = { .magnitude = 6, .direction = WordSearch__Direction__East } }, // SPOCK { .start = { .row = 1, .column = 2 }, .span = { .magnitude = 5, .direction = WordSearch__Direction__SouthEast } }, // BONES { .start = { .row = 6, .column = 0 }, .span = { .magnitude = 5, .direction = WordSearch__Direction__South } }, // UHURA { .start = { .row = 0, .column = 4 }, .span = { .magnitude = 5, .direction = WordSearch__Direction__SouthWest } }, // KIRK { .start = { .row = 7, .column = 4 }, .span = { .magnitude = 4, .direction = WordSearch__Direction__West } }, // SULU { .start = { .row = 3, .column = 3 }, .span = { .magnitude = 4, .direction = WordSearch__Direction__NorthWest } }, // KHAN { .start = { .row = 9, .column = 5 }, .span = { .magnitude = 4, .direction = WordSearch__Direction__North } }, // RIKER { .start = { .row = 14, .column = 6 }, .span = { .magnitude = 5, .direction = WordSearch__Direction__NorthEast } }, // WORF { .start = { .row = 14, .column = 11 }, .span = { .magnitude = 4, .direction = WordSearch__Direction__NorthEast } } }; for( unsigned long word_index = 0; word_index < ELEMENT_COUNT( WORDS ) - 1; word_index++ ){ REQUIRE( word_search__grid__sequence_matches_word( &grid, &sequences[ word_index ], &WORDS[ word_index ] ) == 1 ); } }
/* MoTo - Motion Toolkit Copyright (c) 2006-2019 Gino van den Bergen, DTECTA Source published under the terms of the MIT License. For details please see COPYING file or visit http://opensource.org/licenses/MIT */ #ifndef MT_MATRIX3X3_HPP #define MT_MATRIX3X3_HPP #include <guts/TypeTraits.hpp> #include <moto/Vector3.hpp> #include <moto/Vector4.hpp> #include <moto/Algebra.hpp> #include <moto/Diagonal3.hpp> namespace mt { // Row-major 3x3 matrix template <typename Scalar> class Matrix3x3 { public: typedef Scalar ScalarType; Matrix3x3(); Matrix3x3(Scalar a00, Scalar a01, Scalar a02, Scalar a10, Scalar a11, Scalar a12, Scalar a20, Scalar a21, Scalar a22); Matrix3x3(Zero); Matrix3x3(Identity); Matrix3x3(Scalar s); template <typename Scalar2> explicit Matrix3x3(const Scalar2* v); Matrix3x3(const Vector3<Scalar>& r0, const Vector3<Scalar>& r1, const Vector3<Scalar>& r2); Matrix3x3(const Vector4<Scalar>& q); Matrix3x3(const Diagonal3<Scalar>& d); operator const Vector3<Scalar>*() const; operator Vector3<Scalar>*(); Matrix3x3<Scalar>& operator=(Zero); Matrix3x3<Scalar>& operator+=(Zero); Matrix3x3<Scalar>& operator-=(Zero); Matrix3x3<Scalar>& operator*=(Zero); Matrix3x3<Scalar>& operator=(Identity); Matrix3x3<Scalar>& operator=(Scalar s); Matrix3x3<Scalar>& operator*=(Scalar s); Matrix3x3<Scalar>& operator/=(Scalar s); Matrix3x3<Scalar>& operator+=(const Matrix3x3<Scalar>& a); Matrix3x3<Scalar>& operator-=(const Matrix3x3<Scalar>& a); #if USE_MATRIX_COMP_MULT Matrix3x3<Scalar>& operator*=(const Matrix3x3<Scalar>& a); #endif void setValue(Scalar a00, Scalar a01, Scalar a02, Scalar a10, Scalar a11, Scalar a12, Scalar a20, Scalar a21, Scalar a22); template <typename Scalar2> void setValue(const Scalar2* v); void setColumns(const Vector3<Scalar>& c0, const Vector3<Scalar>& c1, const Vector3<Scalar>& c2); void setRows(const Vector3<Scalar>& r0, const Vector3<Scalar>& r1, const Vector3<Scalar>& r2); Matrix3x3<Scalar>& operator=(const Vector4<Scalar>& q); Matrix3x3<Scalar>& operator=(const Diagonal3<Scalar>& d); private: Vector3<Scalar> mRow[3]; }; template <typename Scalar> Scalar tdot(const Matrix3x3<Scalar>& a, int i, const Vector3<Scalar>& v); template <int I, int J, typename Scalar> Scalar cofactor(const Matrix3x3<Scalar>& a); template <typename Scalar> Vector3<Scalar> column(const Matrix3x3<Scalar>& a, int i); #ifdef USE_OSTREAM template <typename CharT, typename Traits, typename Scalar> std::basic_ostream<CharT, Traits>& operator<<(std::basic_ostream<CharT, Traits>& os, const Matrix3x3<Scalar>& a); #endif #ifdef USE_ISTREAM template <typename CharT, typename Traits, typename Scalar> std::basic_istream<CharT, Traits>& operator>>(std::basic_istream<CharT, Traits>& is, Matrix3x3<Scalar>& a); #endif template <typename Scalar> bool operator==(const Matrix3x3<Scalar>& a, const Matrix3x3<Scalar>& b); template <typename Scalar> Matrix3x3<Scalar> operator-(const Matrix3x3<Scalar>& a); template <typename Scalar1, typename Scalar2> Matrix3x3<typename Promote<Scalar1, Scalar2>::RT> operator+(const Matrix3x3<Scalar1>& a, const Matrix3x3<Scalar2>& b); template <typename Scalar1, typename Scalar2> Matrix3x3<typename Promote<Scalar1, Scalar2>::RT> operator-(const Matrix3x3<Scalar1>& a, const Matrix3x3<Scalar2>& b); #if USE_MATRIX_COMP_MULT template <typename Scalar1, typename Scalar2> Matrix3x3<typename Promote<Scalar1, Scalar2>::RT> operator*(const Matrix3x3<Scalar1>& a, const Matrix3x3<Scalar2>& b); #endif template <typename Scalar1, typename Scalar2> Matrix3x3<typename Promote<Scalar1, Scalar2>::RT> operator*(const Matrix3x3<Scalar1>& a, Scalar2 s); template <typename Scalar1, typename Scalar2> Matrix3x3<typename Promote<Scalar1, Scalar2>::RT> operator*(Scalar1 s, const Matrix3x3<Scalar2>& a); template <typename Scalar1, typename Scalar2> Matrix3x3<typename Promote<Scalar1, Scalar2>::RT> operator/(const Matrix3x3<Scalar1>& a, Scalar2 s); template <typename Scalar1, typename Scalar2> Vector3<typename Promote<Scalar1, Scalar2>::RT> mul(const Matrix3x3<Scalar1>& a, const Vector3<Scalar2>& v); template <typename Scalar1, typename Scalar2> Vector3<typename Promote<Scalar1, Scalar2>::RT> mul(const Vector3<Scalar1>& v, const Matrix3x3<Scalar2>& a); template <typename Scalar1, typename Scalar2> Matrix3x3<typename Promote<Scalar1, Scalar2>::RT> mul(const Matrix3x3<Scalar1>& a, const Matrix3x3<Scalar2>& b); template <typename Scalar1, typename Scalar2> Matrix3x3<typename Promote<Scalar1, Scalar2>::RT> transposeMul(const Matrix3x3<Scalar1>& a, const Matrix3x3<Scalar2>& b); template <typename Scalar1, typename Scalar2> Matrix3x3<typename Promote<Scalar1, Scalar2>::RT> mulTranspose(const Matrix3x3<Scalar1>& a, const Matrix3x3<Scalar2>& b); template <typename Scalar1, typename Scalar2> Matrix3x3<typename Promote<Scalar1, Scalar2>::RT> mul(const Matrix3x3<Scalar1>& a, const Diagonal3<Scalar2>& d); template <typename Scalar1, typename Scalar2> Matrix3x3<typename Promote<Scalar1, Scalar2>::RT> mul(const Diagonal3<Scalar1>& d, const Matrix3x3<Scalar2>& a); template <typename Scalar> Scalar determinant(const Matrix3x3<Scalar>& a); template <typename Scalar> Matrix3x3<Scalar> abs(const Matrix3x3<Scalar>& a); template <typename Scalar> Matrix3x3<Scalar> transpose(const Matrix3x3<Scalar>& a); template <typename Scalar> Matrix3x3<Scalar> adjoint(const Matrix3x3<Scalar>& a); template <typename Scalar> Matrix3x3<Scalar> inverse(const Matrix3x3<Scalar>& a); template <typename Scalar> Matrix3x3<Scalar> orthonormalize(const Matrix3x3<Scalar>& a); template <typename Scalar> Scalar trace(const Matrix3x3<Scalar>& a); template <typename Scalar> Vector4<Scalar> rotation(const Matrix3x3<Scalar>& a); template <typename Scalar> Vector3<Scalar> diagonal(const Matrix3x3<Scalar>& a); template <typename Scalar> Matrix3x3<Scalar> diag(const Vector3<Scalar>& v); template <typename Scalar> Matrix3x3<Scalar> skew(const Vector3<Scalar>& v); template <typename Scalar> Matrix3x3<Scalar> dyad(const Vector3<Scalar>& v1, const Vector3<Scalar>& v2); template <typename Scalar> Matrix3x3<Scalar> cholesky(const Matrix3x3<Scalar> a); template <typename Scalar> Vector3<Scalar> solveTranspose(const Matrix3x3<Scalar>& a, const Vector3<Scalar>& v); template <typename Scalar> Vector3<Scalar> solve(const Matrix3x3<Scalar>& a, const Vector3<Scalar>& v); template <typename Scalar1, typename Scalar2> void convert(Scalar1* v, const Matrix3x3<Scalar2>& a); template <typename Scalar> FORCEINLINE Matrix3x3<Scalar>::Matrix3x3() {} template <typename Scalar> FORCEINLINE Matrix3x3<Scalar>::Matrix3x3(Scalar a00, Scalar a01, Scalar a02, Scalar a10, Scalar a11, Scalar a12, Scalar a20, Scalar a21, Scalar a22) { setValue(a00, a01, a02, a10, a11, a12, a20, a21, a22); } template <typename Scalar> FORCEINLINE Matrix3x3<Scalar>::Matrix3x3(Zero) { *this = Zero(); } template <typename Scalar> FORCEINLINE Matrix3x3<Scalar>::Matrix3x3(Identity) { *this = Identity(); } template <typename Scalar> FORCEINLINE Matrix3x3<Scalar>::Matrix3x3(Scalar s) { *this = s; } template <typename Scalar> template <typename Scalar2> FORCEINLINE Matrix3x3<Scalar>::Matrix3x3(const Scalar2* v) { setValue(v); } template <typename Scalar> FORCEINLINE Matrix3x3<Scalar>::Matrix3x3(const Vector3<Scalar>& r0, const Vector3<Scalar>& r1, const Vector3<Scalar>& r2) { setRows(r0, r1, r2); } template <typename Scalar> FORCEINLINE Matrix3x3<Scalar>::Matrix3x3(const Vector4<Scalar>& q) { *this = q; } template <typename Scalar> FORCEINLINE Matrix3x3<Scalar>::Matrix3x3(const Diagonal3<Scalar>& d) { *this = d; } template <typename Scalar> FORCEINLINE Matrix3x3<Scalar>::operator const Vector3<Scalar>*() const { return mRow; } template <typename Scalar> FORCEINLINE Matrix3x3<Scalar>::operator Vector3<Scalar>*() { return mRow; } template <typename Scalar> FORCEINLINE Matrix3x3<Scalar>& Matrix3x3<Scalar>::operator=(Zero) { mRow[0] = Zero(); mRow[1] = Zero(); mRow[2] = Zero(); return *this; } template <typename Scalar> FORCEINLINE Matrix3x3<Scalar>& Matrix3x3<Scalar>::operator+=(Zero) { return *this; } template <typename Scalar> FORCEINLINE Matrix3x3<Scalar>& Matrix3x3<Scalar>::operator-=(Zero) { return *this; } template <typename Scalar> FORCEINLINE Matrix3x3<Scalar>& Matrix3x3<Scalar>::operator*=(Zero) { return *this = Zero(); } template <typename Scalar> FORCEINLINE Matrix3x3<Scalar>& Matrix3x3<Scalar>::operator=(Identity) { mRow[0] = Unit<0>(); mRow[1] = Unit<1>(); mRow[2] = Unit<2>(); return *this; } template <typename Scalar> FORCEINLINE Matrix3x3<Scalar>& Matrix3x3<Scalar>::operator=(Scalar s) { setValue(s, Scalar(), Scalar(), Scalar(), s, Scalar(), Scalar(), Scalar(), s); return *this; } template <typename Scalar> FORCEINLINE Matrix3x3<Scalar>& Matrix3x3<Scalar>::operator*=(Scalar s) { mRow[0] *= s; mRow[1] *= s; mRow[2] *= s; return *this; } template <typename Scalar> FORCEINLINE Matrix3x3<Scalar>& Matrix3x3<Scalar>::operator/=(Scalar s) { ASSERT(!iszero(s)); return *this *= Scalar(1) / s; } template <typename Scalar> FORCEINLINE Matrix3x3<Scalar>& Matrix3x3<Scalar>::operator+=(const Matrix3x3<Scalar>& a) { mRow[0] += a[0]; mRow[1] += a[1]; mRow[2] += a[2]; return *this; } template <typename Scalar> FORCEINLINE Matrix3x3<Scalar>& Matrix3x3<Scalar>::operator-=(const Matrix3x3<Scalar>& a) { mRow[0] -= a[0]; mRow[1] -= a[1]; mRow[2] -= a[2]; return *this; } #if USE_MATRIX_COMP_MULT template <typename Scalar> FORCEINLINE Matrix3x3<Scalar>& Matrix3x3<Scalar>::operator*=(const Matrix3x3<Scalar>& a) { mRow[0] *= a[0]; mRow[1] *= a[1]; mRow[2] *= a[2]; return *this; } #endif template <typename Scalar> FORCEINLINE void Matrix3x3<Scalar>::setValue(Scalar a00, Scalar a01, Scalar a02, Scalar a10, Scalar a11, Scalar a12, Scalar a20, Scalar a21, Scalar a22) { mRow[0] = Vector3<Scalar>(a00, a01, a02); mRow[1] = Vector3<Scalar>(a10, a11, a12); mRow[2] = Vector3<Scalar>(a20, a21, a22); } template <typename Scalar> template <typename Scalar2> FORCEINLINE void Matrix3x3<Scalar>::setValue(const Scalar2* v) { mRow[0] = Vector3<Scalar>(Scalar(v[0]), Scalar(v[4]), Scalar(v[8])); mRow[1] = Vector3<Scalar>(Scalar(v[1]), Scalar(v[5]), Scalar(v[9])); mRow[2] = Vector3<Scalar>(Scalar(v[2]), Scalar(v[6]), Scalar(v[10])); } template <typename Scalar> FORCEINLINE void Matrix3x3<Scalar>::setColumns(const Vector3<Scalar>& c0, const Vector3<Scalar>& c1, const Vector3<Scalar>& c2) { mRow[0] = Vector3<Scalar>(c0.x, c1.x, c2.x); mRow[1] = Vector3<Scalar>(c0.y, c1.y, c2.y); mRow[2] = Vector3<Scalar>(c0.z, c1.z, c2.z); } template <typename Scalar> FORCEINLINE void Matrix3x3<Scalar>::setRows(const Vector3<Scalar>& r0, const Vector3<Scalar>& r1, const Vector3<Scalar>& r2) { mRow[0] = r0; mRow[1] = r1; mRow[2] = r2; } template <typename Scalar> FORCEINLINE Matrix3x3<Scalar>& Matrix3x3<Scalar>::operator=(const Vector4<Scalar>& q) { Scalar r = dot(q, q); ASSERT(!iszero(r)); Scalar s = Scalar(2) / r; Scalar xs = q.x * s, ys = q.y * s, zs = q.z * s; Scalar wx = q.w * xs, wy = q.w * ys, wz = q.w * zs; Scalar xx = q.x * xs, xy = q.x * ys, xz = q.x * zs; Scalar yy = q.y * ys, yz = q.y * zs, zz = q.z * zs; setValue(Scalar(1) - (yy + zz), xy - wz, xz + wy, xy + wz, Scalar(1) - (xx + zz), yz - wx, xz - wy, yz + wx, Scalar(1) - (xx + yy)); return *this; } template <typename Scalar> FORCEINLINE Matrix3x3<Scalar>& Matrix3x3<Scalar>::operator=(const Diagonal3<Scalar>& d) { setValue(d.x, Scalar(), Scalar(), Scalar(), d.y, Scalar(), Scalar(), Scalar(), d.z); return *this; } template <typename Scalar> FORCEINLINE Scalar tdot(const Matrix3x3<Scalar>& a, int i, const Vector3<Scalar>& v) { return a[0][i] * v.x + a[1][i] * v.y + a[2][i] * v.z; } template <int I, int J, typename Scalar> FORCEINLINE Scalar cofactor(const Matrix3x3<Scalar>& a) { return a[(I + 1) % 3][(J + 1) % 3] * a[(I + 2) % 3][(J + 2) % 3] - a[(I + 2) % 3][(J + 1) % 3] * a[(I + 1) % 3][(J + 2) % 3]; } template <typename Scalar> FORCEINLINE Vector3<Scalar> column(const Matrix3x3<Scalar>& a, int i) { return Vector3<Scalar>(a[0][i], a[1][i], a[2][i]); } #ifdef USE_OSTREAM template <typename CharT, typename Traits, typename Scalar> FORCEINLINE std::basic_ostream<CharT, Traits>& operator<<(std::basic_ostream<CharT, Traits>& os, const Matrix3x3<Scalar>& a) { return os << ' ' << a[0] << ' ' << a[1] << ' ' << a[2]; } #endif #ifdef USE_ISTREAM template <typename CharT, typename Traits, typename Scalar> std::basic_istream<CharT, Traits>& operator>>(std::basic_istream<CharT, Traits>& is, Matrix3x3<Scalar>& a) { return is >> a[0] >> a[1] >> a[2]; } #endif template <typename Scalar> FORCEINLINE bool operator==(const Matrix3x3<Scalar>& a, const Matrix3x3<Scalar>& b) { return a[0] == b[0] && a[1] == b[1] && a[2] == b[2]; } template <typename Scalar> FORCEINLINE Matrix3x3<Scalar> operator-(const Matrix3x3<Scalar>& a) { return Matrix3x3<Scalar>(-a[0][0], -a[0][1], -a[0][2], -a[1][0], -a[1][1], -a[1][2], -a[2][0], -a[2][1], -a[2][2]); } template <typename Scalar1, typename Scalar2> FORCEINLINE Matrix3x3<typename Promote<Scalar1, Scalar2>::RT> operator+(const Matrix3x3<Scalar1>& a, const Matrix3x3<Scalar2>& b) { typedef typename Promote<Scalar1, Scalar2>::RT RT; return Matrix3x3<RT>(a[0][0] + b[0][0], a[0][1] + b[0][1], a[0][2] + b[0][2], a[1][0] + b[1][0], a[1][1] + b[1][1], a[1][2] + b[1][2], a[2][0] + b[2][0], a[2][1] + b[2][1], a[2][2] + b[2][2]); } template <typename Scalar1, typename Scalar2> FORCEINLINE Matrix3x3<typename Promote<Scalar1, Scalar2>::RT> operator-(const Matrix3x3<Scalar1>& a, const Matrix3x3<Scalar2>& b) { typedef typename Promote<Scalar1, Scalar2>::RT RT; return Matrix3x3<RT>(a[0][0] - b[0][0], a[0][1] - b[0][1], a[0][2] - b[0][2], a[1][0] - b[1][0], a[1][1] - b[1][1], a[1][2] - b[1][2], a[2][0] - b[2][0], a[2][1] - b[2][1], a[2][2] - b[2][2]); } #if USE_MATRIX_COMP_MULT template <typename Scalar1, typename Scalar2> FORCEINLINE Matrix3x3<typename Promote<Scalar1, Scalar2>::RT> operator*(const Matrix3x3<Scalar1>& a, const Matrix3x3<Scalar2>& b) { typedef typename Promote<Scalar1, Scalar2>::RT RT; return Matrix3x3<RT>(a[0][0] * b[0][0], a[0][1] * b[0][1], a[0][2] * b[0][2], a[1][0] * b[1][0], a[1][1] * b[1][1], a[1][2] * b[1][2], a[2][0] * b[2][0], a[2][1] * b[2][1], a[2][2] * b[2][2]); } #endif template <typename Scalar1, typename Scalar2> FORCEINLINE Matrix3x3<typename Promote<Scalar1, Scalar2>::RT> operator*(const Matrix3x3<Scalar1>& a, Scalar2 s) { typedef typename Promote<Scalar1, Scalar2>::RT RT; return Matrix3x3<RT>(a[0][0] * s, a[0][1] * s, a[0][2] * s, a[1][0] * s, a[1][1] * s, a[1][2] * s, a[2][0] * s, a[2][1] * s, a[2][2] * s); } template <typename Scalar1, typename Scalar2> FORCEINLINE Matrix3x3<typename Promote<Scalar1, Scalar2>::RT> operator*(Scalar1 s, const Matrix3x3<Scalar2>& a) { return a * s; } template <typename Scalar1, typename Scalar2> FORCEINLINE Matrix3x3<typename Promote<Scalar1, Scalar2>::RT> operator/(const Matrix3x3<Scalar1>& a, Scalar2 s) { ASSERT(!iszero(s)); return a * (Scalar2(1) / s); } template <typename Scalar1, typename Scalar2> FORCEINLINE Vector3<typename Promote<Scalar1, Scalar2>::RT> mul(const Matrix3x3<Scalar1>& a, const Vector3<Scalar2>& v) { typedef typename Promote<Scalar1, Scalar2>::RT RT; return Vector3<RT>(dot(a[0], v), dot(a[1], v), dot(a[2], v)); } template <typename Scalar1, typename Scalar2> FORCEINLINE Vector3<typename Promote<Scalar1, Scalar2>::RT> mul(const Vector3<Scalar1>& v, const Matrix3x3<Scalar2>& a) { typedef typename Promote<Scalar1, Scalar2>::RT RT; return Vector3<RT>(tdot(a, 0, v), tdot(a, 1, v), tdot(a, 2, v)); } template <typename Scalar1, typename Scalar2> FORCEINLINE Matrix3x3<typename Promote<Scalar1, Scalar2>::RT> mul(const Matrix3x3<Scalar1>& a, const Matrix3x3<Scalar2>& b) { typedef typename Promote<Scalar1, Scalar2>::RT RT; return Matrix3x3<RT>(tdot(b, 0, a[0]), tdot(b, 1, a[0]), tdot(b, 2, a[0]), tdot(b, 0, a[1]), tdot(b, 1, a[1]), tdot(b, 2, a[1]), tdot(b, 0, a[2]), tdot(b, 1, a[2]), tdot(b, 2, a[2])); } template <typename Scalar1, typename Scalar2> FORCEINLINE Matrix3x3<typename Promote<Scalar1, Scalar2>::RT> transposeMul(const Matrix3x3<Scalar1>& a, const Matrix3x3<Scalar2>& b) { typedef typename Promote<Scalar1, Scalar2>::RT RT; return Matrix3x3<RT>(a[0][0] * b[0][0] + a[1][0] * b[1][0] + a[2][0] * b[2][0], a[0][0] * b[0][1] + a[1][0] * b[1][1] + a[2][0] * b[2][1], a[0][0] * b[0][2] + a[1][0] * b[1][2] + a[2][0] * b[2][2], a[0][1] * b[0][0] + a[1][1] * b[1][0] + a[2][1] * b[2][0], a[0][1] * b[0][1] + a[1][1] * b[1][1] + a[2][1] * b[2][1], a[0][1] * b[0][2] + a[1][1] * b[1][2] + a[2][1] * b[2][2], a[0][2] * b[0][0] + a[1][2] * b[1][0] + a[2][2] * b[2][0], a[0][2] * b[0][1] + a[1][2] * b[1][1] + a[2][2] * b[2][1], a[0][2] * b[0][2] + a[1][2] * b[1][2] + a[2][2] * b[2][2]); } template <typename Scalar1, typename Scalar2> FORCEINLINE Matrix3x3<typename Promote<Scalar1, Scalar2>::RT> mulTranspose(const Matrix3x3<Scalar1>& a, const Matrix3x3<Scalar2>& b) { typedef typename Promote<Scalar1, Scalar2>::RT RT; return Matrix3x3<RT>(dot(a[0], b[0]), dot(a[0], b[1]), dot(a[0], b[2]), dot(a[1], b[0]), dot(a[1], b[1]), dot(a[1], b[2]), dot(a[2], b[0]), dot(a[2], b[1]), dot(a[2], b[2])); } template <typename Scalar1, typename Scalar2> FORCEINLINE Matrix3x3<typename Promote<Scalar1, Scalar2>::RT> mul(const Diagonal3<Scalar1>& d, const Matrix3x3<Scalar2>& a) { typedef typename Promote<Scalar1, Scalar2>::RT RT; return Matrix3x3<RT>(d[0] * a[0][0], d[0] * a[0][1], d[0] * a[0][2], d[1] * a[1][0], d[1] * a[1][1], d[1] * a[1][2], d[2] * a[2][0], d[2] * a[2][1], d[2] * a[2][2]); } template <typename Scalar1, typename Scalar2> FORCEINLINE Matrix3x3<typename Promote<Scalar1, Scalar2>::RT> mul(const Matrix3x3<Scalar1>& a, const Diagonal3<Scalar2>& d) { typedef typename Promote<Scalar1, Scalar2>::RT RT; return Matrix3x3<RT>(a[0][0] * d[0], a[0][1] * d[1], a[0][2] * d[2], a[1][0] * d[0], a[1][1] * d[1], a[1][2] * d[2], a[2][0] * d[0], a[2][1] * d[1], a[2][2] * d[2]); } template <typename Scalar> FORCEINLINE Scalar determinant(const Matrix3x3<Scalar>& a) { return triple(a[0], a[1], a[2]); } template <typename Scalar> FORCEINLINE Matrix3x3<Scalar> abs(const Matrix3x3<Scalar>& a) { return Matrix3x3<Scalar>(abs(a[0][0]), abs(a[0][1]), abs(a[0][2]), abs(a[1][0]), abs(a[1][1]), abs(a[1][2]), abs(a[2][0]), abs(a[2][1]), abs(a[2][2])); } template <typename Scalar> FORCEINLINE Matrix3x3<Scalar> transpose(const Matrix3x3<Scalar>& a) { return Matrix3x3<Scalar>(a[0][0], a[1][0], a[2][0], a[0][1], a[1][1], a[2][1], a[0][2], a[1][2], a[2][2]); } template <typename Scalar> FORCEINLINE Matrix3x3<Scalar> adjoint(const Matrix3x3<Scalar>& a) { return Matrix3x3<Scalar>(cofactor<0, 0>(a), cofactor<1, 0>(a), cofactor<2, 0>(a), cofactor<0, 1>(a), cofactor<1, 1>(a), cofactor<2, 1>(a), cofactor<0, 2>(a), cofactor<1, 2>(a), cofactor<2, 2>(a)); } template <typename Scalar> FORCEINLINE Matrix3x3<Scalar> inverse(const Matrix3x3<Scalar>& a) { Vector3<Scalar> co(cofactor<0, 0>(a), cofactor<0, 1>(a), cofactor<0, 2>(a)); Scalar det = dot(a[0], co); ASSERT(!iszero(det)); Scalar s = Scalar(1) / det; return Matrix3x3<Scalar>(co[0] * s, cofactor<1, 0>(a) * s, cofactor<2, 0>(a) * s, co[1] * s, cofactor<1, 1>(a) * s, cofactor<2, 1>(a) * s, co[2] * s, cofactor<1, 2>(a) * s, cofactor<2, 2>(a) * s); } template <typename Scalar> FORCEINLINE Matrix3x3<Scalar> orthonormalize(const Matrix3x3<Scalar>& a) { Matrix3x3<Scalar> result; result[0] = normalize(a[0]); result[1] = normalize(a[1]); result[2] = cross(result[0], result[1]); result[1] = cross(result[2], result[0]); return result; } template <typename Scalar> FORCEINLINE Scalar trace(const Matrix3x3<Scalar>& a) { return a[0][0] + a[1][1] + a[2][2]; } template <typename Scalar> FORCEINLINE Vector4<Scalar> rotation(const Matrix3x3<Scalar>& a) { Scalar t = trace(a); if (ispositive(t)) { Scalar d = sqrt(t + Scalar(1)); Scalar s = Scalar(0.5) / d; return Vector4<Scalar>((a[2][1] - a[1][2]) * s, (a[0][2] - a[2][0]) * s, (a[1][0] - a[0][1]) * s, d * Scalar(0.5)); } else { Vector4<Scalar> result; int i = a[0][0] < a[1][1] ? (a[1][1] < a[2][2] ? 2 : 1) : (a[0][0] < a[2][2] ? 2 : 0); int j = (i + 1) % 3; int k = (i + 2) % 3; Scalar d = sqrt(a[i][i] - a[j][j] - a[k][k] + Scalar(1)); Scalar s = Scalar(0.5) / d; result[i] = d * Scalar(0.5); result[j] = (a[j][i] + a[i][j]) * s; result[k] = (a[k][i] + a[i][k]) * s; result[3] = (a[k][j] - a[j][k]) * s; return result; } } template <typename Scalar> FORCEINLINE Vector3<Scalar> diagonal(const Matrix3x3<Scalar>& a) { return Vector3<Scalar>(a[0][0], a[1][1], a[2][2]); } template <typename Scalar> FORCEINLINE Matrix3x3<Scalar> diag(const Vector3<Scalar>& v) { return Matrix3x3<Scalar>(v.x, Scalar(), Scalar(), Scalar(), v.y, Scalar(), Scalar(), Scalar(), v.z); } template <typename Scalar> FORCEINLINE Matrix3x3<Scalar> skew(const Vector3<Scalar>& v) { return Matrix3x3<Scalar>(Scalar(), -v.z, v.y, v.z, Scalar(), -v.x, -v.y, v.x, Scalar()); } template <typename Scalar> FORCEINLINE Matrix3x3<Scalar> dyad(const Vector3<Scalar>& v1, const Vector3<Scalar>& v2) { return Matrix3x3<Scalar>(v1.x * v2.x, v1.x * v2.y, v1.x * v2.z, v1.y * v2.x, v1.y * v2.y, v1.y * v2.z, v1.z * v2.x, v1.z * v2.y, v1.z * v2.z); } template <typename Scalar> FORCEINLINE Matrix3x3<Scalar> cholesky(Matrix3x3<Scalar> a) { for (int k = 0; k != 3 ; ++k) { ASSERT(!isnegative(a[k][k])); a[k][k] = sqrt(a[k][k]); for (int i = k + 1; i != 3; ++i) { a[i][k] /= a[k][k]; } for (int j = k + 1; j != 3; ++j) { for (int i = j; i != 3; ++i) { a[i][j] -= a[i][k] * a[j][k]; } } } a[0][1] = a[0][2] = a[1][2] = Scalar(); return a; } template <typename Scalar> FORCEINLINE Vector3<Scalar> solveTranspose(const Matrix3x3<Scalar>& a, const Vector3<Scalar>& v) { // Cramer's rule Scalar det = determinant(a); ASSERT(!iszero(det)); return Vector3<Scalar>(triple(v, a[1], a[2]) / det, triple(a[0], v, a[2]) / det, triple(a[0], a[1], v) / det); } template <typename Scalar> FORCEINLINE Vector3<Scalar> solve(const Matrix3x3<Scalar>& a, const Vector3<Scalar>& v) { // Cramer's rule return solveTranspose(transpose(a), v); } template <typename Scalar1, typename Scalar2> FORCEINLINE void convert(Scalar1* v, const Matrix3x3<Scalar2>& a) { v[0] = Scalar1(a[0][0]); v[4] = Scalar1(a[0][1]); v[8] = Scalar1(a[0][2]); v[1] = Scalar1(a[1][0]); v[5] = Scalar1(a[1][1]); v[9] = Scalar1(a[1][2]); v[2] = Scalar1(a[2][0]); v[6] = Scalar1(a[2][1]); v[10] = Scalar1(a[2][2]); } } namespace guts { template <> struct TypeTraits<mt::Matrix3x3<float> > { enum { ID = TT_FLOAT3 | TT_3 }; }; template <> struct TypeTraits<mt::Matrix3x3<double> > { enum { ID = TT_DOUBLE3 | TT_3 }; }; } #endif
/* vim: sw=2: * Copyright (c) 2011, Gennady Bystritsky <bystr@mac.com> * * Distributed under the MIT Licence. * This is free software. See 'LICENSE' for details. * You must read and accept the license prior to use. * * Author: Gennady Bystritsky */ #include <sk/util/Class.h> #include <sk/util/Strings.h> #include <sk/util/StandardException.h> sk::util::StandardException:: StandardException(const sk::util::Strings& strings, const std::exception& exception) : sk::util::Exception(strings + exception.what()) { } sk::util::StandardException:: StandardException(const std::exception& exception) : sk::util::Exception(exception.what()) { } const sk::util::Class sk::util::StandardException:: getClass() const { return sk::util::Class("std::exception"); }
// // generic/stream_protocol.cpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // Disable autolinking for unit tests. #if !defined(BOOST_ALL_NO_LIB) #define BOOST_ALL_NO_LIB 1 #endif // !defined(BOOST_ALL_NO_LIB) // Test that header file is self-contained. #include <boost/asio/generic/stream_protocol.hpp> #include <cstring> #include <boost/asio/io_service.hpp> #include <boost/asio/ip/tcp.hpp> #include "../unit_test.hpp" #if defined(__cplusplus_cli) || defined(__cplusplus_winrt) # define generic cpp_generic #endif //------------------------------------------------------------------------------ // generic_stream_protocol_socket_compile test // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // The following test checks that all public member functions on the class // generic::stream_protocol::socket compile and link correctly. Runtime // failures are ignored. namespace generic_stream_protocol_socket_compile { void connect_handler(const boost::system::error_code&) { } void send_handler(const boost::system::error_code&, std::size_t) { } void receive_handler(const boost::system::error_code&, std::size_t) { } void write_some_handler(const boost::system::error_code&, std::size_t) { } void read_some_handler(const boost::system::error_code&, std::size_t) { } void test() { using namespace boost::asio; namespace generic = boost::asio::generic; typedef generic::stream_protocol sp; const int af_inet = BOOST_ASIO_OS_DEF(AF_INET); const int ipproto_tcp = BOOST_ASIO_OS_DEF(IPPROTO_TCP); const int sock_stream = BOOST_ASIO_OS_DEF(SOCK_STREAM); try { io_service ios; char mutable_char_buffer[128] = ""; const char const_char_buffer[128] = ""; socket_base::message_flags in_flags = 0; socket_base::keep_alive socket_option; socket_base::bytes_readable io_control_command; boost::system::error_code ec; // basic_stream_socket constructors. sp::socket socket1(ios); sp::socket socket2(ios, sp(af_inet, ipproto_tcp)); sp::socket socket3(ios, sp::endpoint()); #if defined(BOOST_ASIO_WINDOWS_RUNTIME) Windows::Networking::Sockets::StreamSocket^ native_socket1 = nullptr; #else // defined(BOOST_ASIO_WINDOWS_RUNTIME) sp::socket::native_handle_type native_socket1 = ::socket(af_inet, sock_stream, 0); #endif // defined(BOOST_ASIO_WINDOWS_RUNTIME) sp::socket socket4(ios, sp(af_inet, ipproto_tcp), native_socket1); #if defined(BOOST_ASIO_HAS_MOVE) sp::socket socket5(std::move(socket4)); boost::asio::ip::tcp::socket tcp_socket(ios); sp::socket socket6(std::move(tcp_socket)); #endif // defined(BOOST_ASIO_HAS_MOVE) // basic_stream_socket operators. #if defined(BOOST_ASIO_HAS_MOVE) socket1 = sp::socket(ios); socket1 = std::move(socket2); socket1 = boost::asio::ip::tcp::socket(ios); #endif // defined(BOOST_ASIO_HAS_MOVE) // basic_io_object functions. io_service& ios_ref = socket1.get_io_service(); (void)ios_ref; // basic_socket functions. sp::socket::lowest_layer_type& lowest_layer = socket1.lowest_layer(); (void)lowest_layer; socket1.open(sp(af_inet, ipproto_tcp)); socket1.open(sp(af_inet, ipproto_tcp), ec); #if defined(BOOST_ASIO_WINDOWS_RUNTIME) Windows::Networking::Sockets::StreamSocket^ native_socket2 = nullptr; #else // defined(BOOST_ASIO_WINDOWS_RUNTIME) sp::socket::native_handle_type native_socket2 = ::socket(af_inet, sock_stream, 0); #endif // defined(BOOST_ASIO_WINDOWS_RUNTIME) socket1.assign(sp(af_inet, ipproto_tcp), native_socket2); #if defined(BOOST_ASIO_WINDOWS_RUNTIME) Windows::Networking::Sockets::StreamSocket^ native_socket3 = nullptr; #else // defined(BOOST_ASIO_WINDOWS_RUNTIME) sp::socket::native_handle_type native_socket3 = ::socket(af_inet, sock_stream, 0); #endif // defined(BOOST_ASIO_WINDOWS_RUNTIME) socket1.assign(sp(af_inet, ipproto_tcp), native_socket3, ec); bool is_open = socket1.is_open(); (void)is_open; socket1.close(); socket1.close(ec); sp::socket::native_type native_socket4 = socket1.native(); (void)native_socket4; socket1.cancel(); socket1.cancel(ec); bool at_mark1 = socket1.at_mark(); (void)at_mark1; bool at_mark2 = socket1.at_mark(ec); (void)at_mark2; std::size_t available1 = socket1.available(); (void)available1; std::size_t available2 = socket1.available(ec); (void)available2; socket1.bind(sp::endpoint()); socket1.bind(sp::endpoint(), ec); socket1.connect(sp::endpoint()); socket1.connect(sp::endpoint(), ec); socket1.async_connect(sp::endpoint(), connect_handler); socket1.set_option(socket_option); socket1.set_option(socket_option, ec); socket1.get_option(socket_option); socket1.get_option(socket_option, ec); socket1.io_control(io_control_command); socket1.io_control(io_control_command, ec); sp::endpoint endpoint1 = socket1.local_endpoint(); sp::endpoint endpoint2 = socket1.local_endpoint(ec); sp::endpoint endpoint3 = socket1.remote_endpoint(); sp::endpoint endpoint4 = socket1.remote_endpoint(ec); socket1.shutdown(socket_base::shutdown_both); socket1.shutdown(socket_base::shutdown_both, ec); // basic_stream_socket functions. socket1.send(buffer(mutable_char_buffer)); socket1.send(buffer(const_char_buffer)); socket1.send(null_buffers()); socket1.send(buffer(mutable_char_buffer), in_flags); socket1.send(buffer(const_char_buffer), in_flags); socket1.send(null_buffers(), in_flags); socket1.send(buffer(mutable_char_buffer), in_flags, ec); socket1.send(buffer(const_char_buffer), in_flags, ec); socket1.send(null_buffers(), in_flags, ec); socket1.async_send(buffer(mutable_char_buffer), send_handler); socket1.async_send(buffer(const_char_buffer), send_handler); socket1.async_send(null_buffers(), send_handler); socket1.async_send(buffer(mutable_char_buffer), in_flags, send_handler); socket1.async_send(buffer(const_char_buffer), in_flags, send_handler); socket1.async_send(null_buffers(), in_flags, send_handler); socket1.receive(buffer(mutable_char_buffer)); socket1.receive(null_buffers()); socket1.receive(buffer(mutable_char_buffer), in_flags); socket1.receive(null_buffers(), in_flags); socket1.receive(buffer(mutable_char_buffer), in_flags, ec); socket1.receive(null_buffers(), in_flags, ec); socket1.async_receive(buffer(mutable_char_buffer), receive_handler); socket1.async_receive(null_buffers(), receive_handler); socket1.async_receive(buffer(mutable_char_buffer), in_flags, receive_handler); socket1.async_receive(null_buffers(), in_flags, receive_handler); socket1.write_some(buffer(mutable_char_buffer)); socket1.write_some(buffer(const_char_buffer)); socket1.write_some(null_buffers()); socket1.write_some(buffer(mutable_char_buffer), ec); socket1.write_some(buffer(const_char_buffer), ec); socket1.write_some(null_buffers(), ec); socket1.async_write_some(buffer(mutable_char_buffer), write_some_handler); socket1.async_write_some(buffer(const_char_buffer), write_some_handler); socket1.async_write_some(null_buffers(), write_some_handler); socket1.read_some(buffer(mutable_char_buffer)); socket1.read_some(buffer(mutable_char_buffer), ec); socket1.read_some(null_buffers(), ec); socket1.async_read_some(buffer(mutable_char_buffer), read_some_handler); socket1.async_read_some(null_buffers(), read_some_handler); } catch (std::exception&) { } } } // namespace generic_stream_protocol_socket_compile //------------------------------------------------------------------------------ BOOST_ASIO_TEST_SUITE ( "generic/stream_protocol", BOOST_ASIO_TEST_CASE(generic_stream_protocol_socket_compile::test) )
// Copyright (c) 2011-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "editaddressdialog.h" #include "ui_editaddressdialog.h" #include "addresstablemodel.h" #include "guiutil.h" #include <QDataWidgetMapper> #include <QMessageBox> EditAddressDialog::EditAddressDialog(Mode mode, QWidget *parent) : QDialog(parent), ui(new Ui::EditAddressDialog), mapper(0), mode(mode), model(0) { ui->setupUi(this); GUIUtil::setupAddressWidget(ui->addressEdit, this); switch(mode) { case NewReceivingAddress: setWindowTitle(tr("New receiving address")); ui->addressEdit->setEnabled(false); break; case NewSendingAddress: setWindowTitle(tr("New sending address")); break; case EditReceivingAddress: setWindowTitle(tr("Edit receiving address")); ui->addressEdit->setEnabled(false); break; case EditSendingAddress: setWindowTitle(tr("Edit sending address")); break; } mapper = new QDataWidgetMapper(this); mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit); } EditAddressDialog::~EditAddressDialog() { delete ui; } void EditAddressDialog::setModel(AddressTableModel *model) { this->model = model; if(!model) return; mapper->setModel(model); mapper->addMapping(ui->labelEdit, AddressTableModel::Label); mapper->addMapping(ui->addressEdit, AddressTableModel::Address); } void EditAddressDialog::loadRow(int row) { mapper->setCurrentIndex(row); } bool EditAddressDialog::saveCurrentRow() { if(!model) return false; switch(mode) { case NewReceivingAddress: case NewSendingAddress: address = model->addRow( mode == NewSendingAddress ? AddressTableModel::Send : AddressTableModel::Receive, ui->labelEdit->text(), ui->addressEdit->text()); break; case EditReceivingAddress: case EditSendingAddress: if(mapper->submit()) { address = ui->addressEdit->text(); } break; } return !address.isEmpty(); } void EditAddressDialog::accept() { if(!model) return; if(!saveCurrentRow()) { switch(model->getEditStatus()) { case AddressTableModel::OK: // Failed with unknown reason. Just reject. break; case AddressTableModel::NO_CHANGES: // No changes were made during edit operation. Just reject. break; case AddressTableModel::INVALID_ADDRESS: QMessageBox::warning(this, windowTitle(), tr("The entered address \"%1\" is not a valid Coin3Fly address.").arg(ui->addressEdit->text()), QMessageBox::Ok, QMessageBox::Ok); break; case AddressTableModel::DUPLICATE_ADDRESS: QMessageBox::warning(this, windowTitle(), tr("The entered address \"%1\" is already in the address book.").arg(ui->addressEdit->text()), QMessageBox::Ok, QMessageBox::Ok); break; case AddressTableModel::WALLET_UNLOCK_FAILURE: QMessageBox::critical(this, windowTitle(), tr("Could not unlock wallet."), QMessageBox::Ok, QMessageBox::Ok); break; case AddressTableModel::KEY_GENERATION_FAILURE: QMessageBox::critical(this, windowTitle(), tr("New key generation failed."), QMessageBox::Ok, QMessageBox::Ok); break; } return; } QDialog::accept(); } QString EditAddressDialog::getAddress() const { return address; } void EditAddressDialog::setAddress(const QString &address) { this->address = address; ui->addressEdit->setText(address); }
// Copyright (c) 2014 The Machinecoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <crypto/hmac_sha512.h> #include <string.h> CHMAC_SHA512::CHMAC_SHA512(const unsigned char* key, size_t keylen) { unsigned char rkey[128]; if (keylen <= 128) { memcpy(rkey, key, keylen); memset(rkey + keylen, 0, 128 - keylen); } else { CSHA512().Write(key, keylen).Finalize(rkey); memset(rkey + 64, 0, 64); } for (int n = 0; n < 128; n++) rkey[n] ^= 0x5c; outer.Write(rkey, 128); for (int n = 0; n < 128; n++) rkey[n] ^= 0x5c ^ 0x36; inner.Write(rkey, 128); } void CHMAC_SHA512::Finalize(unsigned char hash[OUTPUT_SIZE]) { unsigned char temp[64]; inner.Finalize(temp); outer.Write(temp, 64).Finalize(hash); }
// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. #include "handle_wrap.h" #include "async-wrap.h" #include "async-wrap-inl.h" #include "env.h" #include "env-inl.h" #include "util.h" #include "util-inl.h" #include "node.h" #include "queue.h" namespace node { using v8::Context; using v8::FunctionCallbackInfo; using v8::Handle; using v8::HandleScope; using v8::Local; using v8::Object; using v8::Value; // defined in node.cc extern QUEUE handle_wrap_queue; void HandleWrap::Ref(const FunctionCallbackInfo<Value>& args) { Environment* env = Environment::GetCurrent(args.GetIsolate()); HandleScope scope(env->isolate()); HandleWrap* wrap = Unwrap<HandleWrap>(args.Holder()); if (wrap != NULL && wrap->handle__ != NULL) { uv_ref(wrap->handle__); wrap->flags_ &= ~kUnref; } } void HandleWrap::Unref(const FunctionCallbackInfo<Value>& args) { Environment* env = Environment::GetCurrent(args.GetIsolate()); HandleScope scope(env->isolate()); HandleWrap* wrap = Unwrap<HandleWrap>(args.Holder()); if (wrap != NULL && wrap->handle__ != NULL) { uv_unref(wrap->handle__); wrap->flags_ |= kUnref; } } void HandleWrap::Close(const FunctionCallbackInfo<Value>& args) { Environment* env = Environment::GetCurrent(args.GetIsolate()); HandleScope scope(env->isolate()); HandleWrap* wrap = Unwrap<HandleWrap>(args.Holder()); // guard against uninitialized handle or double close if (wrap == NULL || wrap->handle__ == NULL) return; assert(!wrap->persistent().IsEmpty()); uv_close(wrap->handle__, OnClose); wrap->handle__ = NULL; if (args[0]->IsFunction()) { wrap->object()->Set(env->close_string(), args[0]); wrap->flags_ |= kCloseCallback; } } HandleWrap::HandleWrap(Environment* env, Handle<Object> object, uv_handle_t* handle, AsyncWrap::ProviderType provider) : AsyncWrap(env, object, provider), flags_(0), handle__(handle) { handle__->data = this; HandleScope scope(env->isolate()); Wrap<HandleWrap>(object, this); QUEUE_INSERT_TAIL(&handle_wrap_queue, &handle_wrap_queue_); } HandleWrap::~HandleWrap() { assert(persistent().IsEmpty()); QUEUE_REMOVE(&handle_wrap_queue_); } void HandleWrap::OnClose(uv_handle_t* handle) { HandleWrap* wrap = static_cast<HandleWrap*>(handle->data); Environment* env = wrap->env(); HandleScope scope(env->isolate()); // The wrap object should still be there. assert(wrap->persistent().IsEmpty() == false); // But the handle pointer should be gone. assert(wrap->handle__ == NULL); HandleScope handle_scope(env->isolate()); Context::Scope context_scope(env->context()); Local<Object> object = wrap->object(); if (wrap->flags_ & kCloseCallback) { wrap->MakeCallback(env->close_string(), 0, NULL); } object->SetAlignedPointerInInternalField(0, NULL); wrap->persistent().Reset(); delete wrap; } } // namespace node
// stdafx.cpp : source file that includes just the standard includes // simeck.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/ecm/v20190719/model/CreateRouteTableResponse.h> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Ecm::V20190719::Model; using namespace std; CreateRouteTableResponse::CreateRouteTableResponse() : m_routeTableHasBeenSet(false) { } CoreInternalOutcome CreateRouteTableResponse::Deserialize(const string &payload) { rapidjson::Document d; d.Parse(payload.c_str()); if (d.HasParseError() || !d.IsObject()) { return CoreInternalOutcome(Error("response not json format")); } if (!d.HasMember("Response") || !d["Response"].IsObject()) { return CoreInternalOutcome(Error("response `Response` is null or not object")); } rapidjson::Value &rsp = d["Response"]; if (!rsp.HasMember("RequestId") || !rsp["RequestId"].IsString()) { return CoreInternalOutcome(Error("response `Response.RequestId` is null or not string")); } string requestId(rsp["RequestId"].GetString()); SetRequestId(requestId); if (rsp.HasMember("Error")) { if (!rsp["Error"].IsObject() || !rsp["Error"].HasMember("Code") || !rsp["Error"]["Code"].IsString() || !rsp["Error"].HasMember("Message") || !rsp["Error"]["Message"].IsString()) { return CoreInternalOutcome(Error("response `Response.Error` format error").SetRequestId(requestId)); } string errorCode(rsp["Error"]["Code"].GetString()); string errorMsg(rsp["Error"]["Message"].GetString()); return CoreInternalOutcome(Error(errorCode, errorMsg).SetRequestId(requestId)); } if (rsp.HasMember("RouteTable") && !rsp["RouteTable"].IsNull()) { if (!rsp["RouteTable"].IsObject()) { return CoreInternalOutcome(Error("response `RouteTable` is not object type").SetRequestId(requestId)); } CoreInternalOutcome outcome = m_routeTable.Deserialize(rsp["RouteTable"]); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_routeTableHasBeenSet = true; } return CoreInternalOutcome(true); } RouteTable CreateRouteTableResponse::GetRouteTable() const { return m_routeTable; } bool CreateRouteTableResponse::RouteTableHasBeenSet() const { return m_routeTableHasBeenSet; }
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/udp/udp_socket_libevent.h" #include <errno.h> #include <fcntl.h> #include <netdb.h> #include <sys/socket.h> #include "base/callback.h" #include "base/logging.h" #include "base/message_loop.h" #include "base/metrics/stats_counters.h" #include "base/posix/eintr_wrapper.h" #include "base/rand_util.h" #include "net/base/io_buffer.h" #include "net/base/ip_endpoint.h" #include "net/base/net_errors.h" #include "net/base/net_log.h" #include "net/base/net_util.h" #include "net/udp/udp_net_log_parameters.h" #if defined(OS_POSIX) #include <netinet/in.h> #endif namespace { static const int kBindRetries = 10; static const int kPortStart = 1024; static const int kPortEnd = 65535; } // namespace net namespace net { UDPSocketLibevent::UDPSocketLibevent( DatagramSocket::BindType bind_type, const RandIntCallback& rand_int_cb, net::NetLog* net_log, const net::NetLog::Source& source) : socket_(kInvalidSocket), addr_family_(0), socket_options_(SOCKET_OPTION_MULTICAST_LOOP), multicast_time_to_live_(1), bind_type_(bind_type), rand_int_cb_(rand_int_cb), read_watcher_(this), write_watcher_(this), read_buf_len_(0), recv_from_address_(NULL), write_buf_len_(0), net_log_(BoundNetLog::Make(net_log, NetLog::SOURCE_UDP_SOCKET)) { net_log_.BeginEvent(NetLog::TYPE_SOCKET_ALIVE, source.ToEventParametersCallback()); if (bind_type == DatagramSocket::RANDOM_BIND) DCHECK(!rand_int_cb.is_null()); } UDPSocketLibevent::~UDPSocketLibevent() { Close(); net_log_.EndEvent(NetLog::TYPE_SOCKET_ALIVE); } void UDPSocketLibevent::Close() { DCHECK(CalledOnValidThread()); if (!is_connected()) return; // Zero out any pending read/write callback state. read_buf_ = NULL; read_buf_len_ = 0; read_callback_.Reset(); recv_from_address_ = NULL; write_buf_ = NULL; write_buf_len_ = 0; write_callback_.Reset(); send_to_address_.reset(); bool ok = read_socket_watcher_.StopWatchingFileDescriptor(); DCHECK(ok); ok = write_socket_watcher_.StopWatchingFileDescriptor(); DCHECK(ok); if (HANDLE_EINTR(close(socket_)) < 0) PLOG(ERROR) << "close"; socket_ = kInvalidSocket; } int UDPSocketLibevent::GetPeerAddress(IPEndPoint* address) const { DCHECK(CalledOnValidThread()); DCHECK(address); if (!is_connected()) return ERR_SOCKET_NOT_CONNECTED; if (!remote_address_.get()) { SockaddrStorage storage; if (getpeername(socket_, storage.addr, &storage.addr_len)) return MapSystemError(errno); scoped_ptr<IPEndPoint> address(new IPEndPoint()); if (!address->FromSockAddr(storage.addr, storage.addr_len)) return ERR_FAILED; remote_address_.reset(address.release()); } *address = *remote_address_; return OK; } int UDPSocketLibevent::GetLocalAddress(IPEndPoint* address) const { DCHECK(CalledOnValidThread()); DCHECK(address); if (!is_connected()) return ERR_SOCKET_NOT_CONNECTED; if (!local_address_.get()) { SockaddrStorage storage; if (getsockname(socket_, storage.addr, &storage.addr_len)) return MapSystemError(errno); scoped_ptr<IPEndPoint> address(new IPEndPoint()); if (!address->FromSockAddr(storage.addr, storage.addr_len)) return ERR_FAILED; local_address_.reset(address.release()); } *address = *local_address_; return OK; } int UDPSocketLibevent::Read(IOBuffer* buf, int buf_len, const CompletionCallback& callback) { return RecvFrom(buf, buf_len, NULL, callback); } int UDPSocketLibevent::RecvFrom(IOBuffer* buf, int buf_len, IPEndPoint* address, const CompletionCallback& callback) { DCHECK(CalledOnValidThread()); DCHECK_NE(kInvalidSocket, socket_); DCHECK(read_callback_.is_null()); DCHECK(!recv_from_address_); DCHECK(!callback.is_null()); // Synchronous operation not supported DCHECK_GT(buf_len, 0); int nread = InternalRecvFrom(buf, buf_len, address); if (nread != ERR_IO_PENDING) return nread; if (!MessageLoopForIO::current()->WatchFileDescriptor( socket_, true, MessageLoopForIO::WATCH_READ, &read_socket_watcher_, &read_watcher_)) { PLOG(ERROR) << "WatchFileDescriptor failed on read"; int result = MapSystemError(errno); LogRead(result, NULL, 0, NULL); return result; } read_buf_ = buf; read_buf_len_ = buf_len; recv_from_address_ = address; read_callback_ = callback; return ERR_IO_PENDING; } int UDPSocketLibevent::Write(IOBuffer* buf, int buf_len, const CompletionCallback& callback) { return SendToOrWrite(buf, buf_len, NULL, callback); } int UDPSocketLibevent::SendTo(IOBuffer* buf, int buf_len, const IPEndPoint& address, const CompletionCallback& callback) { return SendToOrWrite(buf, buf_len, &address, callback); } int UDPSocketLibevent::SendToOrWrite(IOBuffer* buf, int buf_len, const IPEndPoint* address, const CompletionCallback& callback) { DCHECK(CalledOnValidThread()); DCHECK_NE(kInvalidSocket, socket_); DCHECK(write_callback_.is_null()); DCHECK(!callback.is_null()); // Synchronous operation not supported DCHECK_GT(buf_len, 0); int result = InternalSendTo(buf, buf_len, address); if (result != ERR_IO_PENDING) return result; if (!MessageLoopForIO::current()->WatchFileDescriptor( socket_, true, MessageLoopForIO::WATCH_WRITE, &write_socket_watcher_, &write_watcher_)) { DVLOG(1) << "WatchFileDescriptor failed on write, errno " << errno; int result = MapSystemError(errno); LogWrite(result, NULL, NULL); return result; } write_buf_ = buf; write_buf_len_ = buf_len; DCHECK(!send_to_address_.get()); if (address) { send_to_address_.reset(new IPEndPoint(*address)); } write_callback_ = callback; return ERR_IO_PENDING; } int UDPSocketLibevent::Connect(const IPEndPoint& address) { net_log_.BeginEvent(NetLog::TYPE_UDP_CONNECT, CreateNetLogUDPConnectCallback(&address)); int rv = InternalConnect(address); if (rv != OK) Close(); net_log_.EndEventWithNetErrorCode(NetLog::TYPE_UDP_CONNECT, rv); return rv; } int UDPSocketLibevent::InternalConnect(const IPEndPoint& address) { DCHECK(CalledOnValidThread()); DCHECK(!is_connected()); DCHECK(!remote_address_.get()); int rv = CreateSocket(address); if (rv < 0) return rv; if (bind_type_ == DatagramSocket::RANDOM_BIND) rv = RandomBind(address); // else connect() does the DatagramSocket::DEFAULT_BIND if (rv < 0) return rv; SockaddrStorage storage; if (!address.ToSockAddr(storage.addr, &storage.addr_len)) return ERR_FAILED; rv = HANDLE_EINTR(connect(socket_, storage.addr, storage.addr_len)); if (rv < 0) return MapSystemError(errno); remote_address_.reset(new IPEndPoint(address)); return rv; } int UDPSocketLibevent::Bind(const IPEndPoint& address) { DCHECK(CalledOnValidThread()); DCHECK(!is_connected()); int rv = CreateSocket(address); if (rv < 0) return rv; rv = SetSocketOptions(); if (rv < 0) return rv; rv = DoBind(address); if (rv < 0) return rv; local_address_.reset(); return rv; } bool UDPSocketLibevent::SetReceiveBufferSize(int32 size) { DCHECK(CalledOnValidThread()); int rv = setsockopt(socket_, SOL_SOCKET, SO_RCVBUF, reinterpret_cast<const char*>(&size), sizeof(size)); DCHECK(!rv) << "Could not set socket receive buffer size: " << errno; return rv == 0; } bool UDPSocketLibevent::SetSendBufferSize(int32 size) { DCHECK(CalledOnValidThread()); int rv = setsockopt(socket_, SOL_SOCKET, SO_SNDBUF, reinterpret_cast<const char*>(&size), sizeof(size)); DCHECK(!rv) << "Could not set socket send buffer size: " << errno; return rv == 0; } void UDPSocketLibevent::AllowAddressReuse() { DCHECK(CalledOnValidThread()); DCHECK(!is_connected()); socket_options_ |= SOCKET_OPTION_REUSE_ADDRESS; } void UDPSocketLibevent::AllowBroadcast() { DCHECK(CalledOnValidThread()); DCHECK(!is_connected()); socket_options_ |= SOCKET_OPTION_BROADCAST; } void UDPSocketLibevent::ReadWatcher::OnFileCanReadWithoutBlocking(int) { if (!socket_->read_callback_.is_null()) socket_->DidCompleteRead(); } void UDPSocketLibevent::WriteWatcher::OnFileCanWriteWithoutBlocking(int) { if (!socket_->write_callback_.is_null()) socket_->DidCompleteWrite(); } void UDPSocketLibevent::DoReadCallback(int rv) { DCHECK_NE(rv, ERR_IO_PENDING); DCHECK(!read_callback_.is_null()); // since Run may result in Read being called, clear read_callback_ up front. CompletionCallback c = read_callback_; read_callback_.Reset(); c.Run(rv); } void UDPSocketLibevent::DoWriteCallback(int rv) { DCHECK_NE(rv, ERR_IO_PENDING); DCHECK(!write_callback_.is_null()); // since Run may result in Write being called, clear write_callback_ up front. CompletionCallback c = write_callback_; write_callback_.Reset(); c.Run(rv); } void UDPSocketLibevent::DidCompleteRead() { int result = InternalRecvFrom(read_buf_, read_buf_len_, recv_from_address_); if (result != ERR_IO_PENDING) { read_buf_ = NULL; read_buf_len_ = 0; recv_from_address_ = NULL; bool ok = read_socket_watcher_.StopWatchingFileDescriptor(); DCHECK(ok); DoReadCallback(result); } } void UDPSocketLibevent::LogRead(int result, const char* bytes, socklen_t addr_len, const sockaddr* addr) const { if (result < 0) { net_log_.AddEventWithNetErrorCode(NetLog::TYPE_UDP_RECEIVE_ERROR, result); return; } if (net_log_.IsLoggingAllEvents()) { DCHECK(addr_len > 0); DCHECK(addr); IPEndPoint address; bool is_address_valid = address.FromSockAddr(addr, addr_len); net_log_.AddEvent( NetLog::TYPE_UDP_BYTES_RECEIVED, CreateNetLogUDPDataTranferCallback( result, bytes, is_address_valid ? &address : NULL)); } base::StatsCounter read_bytes("udp.read_bytes"); read_bytes.Add(result); } int UDPSocketLibevent::CreateSocket(const IPEndPoint& address) { addr_family_ = address.GetSockAddrFamily(); socket_ = socket(addr_family_, SOCK_DGRAM, 0); if (socket_ == kInvalidSocket) return MapSystemError(errno); if (SetNonBlocking(socket_)) { const int err = MapSystemError(errno); Close(); return err; } return OK; } void UDPSocketLibevent::DidCompleteWrite() { int result = InternalSendTo(write_buf_, write_buf_len_, send_to_address_.get()); if (result != ERR_IO_PENDING) { write_buf_ = NULL; write_buf_len_ = 0; send_to_address_.reset(); write_socket_watcher_.StopWatchingFileDescriptor(); DoWriteCallback(result); } } void UDPSocketLibevent::LogWrite(int result, const char* bytes, const IPEndPoint* address) const { if (result < 0) { net_log_.AddEventWithNetErrorCode(NetLog::TYPE_UDP_SEND_ERROR, result); return; } if (net_log_.IsLoggingAllEvents()) { net_log_.AddEvent( NetLog::TYPE_UDP_BYTES_SENT, CreateNetLogUDPDataTranferCallback(result, bytes, address)); } base::StatsCounter write_bytes("udp.write_bytes"); write_bytes.Add(result); } int UDPSocketLibevent::InternalRecvFrom(IOBuffer* buf, int buf_len, IPEndPoint* address) { int bytes_transferred; int flags = 0; SockaddrStorage storage; bytes_transferred = HANDLE_EINTR(recvfrom(socket_, buf->data(), buf_len, flags, storage.addr, &storage.addr_len)); int result; if (bytes_transferred >= 0) { result = bytes_transferred; if (address && !address->FromSockAddr(storage.addr, storage.addr_len)) result = ERR_FAILED; } else { result = MapSystemError(errno); } if (result != ERR_IO_PENDING) LogRead(result, buf->data(), storage.addr_len, storage.addr); return result; } int UDPSocketLibevent::InternalSendTo(IOBuffer* buf, int buf_len, const IPEndPoint* address) { SockaddrStorage storage; struct sockaddr* addr = storage.addr; if (!address) { addr = NULL; storage.addr_len = 0; } else { if (!address->ToSockAddr(storage.addr, &storage.addr_len)) { int result = ERR_FAILED; LogWrite(result, NULL, NULL); return result; } } int result = HANDLE_EINTR(sendto(socket_, buf->data(), buf_len, 0, addr, storage.addr_len)); if (result < 0) result = MapSystemError(errno); if (result != ERR_IO_PENDING) LogWrite(result, buf->data(), address); return result; } int UDPSocketLibevent::SetSocketOptions() { int true_value = 1; if (socket_options_ & SOCKET_OPTION_REUSE_ADDRESS) { int rv = setsockopt(socket_, SOL_SOCKET, SO_REUSEADDR, &true_value, sizeof(true_value)); if (rv < 0) return MapSystemError(errno); } if (socket_options_ & SOCKET_OPTION_BROADCAST) { int rv; #if defined(OS_MACOSX) // SO_REUSEPORT on OSX permits multiple processes to each receive // UDP multicast or broadcast datagrams destined for the bound // port. rv = setsockopt(socket_, SOL_SOCKET, SO_REUSEPORT, &true_value, sizeof(true_value)); #else rv = setsockopt(socket_, SOL_SOCKET, SO_BROADCAST, &true_value, sizeof(true_value)); #endif // defined(OS_MACOSX) if (rv < 0) return MapSystemError(errno); } if (!(socket_options_ & SOCKET_OPTION_MULTICAST_LOOP)) { int rv; if (addr_family_ == AF_INET) { u_char loop = 0; rv = setsockopt(socket_, IPPROTO_IP, IP_MULTICAST_LOOP, &loop, sizeof(loop)); } else { u_int loop = 0; rv = setsockopt(socket_, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, &loop, sizeof(loop)); } if (rv < 0) return MapSystemError(errno); } if (multicast_time_to_live_ != IP_DEFAULT_MULTICAST_TTL) { int rv; if (addr_family_ == AF_INET) { u_char ttl = multicast_time_to_live_; rv = setsockopt(socket_, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl)); } else { // Signed interger. -1 to use route default. int ttl = multicast_time_to_live_; rv = setsockopt(socket_, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &ttl, sizeof(ttl)); } if (rv < 0) return MapSystemError(errno); } return OK; } int UDPSocketLibevent::DoBind(const IPEndPoint& address) { SockaddrStorage storage; if (!address.ToSockAddr(storage.addr, &storage.addr_len)) return ERR_UNEXPECTED; int rv = bind(socket_, storage.addr, storage.addr_len); return rv < 0 ? MapSystemError(errno) : rv; } int UDPSocketLibevent::RandomBind(const IPEndPoint& address) { DCHECK(bind_type_ == DatagramSocket::RANDOM_BIND && !rand_int_cb_.is_null()); // Construct IPAddressNumber of appropriate size (IPv4 or IPv6) of 0s. IPAddressNumber ip(address.address().size()); for (int i = 0; i < kBindRetries; ++i) { int rv = DoBind(IPEndPoint(ip, rand_int_cb_.Run(kPortStart, kPortEnd))); if (rv == OK || rv != ERR_ADDRESS_IN_USE) return rv; } return DoBind(IPEndPoint(ip, 0)); } int UDPSocketLibevent::JoinGroup(const IPAddressNumber& group_address) const { DCHECK(CalledOnValidThread()); if (!is_connected()) return ERR_SOCKET_NOT_CONNECTED; switch (group_address.size()) { case kIPv4AddressSize: { if (addr_family_ != AF_INET) return ERR_ADDRESS_INVALID; ip_mreq mreq; mreq.imr_interface.s_addr = INADDR_ANY; memcpy(&mreq.imr_multiaddr, &group_address[0], kIPv4AddressSize); int rv = setsockopt(socket_, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)); if (rv < 0) return MapSystemError(errno); return OK; } case kIPv6AddressSize: { if (addr_family_ != AF_INET6) return ERR_ADDRESS_INVALID; ipv6_mreq mreq; mreq.ipv6mr_interface = 0; // 0 indicates default multicast interface. memcpy(&mreq.ipv6mr_multiaddr, &group_address[0], kIPv6AddressSize); int rv = setsockopt(socket_, IPPROTO_IPV6, IPV6_JOIN_GROUP, &mreq, sizeof(mreq)); if (rv < 0) return MapSystemError(errno); return OK; } default: NOTREACHED() << "Invalid address family"; return ERR_ADDRESS_INVALID; } } int UDPSocketLibevent::LeaveGroup(const IPAddressNumber& group_address) const { DCHECK(CalledOnValidThread()); if (!is_connected()) return ERR_SOCKET_NOT_CONNECTED; switch (group_address.size()) { case kIPv4AddressSize: { if (addr_family_ != AF_INET) return ERR_ADDRESS_INVALID; ip_mreq mreq; mreq.imr_interface.s_addr = INADDR_ANY; memcpy(&mreq.imr_multiaddr, &group_address[0], kIPv4AddressSize); int rv = setsockopt(socket_, IPPROTO_IP, IP_DROP_MEMBERSHIP, &mreq, sizeof(mreq)); if (rv < 0) return MapSystemError(errno); return OK; } case kIPv6AddressSize: { if (addr_family_ != AF_INET6) return ERR_ADDRESS_INVALID; ipv6_mreq mreq; mreq.ipv6mr_interface = 0; // 0 indicates default multicast interface. memcpy(&mreq.ipv6mr_multiaddr, &group_address[0], kIPv6AddressSize); int rv = setsockopt(socket_, IPPROTO_IPV6, IPV6_LEAVE_GROUP, &mreq, sizeof(mreq)); if (rv < 0) return MapSystemError(errno); return OK; } default: NOTREACHED() << "Invalid address family"; return ERR_ADDRESS_INVALID; } } int UDPSocketLibevent::SetMulticastTimeToLive(int time_to_live) { DCHECK(CalledOnValidThread()); if (is_connected()) return ERR_UNEXPECTED; if (time_to_live < 0 || time_to_live > 255) return ERR_INVALID_ARGUMENT; multicast_time_to_live_ = time_to_live; return OK; } int UDPSocketLibevent::SetMulticastLoopbackMode(bool loopback) { DCHECK(CalledOnValidThread()); if (is_connected()) return ERR_UNEXPECTED; if (loopback) socket_options_ |= SOCKET_OPTION_MULTICAST_LOOP; else socket_options_ &= ~SOCKET_OPTION_MULTICAST_LOOP; return OK; } } // namespace net
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "config.h" #include "core/html/HTMLPictureElement.h" #include "core/HTMLNames.h" #include "core/dom/ElementTraversal.h" #include "core/frame/UseCounter.h" #include "core/html/HTMLImageElement.h" #include "core/loader/ImageLoader.h" namespace blink { using namespace HTMLNames; inline HTMLPictureElement::HTMLPictureElement(Document& document) : HTMLElement(pictureTag, document) { } DEFINE_NODE_FACTORY(HTMLPictureElement) void HTMLPictureElement::sourceOrMediaChanged() { for (HTMLImageElement* imageElement = Traversal<HTMLImageElement>::firstChild(*this); imageElement; imageElement = Traversal<HTMLImageElement>::nextSibling(*imageElement)) { imageElement->selectSourceURL(ImageLoader::UpdateNormal); } } Node::InsertionNotificationRequest HTMLPictureElement::insertedInto(ContainerNode* insertionPoint) { UseCounter::count(document(), UseCounter::Picture); return HTMLElement::insertedInto(insertionPoint); } } // namespace
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "msd_vsl_device.h" #include <chrono> #include <thread> #include "magma_util/macros.h" #include "magma_vendor_queries.h" #include "msd.h" #include "platform_mmio.h" #include "registers.h" std::unique_ptr<MsdVslDevice> MsdVslDevice::Create(void* device_handle, bool enable_mmu) { auto device = std::make_unique<MsdVslDevice>(); if (!device->Init(device_handle, enable_mmu)) return DRETP(nullptr, "Failed to initialize device"); return device; } bool MsdVslDevice::Init(void* device_handle, bool enable_mmu) { platform_device_ = magma::PlatformDevice::Create(device_handle); if (!platform_device_) return DRETF(false, "Failed to create platform device"); std::unique_ptr<magma::PlatformMmio> mmio = platform_device_->CpuMapMmio(0, magma::PlatformMmio::CACHE_POLICY_UNCACHED_DEVICE); if (!mmio) return DRETF(false, "failed to map registers"); register_io_ = std::make_unique<magma::RegisterIo>(std::move(mmio)); device_id_ = registers::ChipId::Get().ReadFrom(register_io_.get()).chip_id().get(); DLOG("Detected vsl chip id 0x%x", device_id_); if (device_id_ != 0x7000 && device_id_ != 0x8000) return DRETF(false, "Unspported gpu model 0x%x\n", device_id_); gpu_features_ = std::make_unique<GpuFeatures>(register_io_.get()); DLOG("gpu features: 0x%x minor features 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x\n", gpu_features_->features().reg_value(), gpu_features_->minor_features(0), gpu_features_->minor_features(1), gpu_features_->minor_features(2), gpu_features_->minor_features(3), gpu_features_->minor_features(4), gpu_features_->minor_features(5)); DLOG("halti5: %d mmu: %d", gpu_features_->halti5(), gpu_features_->has_mmu()); DLOG( "stream count %u register_max %u thread_count %u vertex_cache_size %u shader_core_count " "%u pixel_pipes %u vertex_output_buffer_size %u\n", gpu_features_->stream_count(), gpu_features_->register_max(), gpu_features_->thread_count(), gpu_features_->vertex_cache_size(), gpu_features_->shader_core_count(), gpu_features_->pixel_pipes(), gpu_features_->vertex_output_buffer_size()); DLOG("instruction count %u buffer_size %u num_constants %u varyings_count %u\n", gpu_features_->instruction_count(), gpu_features_->buffer_size(), gpu_features_->num_constants(), gpu_features_->varyings_count()); if (!gpu_features_->features().pipe_3d().get()) return DRETF(false, "Gpu has no 3d pipe: features 0x%x\n", gpu_features_->features().reg_value()); bus_mapper_ = magma::PlatformBusMapper::Create(platform_device_->GetBusTransactionInitiator()); if (!bus_mapper_) return DRETF(false, "failed to create bus mapper"); page_table_arrays_ = PageTableArrays::Create(bus_mapper_.get()); if (!page_table_arrays_) return DRETF(false, "failed to create page table arrays"); Reset(); HardwareInit(enable_mmu); return true; } void MsdVslDevice::HardwareInit(bool enable_mmu) { { auto reg = registers::SecureAhbControl::Get().ReadFrom(register_io_.get()); reg.non_secure_access().set(1); reg.WriteTo(register_io_.get()); } page_table_arrays_->HardwareInit(register_io_.get()); page_table_arrays_->Enable(register_io(), enable_mmu); page_table_slot_allocator_ = std::make_unique<PageTableSlotAllocator>(page_table_arrays_->size()); } void MsdVslDevice::Reset() { DLOG("Reset start"); auto clock_control = registers::ClockControl::Get().FromValue(0); clock_control.isolate_gpu().set(1); clock_control.WriteTo(register_io()); { auto reg = registers::SecureAhbControl::Get().FromValue(0); reg.reset().set(1); reg.WriteTo(register_io_.get()); } std::this_thread::sleep_for(std::chrono::microseconds(100)); clock_control.soft_reset().set(0); clock_control.WriteTo(register_io()); clock_control.isolate_gpu().set(0); clock_control.WriteTo(register_io()); clock_control = registers::ClockControl::Get().ReadFrom(register_io_.get()); if (!IsIdle() || !clock_control.idle_3d().get()) { magma::log(magma::LOG_WARNING, "Gpu reset: failed to idle"); } DLOG("Reset complete"); } bool MsdVslDevice::IsIdle() { return registers::IdleState::Get().ReadFrom(register_io_.get()).IsIdle(); } bool MsdVslDevice::SubmitCommandBufferNoMmu(uint64_t bus_addr, uint32_t length, uint16_t* prefetch_out) { if (bus_addr & 0xFFFFFFFF00000000ul) return DRETF(false, "Can't submit address > 32 bits without mmu: 0x%08lx", bus_addr); uint32_t prefetch = magma::round_up(length, sizeof(uint64_t)) / sizeof(uint64_t); if (prefetch & 0xFFFF0000) return DRETF(false, "Can't submit length %u (prefetch 0x%x)", length, prefetch); *prefetch_out = prefetch & 0xFFFF; DLOG("Submitting buffer at bus addr 0x%lx", bus_addr); auto reg_cmd_addr = registers::FetchEngineCommandAddress::Get().FromValue(0); reg_cmd_addr.addr().set(bus_addr & 0xFFFFFFFF); auto reg_cmd_ctrl = registers::FetchEngineCommandControl::Get().FromValue(0); reg_cmd_ctrl.enable().set(1); reg_cmd_ctrl.prefetch().set(*prefetch_out); auto reg_sec_cmd_ctrl = registers::SecureCommandControl::Get().FromValue(0); reg_sec_cmd_ctrl.enable().set(1); reg_sec_cmd_ctrl.prefetch().set(*prefetch_out); reg_cmd_addr.WriteTo(register_io_.get()); reg_cmd_ctrl.WriteTo(register_io_.get()); reg_sec_cmd_ctrl.WriteTo(register_io_.get()); return true; } bool MsdVslDevice::SubmitCommandBuffer(uint32_t gpu_addr, uint32_t length, uint16_t* prefetch_out) { uint32_t prefetch = magma::round_up(length, sizeof(uint64_t)) / sizeof(uint64_t); if (prefetch & 0xFFFF0000) return DRETF(false, "Can't submit length %u (prefetch 0x%x)", length, prefetch); *prefetch_out = prefetch & 0xFFFF; DLOG("Submitting buffer at gpu addr 0x%x", gpu_addr); auto reg_cmd_addr = registers::FetchEngineCommandAddress::Get().FromValue(0); reg_cmd_addr.addr().set(gpu_addr); auto reg_cmd_ctrl = registers::FetchEngineCommandControl::Get().FromValue(0); reg_cmd_ctrl.enable().set(1); reg_cmd_ctrl.prefetch().set(*prefetch_out); auto reg_sec_cmd_ctrl = registers::SecureCommandControl::Get().FromValue(0); reg_sec_cmd_ctrl.enable().set(1); reg_sec_cmd_ctrl.prefetch().set(*prefetch_out); reg_cmd_addr.WriteTo(register_io_.get()); reg_cmd_ctrl.WriteTo(register_io_.get()); reg_sec_cmd_ctrl.WriteTo(register_io_.get()); return true; } std::unique_ptr<MsdVslConnection> MsdVslDevice::Open(msd_client_id_t client_id) { uint32_t page_table_array_slot; if (!page_table_slot_allocator_->Alloc(&page_table_array_slot)) return DRETP(nullptr, "couldn't allocate page table slot"); auto address_space = AddressSpace::Create(this); if (!address_space) return DRETP(nullptr, "failed to create address space"); page_table_arrays_->AssignAddressSpace(page_table_array_slot, address_space.get()); return std::make_unique<MsdVslConnection>(this, page_table_array_slot, std::move(address_space), client_id); } magma_status_t MsdVslDevice::ChipIdentity(magma_vsl_gc_chip_identity* out_identity) { if (device_id() != 0x8000) { // TODO(fxb/37962): Read hardcoded values from features database instead. return DRET_MSG(MAGMA_STATUS_UNIMPLEMENTED, "unhandled device id 0x%x", device_id()); } memset(out_identity, 0, sizeof(*out_identity)); out_identity->chip_model = device_id(); out_identity->chip_revision = registers::Revision::Get().ReadFrom( register_io_.get()).chip_revision().get(); out_identity->chip_date = registers::ChipDate::Get().ReadFrom( register_io_.get()).chip_date().get(); out_identity->stream_count = gpu_features_->stream_count(); out_identity->pixel_pipes = gpu_features_->pixel_pipes(); out_identity->resolve_pipes = 0x0; out_identity->instruction_count = gpu_features_->instruction_count(); out_identity->num_constants = gpu_features_->num_constants(); out_identity->varyings_count = gpu_features_->varyings_count(); out_identity->gpu_core_count = 0x1; out_identity->product_id = registers::ProductId::Get().ReadFrom( register_io_.get()).product_id().get(); out_identity->chip_flags = 0x4; out_identity->eco_id = registers::EcoId::Get().ReadFrom( register_io_.get()).eco_id().get(); out_identity->customer_id = registers::CustomerId::Get().ReadFrom( register_io_.get()).customer_id().get(); return MAGMA_STATUS_OK; } magma_status_t MsdVslDevice::ChipOption(magma_vsl_gc_chip_option* out_option) { if (device_id() != 0x8000) { // TODO(fxb/37962): Read hardcoded values from features database instead. return DRET_MSG(MAGMA_STATUS_UNIMPLEMENTED, "unhandled device id 0x%x", device_id()); } memset(out_option, 0, sizeof(*out_option)); out_option->gpu_profiler = false; out_option->allow_fast_clear = false; out_option->power_management = false; out_option->enable_mmu = true; out_option->compression = kVslGcCompressionOptionNone; out_option->usc_l1_cache_ratio = 0; out_option->secure_mode = kVslGcSecureModeNormal; return MAGMA_STATUS_OK; } ////////////////////////////////////////////////////////////////////////////////////////////////// msd_connection_t* msd_device_open(msd_device_t* device, msd_client_id_t client_id) { auto connection = MsdVslDevice::cast(device)->Open(client_id); if (!connection) return DRETP(nullptr, "failed to create connection"); return new MsdVslAbiConnection(std::move(connection)); } void msd_device_destroy(msd_device_t* device) { delete MsdVslDevice::cast(device); } magma_status_t msd_device_query(msd_device_t* device, uint64_t id, uint64_t* value_out) { switch (id) { case MAGMA_QUERY_VENDOR_ID: // VK_VENDOR_ID_VIV *value_out = 0x10001; return MAGMA_STATUS_OK; case MAGMA_QUERY_DEVICE_ID: *value_out = MsdVslDevice::cast(device)->device_id(); return MAGMA_STATUS_OK; case MAGMA_QUERY_IS_TOTAL_TIME_SUPPORTED: *value_out = 0; return MAGMA_STATUS_OK; } return DRET_MSG(MAGMA_STATUS_INVALID_ARGS, "unhandled id %" PRIu64, id); } static magma_status_t DataToBuffer(const char* name, void* data, uint64_t size, uint32_t* buffer_out) { std::unique_ptr<magma::PlatformBuffer> buffer = magma::PlatformBuffer::Create(size, name); if (!buffer) { return DRET_MSG(MAGMA_STATUS_INTERNAL_ERROR, "Failed to allocate buffer"); } if (!buffer->Write(data, 0, size)) { return DRET_MSG(MAGMA_STATUS_INTERNAL_ERROR, "Failed to write result to buffer"); } if (!buffer->duplicate_handle(buffer_out)) { return DRET_MSG(MAGMA_STATUS_INTERNAL_ERROR, "Failed to duplicate handle"); } return MAGMA_STATUS_OK; } magma_status_t msd_device_query_returns_buffer(msd_device_t* device, uint64_t id, uint32_t* buffer_out) { switch (id) { case kMsdVslVendorQueryChipIdentity: { magma_vsl_gc_chip_identity result; magma_status_t status = MsdVslDevice::cast(device)->ChipIdentity(&result); if (status != MAGMA_STATUS_OK) { return status; } return DataToBuffer("chip_identity", &result, sizeof(result), buffer_out); } case kMsdVslVendorQueryChipOption: { magma_vsl_gc_chip_option result; magma_status_t status = MsdVslDevice::cast(device)->ChipOption(&result); if (status != MAGMA_STATUS_OK) { return status; } return DataToBuffer("chip_option", &result, sizeof(result), buffer_out); } default: return DRET_MSG(MAGMA_STATUS_UNIMPLEMENTED, "unhandled id %" PRIu64, id); } } void msd_device_dump_status(msd_device_t* device, uint32_t dump_type) {}
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Bitcoin Core developers // Copyright (c) 2014-2017 The Dash Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "amount.h" #include "base58.h" #include "chain.h" #include "core_io.h" #include "init.h" #include "instantx.h" #include "net.h" #include "policy/rbf.h" #include "rpc/server.h" #include "timedata.h" #include "util.h" #include "utilmoneystr.h" #include "validation.h" #include "wallet.h" #include "walletdb.h" #include "keepass.h" #include <stdint.h> #include <boost/assign/list_of.hpp> #include <univalue.h> using namespace std; int64_t nWalletUnlockTime; static CCriticalSection cs_nWalletUnlockTime; std::string HelpRequiringPassphrase() { return pwalletMain && pwalletMain->IsCrypted() ? "\nRequires wallet passphrase to be set with walletpassphrase call." : ""; } bool EnsureWalletIsAvailable(bool avoidException) { if (!pwalletMain) { if (!avoidException) throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (disabled)"); else return false; } return true; } void EnsureWalletIsUnlocked() { if (pwalletMain->IsLocked()) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first."); } void WalletTxToJSON(const CWalletTx& wtx, UniValue& entry) { int confirms = wtx.GetDepthInMainChain(false); bool fLocked = instantsend.IsLockedInstantSendTransaction(wtx.GetHash()); entry.push_back(Pair("confirmations", confirms)); entry.push_back(Pair("instantlock", fLocked)); if (wtx.IsCoinBase()) entry.push_back(Pair("generated", true)); if (confirms > 0) { entry.push_back(Pair("blockhash", wtx.hashBlock.GetHex())); entry.push_back(Pair("blockindex", wtx.nIndex)); entry.push_back(Pair("blocktime", mapBlockIndex[wtx.hashBlock]->GetBlockTime())); } else { entry.push_back(Pair("trusted", wtx.IsTrusted())); } uint256 hash = wtx.GetHash(); entry.push_back(Pair("txid", hash.GetHex())); UniValue conflicts(UniValue::VARR); BOOST_FOREACH(const uint256& conflict, wtx.GetConflicts()) conflicts.push_back(conflict.GetHex()); entry.push_back(Pair("walletconflicts", conflicts)); entry.push_back(Pair("time", wtx.GetTxTime())); entry.push_back(Pair("timereceived", (int64_t)wtx.nTimeReceived)); // Add opt-in RBF status std::string rbfStatus = "no"; if (confirms <= 0) { LOCK(mempool.cs); if (!mempool.exists(hash)) { if (SignalsOptInRBF(wtx)) { rbfStatus = "yes"; } else { rbfStatus = "unknown"; } } else if (IsRBFOptIn(*mempool.mapTx.find(hash), mempool)) { rbfStatus = "yes"; } } entry.push_back(Pair("bip125-replaceable", rbfStatus)); BOOST_FOREACH(const PAIRTYPE(string,string)& item, wtx.mapValue) entry.push_back(Pair(item.first, item.second)); } string AccountFromValue(const UniValue& value) { string strAccount = value.get_str(); if (strAccount == "*") throw JSONRPCError(RPC_WALLET_INVALID_ACCOUNT_NAME, "Invalid account name"); return strAccount; } UniValue getnewaddress(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() > 1) throw runtime_error( "getnewaddress ( \"account\" )\n" "\nReturns a new NewCoin address for receiving payments.\n" "If 'account' is specified (DEPRECATED), it is added to the address book \n" "so payments received with the address will be credited to 'account'.\n" "\nArguments:\n" "1. \"account\" (string, optional) DEPRECATED. The account name for the address to be linked to. If not provided, the default account \"\" is used. It can also be set to the empty string \"\" to represent the default account. The account does not need to exist, it will be created if there is no account by the given name.\n" "\nResult:\n" "\"newcoinaddress\" (string) The new newcoin address\n" "\nExamples:\n" + HelpExampleCli("getnewaddress", "") + HelpExampleRpc("getnewaddress", "") ); LOCK2(cs_main, pwalletMain->cs_wallet); // Parse the account first so we don't generate a key if there's an error string strAccount; if (params.size() > 0) strAccount = AccountFromValue(params[0]); if (!pwalletMain->IsLocked(true)) pwalletMain->TopUpKeyPool(); // Generate a new key that is added to wallet CPubKey newKey; if (!pwalletMain->GetKeyFromPool(newKey, false)) throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first"); CKeyID keyID = newKey.GetID(); pwalletMain->SetAddressBook(keyID, strAccount, "receive"); return CBitcoinAddress(keyID).ToString(); } CBitcoinAddress GetAccountAddress(string strAccount, bool bForceNew=false) { CWalletDB walletdb(pwalletMain->strWalletFile); CAccount account; walletdb.ReadAccount(strAccount, account); bool bKeyUsed = false; // Check if the current key has been used if (account.vchPubKey.IsValid()) { CScript scriptPubKey = GetScriptForDestination(account.vchPubKey.GetID()); for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end() && account.vchPubKey.IsValid(); ++it) { const CWalletTx& wtx = (*it).second; BOOST_FOREACH(const CTxOut& txout, wtx.vout) if (txout.scriptPubKey == scriptPubKey) bKeyUsed = true; } } // Generate a new key if (!account.vchPubKey.IsValid() || bForceNew || bKeyUsed) { if (!pwalletMain->GetKeyFromPool(account.vchPubKey, false)) throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first"); pwalletMain->SetAddressBook(account.vchPubKey.GetID(), strAccount, "receive"); walletdb.WriteAccount(strAccount, account); } return CBitcoinAddress(account.vchPubKey.GetID()); } UniValue getaccountaddress(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() != 1) throw runtime_error( "getaccountaddress \"account\"\n" "\nDEPRECATED. Returns the current NewCoin address for receiving payments to this account.\n" "\nArguments:\n" "1. \"account\" (string, required) The account name for the address. It can also be set to the empty string \"\" to represent the default account. The account does not need to exist, it will be created and a new address created if there is no account by the given name.\n" "\nResult:\n" "\"newcoinaddress\" (string) The account newcoin address\n" "\nExamples:\n" + HelpExampleCli("getaccountaddress", "") + HelpExampleCli("getaccountaddress", "\"\"") + HelpExampleCli("getaccountaddress", "\"myaccount\"") + HelpExampleRpc("getaccountaddress", "\"myaccount\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); // Parse the account first so we don't generate a key if there's an error string strAccount = AccountFromValue(params[0]); UniValue ret(UniValue::VSTR); ret = GetAccountAddress(strAccount).ToString(); return ret; } UniValue getrawchangeaddress(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() > 1) throw runtime_error( "getrawchangeaddress\n" "\nReturns a new NewCoin address, for receiving change.\n" "This is for use with raw transactions, NOT normal use.\n" "\nResult:\n" "\"address\" (string) The address\n" "\nExamples:\n" + HelpExampleCli("getrawchangeaddress", "") + HelpExampleRpc("getrawchangeaddress", "") ); LOCK2(cs_main, pwalletMain->cs_wallet); if (!pwalletMain->IsLocked(true)) pwalletMain->TopUpKeyPool(); CReserveKey reservekey(pwalletMain); CPubKey vchPubKey; if (!reservekey.GetReservedKey(vchPubKey, true)) throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first"); reservekey.KeepKey(); CKeyID keyID = vchPubKey.GetID(); return CBitcoinAddress(keyID).ToString(); } UniValue setaccount(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "setaccount \"newcoinaddress\" \"account\"\n" "\nDEPRECATED. Sets the account associated with the given address.\n" "\nArguments:\n" "1. \"newcoinaddress\" (string, required) The newcoin address to be associated with an account.\n" "2. \"account\" (string, required) The account to assign the address to.\n" "\nExamples:\n" + HelpExampleCli("setaccount", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" \"tabby\"") + HelpExampleRpc("setaccount", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\", \"tabby\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); CBitcoinAddress address(params[0].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid NewCoin address"); string strAccount; if (params.size() > 1) strAccount = AccountFromValue(params[1]); // Only add the account if the address is yours. if (IsMine(*pwalletMain, address.Get())) { // Detect when changing the account of an address that is the 'unused current key' of another account: if (pwalletMain->mapAddressBook.count(address.Get())) { string strOldAccount = pwalletMain->mapAddressBook[address.Get()].name; if (address == GetAccountAddress(strOldAccount)) GetAccountAddress(strOldAccount, true); } pwalletMain->SetAddressBook(address.Get(), strAccount, "receive"); } else throw JSONRPCError(RPC_MISC_ERROR, "setaccount can only be used with own address"); return NullUniValue; } UniValue getaccount(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() != 1) throw runtime_error( "getaccount \"newcoinaddress\"\n" "\nDEPRECATED. Returns the account associated with the given address.\n" "\nArguments:\n" "1. \"newcoinaddress\" (string, required) The newcoin address for account lookup.\n" "\nResult:\n" "\"accountname\" (string) the account address\n" "\nExamples:\n" + HelpExampleCli("getaccount", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\"") + HelpExampleRpc("getaccount", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); CBitcoinAddress address(params[0].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid NewCoin address"); string strAccount; map<CTxDestination, CAddressBookData>::iterator mi = pwalletMain->mapAddressBook.find(address.Get()); if (mi != pwalletMain->mapAddressBook.end() && !(*mi).second.name.empty()) strAccount = (*mi).second.name; return strAccount; } UniValue getaddressesbyaccount(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() != 1) throw runtime_error( "getaddressesbyaccount \"account\"\n" "\nDEPRECATED. Returns the list of addresses for the given account.\n" "\nArguments:\n" "1. \"account\" (string, required) The account name.\n" "\nResult:\n" "[ (json array of string)\n" " \"newcoinaddress\" (string) a newcoin address associated with the given account\n" " ,...\n" "]\n" "\nExamples:\n" + HelpExampleCli("getaddressesbyaccount", "\"tabby\"") + HelpExampleRpc("getaddressesbyaccount", "\"tabby\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); string strAccount = AccountFromValue(params[0]); // Find all addresses that have the given account UniValue ret(UniValue::VARR); BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, CAddressBookData)& item, pwalletMain->mapAddressBook) { const CBitcoinAddress& address = item.first; const string& strName = item.second.name; if (strName == strAccount) ret.push_back(address.ToString()); } return ret; } static void SendMoney(const CTxDestination &address, CAmount nValue, bool fSubtractFeeFromAmount, CWalletTx& wtxNew, bool fUseInstantSend=false, bool fUsePrivateSend=false) { CAmount curBalance = pwalletMain->GetBalance(); // Check amount if (nValue <= 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid amount"); if (nValue > curBalance) throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Insufficient funds"); if (pwalletMain->GetBroadcastTransactions() && !g_connman) throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); // Parse NewCoin address CScript scriptPubKey = GetScriptForDestination(address); // Create and send the transaction CReserveKey reservekey(pwalletMain); CAmount nFeeRequired; std::string strError; vector<CRecipient> vecSend; int nChangePosRet = -1; CRecipient recipient = {scriptPubKey, nValue, fSubtractFeeFromAmount}; vecSend.push_back(recipient); if (!pwalletMain->CreateTransaction(vecSend, wtxNew, reservekey, nFeeRequired, nChangePosRet, strError, NULL, true, fUsePrivateSend ? ONLY_DENOMINATED : ALL_COINS, fUseInstantSend)) { if (!fSubtractFeeFromAmount && nValue + nFeeRequired > pwalletMain->GetBalance()) strError = strprintf("Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!", FormatMoney(nFeeRequired)); throw JSONRPCError(RPC_WALLET_ERROR, strError); } if (!pwalletMain->CommitTransaction(wtxNew, reservekey, g_connman.get(), fUseInstantSend ? NetMsgType::TXLOCKREQUEST : NetMsgType::TX)) throw JSONRPCError(RPC_WALLET_ERROR, "Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here."); } UniValue sendtoaddress(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() < 2 || params.size() > 7) throw runtime_error( "sendtoaddress \"newcoinaddress\" amount ( \"comment\" \"comment-to\" subtractfeefromamount use_is use_ps )\n" "\nSend an amount to a given address.\n" + HelpRequiringPassphrase() + "\nArguments:\n" "1. \"newcoinaddress\" (string, required) The newcoin address to send to.\n" "2. \"amount\" (numeric or string, required) The amount in " + CURRENCY_UNIT + " to send. eg 0.1\n" "3. \"comment\" (string, optional) A comment used to store what the transaction is for. \n" " This is not part of the transaction, just kept in your wallet.\n" "4. \"comment-to\" (string, optional) A comment to store the name of the person or organization \n" " to which you're sending the transaction. This is not part of the \n" " transaction, just kept in your wallet.\n" "5. subtractfeefromamount (boolean, optional, default=false) The fee will be deducted from the amount being sent.\n" " The recipient will receive less amount of NewCoin than you enter in the amount field.\n" "6. \"use_is\" (bool, optional) Send this transaction as InstantSend (default: false)\n" "7. \"use_ps\" (bool, optional) Use anonymized funds only (default: false)\n" "\nResult:\n" "\"transactionid\" (string) The transaction id.\n" "\nExamples:\n" + HelpExampleCli("sendtoaddress", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" 0.1") + HelpExampleCli("sendtoaddress", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" 0.1 \"donation\" \"seans outpost\"") + HelpExampleCli("sendtoaddress", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" 0.1 \"\" \"\" true") + HelpExampleRpc("sendtoaddress", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\", 0.1, \"donation\", \"seans outpost\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); CBitcoinAddress address(params[0].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid NewCoin address"); // Amount CAmount nAmount = AmountFromValue(params[1]); if (nAmount <= 0) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send"); // Wallet comments CWalletTx wtx; if (params.size() > 2 && !params[2].isNull() && !params[2].get_str().empty()) wtx.mapValue["comment"] = params[2].get_str(); if (params.size() > 3 && !params[3].isNull() && !params[3].get_str().empty()) wtx.mapValue["to"] = params[3].get_str(); bool fSubtractFeeFromAmount = false; if (params.size() > 4) fSubtractFeeFromAmount = params[4].get_bool(); bool fUseInstantSend = false; bool fUsePrivateSend = false; if (params.size() > 5) fUseInstantSend = params[5].get_bool(); if (params.size() > 6) fUsePrivateSend = params[6].get_bool(); EnsureWalletIsUnlocked(); SendMoney(address.Get(), nAmount, fSubtractFeeFromAmount, wtx, fUseInstantSend, fUsePrivateSend); return wtx.GetHash().GetHex(); } UniValue instantsendtoaddress(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() < 2 || params.size() > 5) throw runtime_error( "instantsendtoaddress \"newcoinaddress\" amount ( \"comment\" \"comment-to\" subtractfeefromamount )\n" "\nSend an amount to a given address. The amount is a real and is rounded to the nearest 0.00000001\n" + HelpRequiringPassphrase() + "\nArguments:\n" "1. \"newcoinaddress\" (string, required) The newcoin address to send to.\n" "2. \"amount\" (numeric, required) The amount in btc to send. eg 0.1\n" "3. \"comment\" (string, optional) A comment used to store what the transaction is for. \n" " This is not part of the transaction, just kept in your wallet.\n" "4. \"comment-to\" (string, optional) A comment to store the name of the person or organization \n" " to which you're sending the transaction. This is not part of the \n" " transaction, just kept in your wallet.\n" "5. subtractfeefromamount (boolean, optional, default=false) The fee will be deducted from the amount being sent.\n" " The recipient will receive less amount of NewCoin than you enter in the amount field.\n" "\nResult:\n" "\"transactionid\" (string) The transaction id.\n" "\nExamples:\n" + HelpExampleCli("instantsendtoaddress", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" 0.1") + HelpExampleCli("instantsendtoaddress", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" 0.1 \"donation\" \"seans outpost\"") + HelpExampleCli("instantsendtoaddress", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" 0.1 \"\" \"\" true") + HelpExampleRpc("instantsendtoaddress", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\", 0.1, \"donation\", \"seans outpost\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); CBitcoinAddress address(params[0].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid NewCoin address"); // Amount CAmount nAmount = AmountFromValue(params[1]); if (nAmount <= 0) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send"); // Wallet comments CWalletTx wtx; if (params.size() > 2 && !params[2].isNull() && !params[2].get_str().empty()) wtx.mapValue["comment"] = params[2].get_str(); if (params.size() > 3 && !params[3].isNull() && !params[3].get_str().empty()) wtx.mapValue["to"] = params[3].get_str(); bool fSubtractFeeFromAmount = false; if (params.size() > 4) fSubtractFeeFromAmount = params[4].get_bool(); EnsureWalletIsUnlocked(); SendMoney(address.Get(), nAmount, fSubtractFeeFromAmount, wtx, true); return wtx.GetHash().GetHex(); } UniValue listaddressgroupings(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp) throw runtime_error( "listaddressgroupings\n" "\nLists groups of addresses which have had their common ownership\n" "made public by common use as inputs or as the resulting change\n" "in past transactions\n" "\nResult:\n" "[\n" " [\n" " [\n" " \"newcoinaddress\", (string) The newcoin address\n" " amount, (numeric) The amount in " + CURRENCY_UNIT + "\n" " \"account\" (string, optional) The account (DEPRECATED)\n" " ]\n" " ,...\n" " ]\n" " ,...\n" "]\n" "\nExamples:\n" + HelpExampleCli("listaddressgroupings", "") + HelpExampleRpc("listaddressgroupings", "") ); LOCK2(cs_main, pwalletMain->cs_wallet); UniValue jsonGroupings(UniValue::VARR); map<CTxDestination, CAmount> balances = pwalletMain->GetAddressBalances(); BOOST_FOREACH(set<CTxDestination> grouping, pwalletMain->GetAddressGroupings()) { UniValue jsonGrouping(UniValue::VARR); BOOST_FOREACH(CTxDestination address, grouping) { UniValue addressInfo(UniValue::VARR); addressInfo.push_back(CBitcoinAddress(address).ToString()); addressInfo.push_back(ValueFromAmount(balances[address])); { if (pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get()) != pwalletMain->mapAddressBook.end()) addressInfo.push_back(pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get())->second.name); } jsonGrouping.push_back(addressInfo); } jsonGroupings.push_back(jsonGrouping); } return jsonGroupings; } UniValue signmessage(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() != 2) throw runtime_error( "signmessage \"newcoinaddress\" \"message\"\n" "\nSign a message with the private key of an address" + HelpRequiringPassphrase() + "\n" "\nArguments:\n" "1. \"newcoinaddress\" (string, required) The newcoin address to use for the private key.\n" "2. \"message\" (string, required) The message to create a signature of.\n" "\nResult:\n" "\"signature\" (string) The signature of the message encoded in base 64\n" "\nExamples:\n" "\nUnlock the wallet for 30 seconds\n" + HelpExampleCli("walletpassphrase", "\"mypassphrase\" 30") + "\nCreate the signature\n" + HelpExampleCli("signmessage", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" \"my message\"") + "\nVerify the signature\n" + HelpExampleCli("verifymessage", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" \"signature\" \"my message\"") + "\nAs json rpc\n" + HelpExampleRpc("signmessage", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\", \"my message\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); EnsureWalletIsUnlocked(); string strAddress = params[0].get_str(); string strMessage = params[1].get_str(); CBitcoinAddress addr(strAddress); if (!addr.IsValid()) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address"); CKeyID keyID; if (!addr.GetKeyID(keyID)) throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key"); CKey key; if (!pwalletMain->GetKey(keyID, key)) throw JSONRPCError(RPC_WALLET_ERROR, "Private key not available"); CHashWriter ss(SER_GETHASH, 0); ss << strMessageMagic; ss << strMessage; vector<unsigned char> vchSig; if (!key.SignCompact(ss.GetHash(), vchSig)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed"); return EncodeBase64(&vchSig[0], vchSig.size()); } UniValue getreceivedbyaddress(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() < 1 || params.size() > 3) throw runtime_error( "getreceivedbyaddress \"newcoinaddress\" ( minconf addlockconf )\n" "\nReturns the total amount received by the given newcoinaddress in transactions with specified minimum number of confirmations.\n" "\nArguments:\n" "1. \"newcoinaddress\" (string, required) The newcoin address for transactions.\n" "2. minconf (numeric, optional, default=1) Only include transactions confirmed at least this many times.\n" "3. addlockconf (bool, optional, default=false) Whether to add " + std::to_string(nInstantSendDepth) + " confirmations to transactions locked via InstantSend.\n" "\nResult:\n" "amount (numeric) The total amount in " + CURRENCY_UNIT + " received at this address.\n" "\nExamples:\n" "\nThe amount from transactions with at least 1 confirmation\n" + HelpExampleCli("getreceivedbyaddress", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\"") + "\nThe amount including unconfirmed transactions, zero confirmations\n" + HelpExampleCli("getreceivedbyaddress", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" 0") + "\nThe amount with at least 6 confirmation, very safe\n" + HelpExampleCli("getreceivedbyaddress", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" 6") + "\nAs a json rpc call\n" + HelpExampleRpc("getreceivedbyaddress", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\", 6") ); LOCK2(cs_main, pwalletMain->cs_wallet); // NewCoin address CBitcoinAddress address = CBitcoinAddress(params[0].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid NewCoin address"); CScript scriptPubKey = GetScriptForDestination(address.Get()); if (!IsMine(*pwalletMain, scriptPubKey)) return ValueFromAmount(0); // Minimum confirmations int nMinDepth = 1; if (params.size() > 1) nMinDepth = params[1].get_int(); bool fAddLockConf = (params.size() > 2 && params[2].get_bool()); // Tally CAmount nAmount = 0; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (wtx.IsCoinBase() || !CheckFinalTx(wtx)) continue; BOOST_FOREACH(const CTxOut& txout, wtx.vout) if (txout.scriptPubKey == scriptPubKey) if (wtx.GetDepthInMainChain(fAddLockConf) >= nMinDepth) nAmount += txout.nValue; } return ValueFromAmount(nAmount); } UniValue getreceivedbyaccount(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() < 1 || params.size() > 3) throw runtime_error( "getreceivedbyaccount \"account\" ( minconf addlockconf )\n" "\nDEPRECATED. Returns the total amount received by addresses with <account> in transactions with specified minimum number of confirmations.\n" "\nArguments:\n" "1. \"account\" (string, required) The selected account, may be the default account using \"\".\n" "2. minconf (numeric, optional, default=1) Only include transactions confirmed at least this many times.\n" "3. addlockconf (bool, optional, default=false) Whether to add " + std::to_string(nInstantSendDepth) + " confirmations to transactions locked via InstantSend.\n" "\nResult:\n" "amount (numeric) The total amount in " + CURRENCY_UNIT + " received for this account.\n" "\nExamples:\n" "\nAmount received by the default account with at least 1 confirmation\n" + HelpExampleCli("getreceivedbyaccount", "\"\"") + "\nAmount received at the tabby account including unconfirmed amounts with zero confirmations\n" + HelpExampleCli("getreceivedbyaccount", "\"tabby\" 0") + "\nThe amount with at least 6 confirmation, very safe\n" + HelpExampleCli("getreceivedbyaccount", "\"tabby\" 6") + "\nAs a json rpc call\n" + HelpExampleRpc("getreceivedbyaccount", "\"tabby\", 6") ); LOCK2(cs_main, pwalletMain->cs_wallet); // Minimum confirmations int nMinDepth = 1; if (params.size() > 1) nMinDepth = params[1].get_int(); bool fAddLockConf = (params.size() > 2 && params[2].get_bool()); // Get the set of pub keys assigned to account string strAccount = AccountFromValue(params[0]); set<CTxDestination> setAddress = pwalletMain->GetAccountAddresses(strAccount); // Tally CAmount nAmount = 0; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (wtx.IsCoinBase() || !CheckFinalTx(wtx)) continue; BOOST_FOREACH(const CTxOut& txout, wtx.vout) { CTxDestination address; if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*pwalletMain, address) && setAddress.count(address)) if (wtx.GetDepthInMainChain(fAddLockConf) >= nMinDepth) nAmount += txout.nValue; } } return ValueFromAmount(nAmount); } CAmount GetAccountBalance(CWalletDB& walletdb, const string& strAccount, int nMinDepth, const isminefilter& filter, bool fAddLockConf) { CAmount nBalance = 0; // Tally wallet transactions for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (!CheckFinalTx(wtx) || wtx.GetBlocksToMaturity() > 0 || wtx.GetDepthInMainChain(fAddLockConf) < 0) continue; CAmount nReceived, nSent, nFee; wtx.GetAccountAmounts(strAccount, nReceived, nSent, nFee, filter); if (nReceived != 0 && wtx.GetDepthInMainChain(fAddLockConf) >= nMinDepth) nBalance += nReceived; nBalance -= nSent + nFee; } // Tally internal accounting entries nBalance += walletdb.GetAccountCreditDebit(strAccount); return nBalance; } CAmount GetAccountBalance(const string& strAccount, int nMinDepth, const isminefilter& filter, bool fAddLockConf) { CWalletDB walletdb(pwalletMain->strWalletFile); return GetAccountBalance(walletdb, strAccount, nMinDepth, filter, fAddLockConf); } UniValue getbalance(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() > 4) throw runtime_error( "getbalance ( \"account\" minconf addlockconf includeWatchonly )\n" "\nIf account is not specified, returns the server's total available balance.\n" "If account is specified (DEPRECATED), returns the balance in the account.\n" "Note that the account \"\" is not the same as leaving the parameter out.\n" "The server total may be different to the balance in the default \"\" account.\n" "\nArguments:\n" "1. \"account\" (string, optional) DEPRECATED. The selected account, or \"*\" for entire wallet. It may be the default account using \"\".\n" "2. minconf (numeric, optional, default=1) Only include transactions confirmed at least this many times.\n" "3. addlockconf (bool, optional, default=false) Whether to add " + std::to_string(nInstantSendDepth) + " confirmations to transactions locked via InstantSend.\n" "4. includeWatchonly (bool, optional, default=false) Also include balance in watchonly addresses (see 'importaddress')\n" "\nResult:\n" "amount (numeric) The total amount in " + CURRENCY_UNIT + " received for this account.\n" "\nExamples:\n" "\nThe total amount in the wallet\n" + HelpExampleCli("getbalance", "") + "\nThe total amount in the wallet at least 5 blocks confirmed\n" + HelpExampleCli("getbalance", "\"*\" 6") + "\nAs a json rpc call\n" + HelpExampleRpc("getbalance", "\"*\", 6") ); LOCK2(cs_main, pwalletMain->cs_wallet); if (params.size() == 0) return ValueFromAmount(pwalletMain->GetBalance()); int nMinDepth = 1; if (params.size() > 1) nMinDepth = params[1].get_int(); bool fAddLockConf = (params.size() > 2 && params[2].get_bool()); isminefilter filter = ISMINE_SPENDABLE; if(params.size() > 3) if(params[3].get_bool()) filter = filter | ISMINE_WATCH_ONLY; if (params[0].get_str() == "*") { // Calculate total balance a different way from GetBalance() // (GetBalance() sums up all unspent TxOuts) // getbalance and "getbalance * 1 true" should return the same number CAmount nBalance = 0; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (!CheckFinalTx(wtx) || wtx.GetBlocksToMaturity() > 0 || wtx.GetDepthInMainChain() < 0) continue; CAmount allFee; string strSentAccount; list<COutputEntry> listReceived; list<COutputEntry> listSent; wtx.GetAmounts(listReceived, listSent, allFee, strSentAccount, filter); if (wtx.GetDepthInMainChain(fAddLockConf) >= nMinDepth) { BOOST_FOREACH(const COutputEntry& r, listReceived) nBalance += r.amount; } BOOST_FOREACH(const COutputEntry& s, listSent) nBalance -= s.amount; nBalance -= allFee; } return ValueFromAmount(nBalance); } string strAccount = AccountFromValue(params[0]); CAmount nBalance = GetAccountBalance(strAccount, nMinDepth, filter, fAddLockConf); return ValueFromAmount(nBalance); } UniValue getunconfirmedbalance(const UniValue &params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() > 0) throw runtime_error( "getunconfirmedbalance\n" "Returns the server's total unconfirmed balance\n"); LOCK2(cs_main, pwalletMain->cs_wallet); return ValueFromAmount(pwalletMain->GetUnconfirmedBalance()); } UniValue movecmd(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() < 3 || params.size() > 5) throw runtime_error( "move \"fromaccount\" \"toaccount\" amount ( minconf \"comment\" )\n" "\nDEPRECATED. Move a specified amount from one account in your wallet to another.\n" "\nArguments:\n" "1. \"fromaccount\" (string, required) The name of the account to move funds from. May be the default account using \"\".\n" "2. \"toaccount\" (string, required) The name of the account to move funds to. May be the default account using \"\".\n" "3. amount (numeric) Quantity of " + CURRENCY_UNIT + " to move between accounts.\n" "4. minconf (numeric, optional, default=1) Only use funds with at least this many confirmations.\n" "5. \"comment\" (string, optional) An optional comment, stored in the wallet only.\n" "\nResult:\n" "true|false (boolean) true if successful.\n" "\nExamples:\n" "\nMove 0.01 " + CURRENCY_UNIT + " from the default account to the account named tabby\n" + HelpExampleCli("move", "\"\" \"tabby\" 0.01") + "\nMove 0.01 " + CURRENCY_UNIT + " timotei to akiko with a comment and funds have 6 confirmations\n" + HelpExampleCli("move", "\"timotei\" \"akiko\" 0.01 6 \"happy birthday!\"") + "\nAs a json rpc call\n" + HelpExampleRpc("move", "\"timotei\", \"akiko\", 0.01, 6, \"happy birthday!\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); string strFrom = AccountFromValue(params[0]); string strTo = AccountFromValue(params[1]); CAmount nAmount = AmountFromValue(params[2]); if (nAmount <= 0) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send"); if (params.size() > 3) // unused parameter, used to be nMinDepth, keep type-checking it though (void)params[3].get_int(); string strComment; if (params.size() > 4) strComment = params[4].get_str(); CWalletDB walletdb(pwalletMain->strWalletFile); if (!walletdb.TxnBegin()) throw JSONRPCError(RPC_DATABASE_ERROR, "database error"); int64_t nNow = GetAdjustedTime(); // Debit CAccountingEntry debit; debit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb); debit.strAccount = strFrom; debit.nCreditDebit = -nAmount; debit.nTime = nNow; debit.strOtherAccount = strTo; debit.strComment = strComment; pwalletMain->AddAccountingEntry(debit, walletdb); // Credit CAccountingEntry credit; credit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb); credit.strAccount = strTo; credit.nCreditDebit = nAmount; credit.nTime = nNow; credit.strOtherAccount = strFrom; credit.strComment = strComment; pwalletMain->AddAccountingEntry(credit, walletdb); if (!walletdb.TxnCommit()) throw JSONRPCError(RPC_DATABASE_ERROR, "database error"); return true; } UniValue sendfrom(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() < 3 || params.size() > 7) throw runtime_error( "sendfrom \"fromaccount\" \"tonewcoinaddress\" amount ( minconf addlockconf \"comment\" \"comment-to\" )\n" "\nDEPRECATED (use sendtoaddress). Sent an amount from an account to a newcoin address." + HelpRequiringPassphrase() + "\n" "\nArguments:\n" "1. \"fromaccount\" (string, required) The name of the account to send funds from. May be the default account using \"\".\n" "2. \"tonewcoinaddress\" (string, required) The newcoin address to send funds to.\n" "3. amount (numeric or string, required) The amount in " + CURRENCY_UNIT + " (transaction fee is added on top).\n" "4. minconf (numeric, optional, default=1) Only use funds with at least this many confirmations.\n" "5. addlockconf (bool, optional, default=false) Whether to add " + std::to_string(nInstantSendDepth) + " confirmations to transactions locked via InstantSend.\n" "6. \"comment\" (string, optional) A comment used to store what the transaction is for. \n" " This is not part of the transaction, just kept in your wallet.\n" "7. \"comment-to\" (string, optional) An optional comment to store the name of the person or organization \n" " to which you're sending the transaction. This is not part of the transaction, \n" " it is just kept in your wallet.\n" "\nResult:\n" "\"transactionid\" (string) The transaction id.\n" "\nExamples:\n" "\nSend 0.01 " + CURRENCY_UNIT + " from the default account to the address, must have at least 1 confirmation\n" + HelpExampleCli("sendfrom", "\"\" \"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" 0.01") + "\nSend 0.01 from the tabby account to the given address, funds must have at least 6 confirmations\n" + HelpExampleCli("sendfrom", "\"tabby\" \"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" 0.01 6 false \"donation\" \"seans outpost\"") + "\nAs a json rpc call\n" + HelpExampleRpc("sendfrom", "\"tabby\", \"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\", 0.01, 6, false, \"donation\", \"seans outpost\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); string strAccount = AccountFromValue(params[0]); CBitcoinAddress address(params[1].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid NewCoin address"); CAmount nAmount = AmountFromValue(params[2]); if (nAmount <= 0) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send"); int nMinDepth = 1; if (params.size() > 3) nMinDepth = params[3].get_int(); bool fAddLockConf = (params.size() > 4 && params[4].get_bool()); CWalletTx wtx; wtx.strFromAccount = strAccount; if (params.size() > 5 && !params[5].isNull() && !params[5].get_str().empty()) wtx.mapValue["comment"] = params[5].get_str(); if (params.size() > 6 && !params[6].isNull() && !params[6].get_str().empty()) wtx.mapValue["to"] = params[6].get_str(); EnsureWalletIsUnlocked(); // Check funds CAmount nBalance = GetAccountBalance(strAccount, nMinDepth, ISMINE_SPENDABLE, fAddLockConf); if (nAmount > nBalance) throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds"); SendMoney(address.Get(), nAmount, false, wtx); return wtx.GetHash().GetHex(); } UniValue sendmany(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() < 2 || params.size() > 8) throw runtime_error( "sendmany \"fromaccount\" {\"address\":amount,...} ( minconf addlockconf \"comment\" [\"address\",...] subtractfeefromamount use_is use_ps )\n" "\nSend multiple times. Amounts are double-precision floating point numbers." + HelpRequiringPassphrase() + "\n" "\nArguments:\n" "1. \"fromaccount\" (string, required) DEPRECATED. The account to send the funds from. Should be \"\" for the default account\n" "2. \"amounts\" (string, required) A json object with addresses and amounts\n" " {\n" " \"address\":amount (numeric or string) The newcoin address is the key, the numeric amount (can be string) in " + CURRENCY_UNIT + " is the value\n" " ,...\n" " }\n" "3. minconf (numeric, optional, default=1) Only use the balance confirmed at least this many times.\n" "4. addlockconf (bool, optional, default=false) Whether to add " + std::to_string(nInstantSendDepth) + " confirmations to transactions locked via InstantSend.\n" "5. \"comment\" (string, optional) A comment\n" "6. subtractfeefromamount (string, optional) A json array with addresses.\n" " The fee will be equally deducted from the amount of each selected address.\n" " Those recipients will receive less newcoins than you enter in their corresponding amount field.\n" " If no addresses are specified here, the sender pays the fee.\n" " [\n" " \"address\" (string) Subtract fee from this address\n" " ,...\n" " ]\n" "7. \"use_is\" (bool, optional) Send this transaction as InstantSend (default: false)\n" "8. \"use_ps\" (bool, optional) Use anonymized funds only (default: false)\n" "\nResult:\n" "\"transactionid\" (string) The transaction id for the send. Only 1 transaction is created regardless of \n" " the number of addresses.\n" "\nExamples:\n" "\nSend two amounts to two different addresses:\n" + HelpExampleCli("sendmany", "\"tabby\" \"{\\\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\\\":0.01,\\\"XuQQkwA4FYkq2XERzMY2CiAZhJTEDAbtcg\\\":0.02}\"") + "\nSend two amounts to two different addresses setting the confirmation and comment:\n" + HelpExampleCli("sendmany", "\"tabby\" \"{\\\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\\\":0.01,\\\"XuQQkwA4FYkq2XERzMY2CiAZhJTEDAbtcg\\\":0.02}\" 6 false \"testing\"") + "\nAs a json rpc call\n" + HelpExampleRpc("sendmany", "\"tabby\", \"{\\\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\\\":0.01,\\\"XuQQkwA4FYkq2XERzMY2CiAZhJTEDAbtcg\\\":0.02}\", 6, false, \"testing\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); if (pwalletMain->GetBroadcastTransactions() && !g_connman) throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); string strAccount = AccountFromValue(params[0]); UniValue sendTo = params[1].get_obj(); int nMinDepth = 1; if (params.size() > 2) nMinDepth = params[2].get_int(); bool fAddLockConf = (params.size() > 3 && params[3].get_bool()); CWalletTx wtx; wtx.strFromAccount = strAccount; if (params.size() > 4 && !params[4].isNull() && !params[4].get_str().empty()) wtx.mapValue["comment"] = params[4].get_str(); UniValue subtractFeeFromAmount(UniValue::VARR); if (params.size() > 5) subtractFeeFromAmount = params[5].get_array(); set<CBitcoinAddress> setAddress; vector<CRecipient> vecSend; CAmount totalAmount = 0; vector<string> keys = sendTo.getKeys(); BOOST_FOREACH(const string& name_, keys) { CBitcoinAddress address(name_); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid NewCoin address: ")+name_); if (setAddress.count(address)) throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+name_); setAddress.insert(address); CScript scriptPubKey = GetScriptForDestination(address.Get()); CAmount nAmount = AmountFromValue(sendTo[name_]); if (nAmount <= 0) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send"); totalAmount += nAmount; bool fSubtractFeeFromAmount = false; for (unsigned int idx = 0; idx < subtractFeeFromAmount.size(); idx++) { const UniValue& addr = subtractFeeFromAmount[idx]; if (addr.get_str() == name_) fSubtractFeeFromAmount = true; } CRecipient recipient = {scriptPubKey, nAmount, fSubtractFeeFromAmount}; vecSend.push_back(recipient); } EnsureWalletIsUnlocked(); // Check funds CAmount nBalance = GetAccountBalance(strAccount, nMinDepth, ISMINE_SPENDABLE, fAddLockConf); if (totalAmount > nBalance) throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds"); // Send CReserveKey keyChange(pwalletMain); CAmount nFeeRequired = 0; int nChangePosRet = -1; string strFailReason; bool fUseInstantSend = false; bool fUsePrivateSend = false; if (params.size() > 6) fUseInstantSend = params[6].get_bool(); if (params.size() > 7) fUsePrivateSend = params[7].get_bool(); bool fCreated = pwalletMain->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired, nChangePosRet, strFailReason, NULL, true, fUsePrivateSend ? ONLY_DENOMINATED : ALL_COINS, fUseInstantSend); if (!fCreated) throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, strFailReason); if (!pwalletMain->CommitTransaction(wtx, keyChange, g_connman.get(), fUseInstantSend ? NetMsgType::TXLOCKREQUEST : NetMsgType::TX)) throw JSONRPCError(RPC_WALLET_ERROR, "Transaction commit failed"); return wtx.GetHash().GetHex(); } // Defined in rpc/misc.cpp extern CScript _createmultisig_redeemScript(const UniValue& params); UniValue addmultisigaddress(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() < 2 || params.size() > 3) { string msg = "addmultisigaddress nrequired [\"key\",...] ( \"account\" )\n" "\nAdd a nrequired-to-sign multisignature address to the wallet.\n" "Each key is a NewCoin address or hex-encoded public key.\n" "If 'account' is specified (DEPRECATED), assign address to that account.\n" "\nArguments:\n" "1. nrequired (numeric, required) The number of required signatures out of the n keys or addresses.\n" "2. \"keysobject\" (string, required) A json array of newcoin addresses or hex-encoded public keys\n" " [\n" " \"address\" (string) newcoin address or hex-encoded public key\n" " ...,\n" " ]\n" "3. \"account\" (string, optional) DEPRECATED. An account to assign the addresses to.\n" "\nResult:\n" "\"newcoinaddress\" (string) A newcoin address associated with the keys.\n" "\nExamples:\n" "\nAdd a multisig address from 2 addresses\n" + HelpExampleCli("addmultisigaddress", "2 \"[\\\"Xt4qk9uKvQYAonVGSZNXqxeDmtjaEWgfrs\\\",\\\"XoSoWQkpgLpppPoyyzbUFh1fq2RBvW6UK1\\\"]\"") + "\nAs json rpc call\n" + HelpExampleRpc("addmultisigaddress", "2, \"[\\\"Xt4qk9uKvQYAonVGSZNXqxeDmtjaEWgfrs\\\",\\\"XoSoWQkpgLpppPoyyzbUFh1fq2RBvW6UK1\\\"]\"") ; throw runtime_error(msg); } LOCK2(cs_main, pwalletMain->cs_wallet); string strAccount; if (params.size() > 2) strAccount = AccountFromValue(params[2]); // Construct using pay-to-script-hash: CScript inner = _createmultisig_redeemScript(params); CScriptID innerID(inner); pwalletMain->AddCScript(inner); pwalletMain->SetAddressBook(innerID, strAccount, "send"); return CBitcoinAddress(innerID).ToString(); } struct tallyitem { CAmount nAmount; int nConf; vector<uint256> txids; bool fIsWatchonly; tallyitem() { nAmount = 0; nConf = std::numeric_limits<int>::max(); fIsWatchonly = false; } }; UniValue ListReceived(const UniValue& params, bool fByAccounts) { // Minimum confirmations int nMinDepth = 1; if (params.size() > 0) nMinDepth = params[0].get_int(); bool fAddLockConf = (params.size() > 1 && params[1].get_bool()); // Whether to include empty accounts bool fIncludeEmpty = false; if (params.size() > 2) fIncludeEmpty = params[2].get_bool(); isminefilter filter = ISMINE_SPENDABLE; if(params.size() > 3) if(params[3].get_bool()) filter = filter | ISMINE_WATCH_ONLY; // Tally map<CBitcoinAddress, tallyitem> mapTally; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (wtx.IsCoinBase() || !CheckFinalTx(wtx)) continue; int nDepth = wtx.GetDepthInMainChain(fAddLockConf); if (nDepth < nMinDepth) continue; BOOST_FOREACH(const CTxOut& txout, wtx.vout) { CTxDestination address; if (!ExtractDestination(txout.scriptPubKey, address)) continue; isminefilter mine = IsMine(*pwalletMain, address); if(!(mine & filter)) continue; tallyitem& item = mapTally[address]; item.nAmount += txout.nValue; item.nConf = min(item.nConf, nDepth); item.txids.push_back(wtx.GetHash()); if (mine & ISMINE_WATCH_ONLY) item.fIsWatchonly = true; } } // Reply UniValue ret(UniValue::VARR); map<string, tallyitem> mapAccountTally; BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, CAddressBookData)& item, pwalletMain->mapAddressBook) { const CBitcoinAddress& address = item.first; const string& strAccount = item.second.name; map<CBitcoinAddress, tallyitem>::iterator it = mapTally.find(address); if (it == mapTally.end() && !fIncludeEmpty) continue; isminefilter mine = IsMine(*pwalletMain, address.Get()); if(!(mine & filter)) continue; CAmount nAmount = 0; int nConf = std::numeric_limits<int>::max(); bool fIsWatchonly = false; if (it != mapTally.end()) { nAmount = (*it).second.nAmount; nConf = (*it).second.nConf; fIsWatchonly = (*it).second.fIsWatchonly; } if (fByAccounts) { tallyitem& item = mapAccountTally[strAccount]; item.nAmount += nAmount; item.nConf = min(item.nConf, nConf); item.fIsWatchonly = fIsWatchonly; } else { UniValue obj(UniValue::VOBJ); if(fIsWatchonly) obj.push_back(Pair("involvesWatchonly", true)); obj.push_back(Pair("address", address.ToString())); obj.push_back(Pair("account", strAccount)); obj.push_back(Pair("amount", ValueFromAmount(nAmount))); obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf))); if (!fByAccounts) obj.push_back(Pair("label", strAccount)); UniValue transactions(UniValue::VARR); if (it != mapTally.end()) { BOOST_FOREACH(const uint256& item, (*it).second.txids) { transactions.push_back(item.GetHex()); } } obj.push_back(Pair("txids", transactions)); ret.push_back(obj); } } if (fByAccounts) { for (map<string, tallyitem>::iterator it = mapAccountTally.begin(); it != mapAccountTally.end(); ++it) { CAmount nAmount = (*it).second.nAmount; int nConf = (*it).second.nConf; UniValue obj(UniValue::VOBJ); if((*it).second.fIsWatchonly) obj.push_back(Pair("involvesWatchonly", true)); obj.push_back(Pair("account", (*it).first)); obj.push_back(Pair("amount", ValueFromAmount(nAmount))); obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf))); ret.push_back(obj); } } return ret; } UniValue listreceivedbyaddress(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() > 4) throw runtime_error( "listreceivedbyaddress ( minconf addlockconf includeempty includeWatchonly)\n" "\nList balances by receiving address.\n" "\nArguments:\n" "1. minconf (numeric, optional, default=1) The minimum number of confirmations before payments are included.\n" "2. addlockconf (bool, optional, default=false) Whether to add " + std::to_string(nInstantSendDepth) + " confirmations to transactions locked via InstantSend.\n" "3. includeempty (bool, optional, default=false) Whether to include addresses that haven't received any payments.\n" "4. includeWatchonly (bool, optional, default=false) Whether to include watchonly addresses (see 'importaddress').\n" "\nResult:\n" "[\n" " {\n" " \"involvesWatchonly\" : true, (bool) Only returned if imported addresses were involved in transaction\n" " \"address\" : \"receivingaddress\", (string) The receiving address\n" " \"account\" : \"accountname\", (string) DEPRECATED. The account of the receiving address. The default account is \"\".\n" " \"amount\" : x.xxx, (numeric) The total amount in " + CURRENCY_UNIT + " received by the address\n" " \"confirmations\" : n (numeric) The number of confirmations of the most recent transaction included.\n" " If 'addlockconf' is true, the minimum number of confirmations is calculated\n" " including additional " + std::to_string(nInstantSendDepth) + " confirmations for transactions locked via InstantSend\n" " \"label\" : \"label\" (string) A comment for the address/transaction, if any\n" " }\n" " ,...\n" "]\n" "\nExamples:\n" + HelpExampleCli("listreceivedbyaddress", "") + HelpExampleCli("listreceivedbyaddress", "6 false true") + HelpExampleRpc("listreceivedbyaddress", "6, false, true, true") ); LOCK2(cs_main, pwalletMain->cs_wallet); return ListReceived(params, false); } UniValue listreceivedbyaccount(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() > 4) throw runtime_error( "listreceivedbyaccount ( minconf addlockconf includeempty includeWatchonly)\n" "\nDEPRECATED. List balances by account.\n" "\nArguments:\n" "1. minconf (numeric, optional, default=1) The minimum number of confirmations before payments are included.\n" "2. addlockconf (bool, optional, default=false) Whether to add " + std::to_string(nInstantSendDepth) + " confirmations to transactions locked via InstantSend.\n" "3. includeempty (bool, optional, default=false) Whether to include accounts that haven't received any payments.\n" "4. includeWatchonly (bool, optional, default=false) Whether to include watchonly addresses (see 'importaddress').\n" "\nResult:\n" "[\n" " {\n" " \"involvesWatchonly\" : true, (bool) Only returned if imported addresses were involved in transaction\n" " \"account\" : \"accountname\", (string) The account name of the receiving account\n" " \"amount\" : x.xxx, (numeric) The total amount received by addresses with this account\n" " \"confirmations\" : n (numeric) The number of blockchain confirmations of the most recent transaction included\n" " \"label\" : \"label\" (string) A comment for the address/transaction, if any\n" " }\n" " ,...\n" "]\n" "\nExamples:\n" + HelpExampleCli("listreceivedbyaccount", "") + HelpExampleCli("listreceivedbyaccount", "6 false true") + HelpExampleRpc("listreceivedbyaccount", "6, false, true, true") ); LOCK2(cs_main, pwalletMain->cs_wallet); return ListReceived(params, true); } static void MaybePushAddress(UniValue & entry, const CTxDestination &dest) { CBitcoinAddress addr; if (addr.Set(dest)) entry.push_back(Pair("address", addr.ToString())); } void ListTransactions(const CWalletTx& wtx, const string& strAccount, int nMinDepth, bool fLong, UniValue& ret, const isminefilter& filter) { CAmount nFee; string strSentAccount; list<COutputEntry> listReceived; list<COutputEntry> listSent; wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount, filter); bool fAllAccounts = (strAccount == string("*")); bool involvesWatchonly = wtx.IsFromMe(ISMINE_WATCH_ONLY); // Sent if ((!listSent.empty() || nFee != 0) && (fAllAccounts || strAccount == strSentAccount)) { BOOST_FOREACH(const COutputEntry& s, listSent) { UniValue entry(UniValue::VOBJ); if(involvesWatchonly || (::IsMine(*pwalletMain, s.destination) & ISMINE_WATCH_ONLY)) entry.push_back(Pair("involvesWatchonly", true)); entry.push_back(Pair("account", strSentAccount)); MaybePushAddress(entry, s.destination); std::map<std::string, std::string>::const_iterator it = wtx.mapValue.find("DS"); entry.push_back(Pair("category", (it != wtx.mapValue.end() && it->second == "1") ? "privatesend" : "send")); entry.push_back(Pair("amount", ValueFromAmount(-s.amount))); if (pwalletMain->mapAddressBook.count(s.destination)) entry.push_back(Pair("label", pwalletMain->mapAddressBook[s.destination].name)); entry.push_back(Pair("vout", s.vout)); entry.push_back(Pair("fee", ValueFromAmount(-nFee))); if (fLong) WalletTxToJSON(wtx, entry); entry.push_back(Pair("abandoned", wtx.isAbandoned())); ret.push_back(entry); } } // Received if (listReceived.size() > 0 && wtx.GetDepthInMainChain() >= nMinDepth) { BOOST_FOREACH(const COutputEntry& r, listReceived) { string account; if (pwalletMain->mapAddressBook.count(r.destination)) account = pwalletMain->mapAddressBook[r.destination].name; if (fAllAccounts || (account == strAccount)) { UniValue entry(UniValue::VOBJ); if(involvesWatchonly || (::IsMine(*pwalletMain, r.destination) & ISMINE_WATCH_ONLY)) entry.push_back(Pair("involvesWatchonly", true)); entry.push_back(Pair("account", account)); MaybePushAddress(entry, r.destination); if (wtx.IsCoinBase()) { if (wtx.GetDepthInMainChain() < 1) entry.push_back(Pair("category", "orphan")); else if (wtx.GetBlocksToMaturity() > 0) entry.push_back(Pair("category", "immature")); else entry.push_back(Pair("category", "generate")); } else { entry.push_back(Pair("category", "receive")); } entry.push_back(Pair("amount", ValueFromAmount(r.amount))); if (pwalletMain->mapAddressBook.count(r.destination)) entry.push_back(Pair("label", account)); entry.push_back(Pair("vout", r.vout)); if (fLong) WalletTxToJSON(wtx, entry); ret.push_back(entry); } } } } void AcentryToJSON(const CAccountingEntry& acentry, const string& strAccount, UniValue& ret) { bool fAllAccounts = (strAccount == string("*")); if (fAllAccounts || acentry.strAccount == strAccount) { UniValue entry(UniValue::VOBJ); entry.push_back(Pair("account", acentry.strAccount)); entry.push_back(Pair("category", "move")); entry.push_back(Pair("time", acentry.nTime)); entry.push_back(Pair("amount", ValueFromAmount(acentry.nCreditDebit))); entry.push_back(Pair("otheraccount", acentry.strOtherAccount)); entry.push_back(Pair("comment", acentry.strComment)); ret.push_back(entry); } } UniValue listtransactions(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() > 4) throw runtime_error( "listtransactions ( \"account\" count from includeWatchonly)\n" "\nReturns up to 'count' most recent transactions skipping the first 'from' transactions for account 'account'.\n" "\nArguments:\n" "1. \"account\" (string, optional) DEPRECATED. The account name. Should be \"*\".\n" "2. count (numeric, optional, default=10) The number of transactions to return\n" "3. from (numeric, optional, default=0) The number of transactions to skip\n" "4. includeWatchonly (bool, optional, default=false) Include transactions to watchonly addresses (see 'importaddress')\n" "\nResult:\n" "[\n" " {\n" " \"account\":\"accountname\", (string) DEPRECATED. The account name associated with the transaction. \n" " It will be \"\" for the default account.\n" " \"address\":\"newcoinaddress\", (string) The newcoin address of the transaction. Not present for \n" " move transactions (category = move).\n" " \"category\":\"send|receive|move\", (string) The transaction category. 'move' is a local (off blockchain)\n" " transaction between accounts, and not associated with an address,\n" " transaction id or block. 'send' and 'receive' transactions are \n" " associated with an address, transaction id and block details\n" " \"amount\": x.xxx, (numeric) The amount in " + CURRENCY_UNIT + ". This is negative for the 'send' category, and for the\n" " 'move' category for moves outbound. It is positive for the 'receive' category,\n" " and for the 'move' category for inbound funds.\n" " \"vout\": n, (numeric) the vout value\n" " \"fee\": x.xxx, (numeric) The amount of the fee in " + CURRENCY_UNIT + ". This is negative and only available for the \n" " 'send' category of transactions.\n" " \"instantlock\" : true|false, (bool) Current transaction lock state. Available for 'send' and 'receive' category of transactions.\n" " \"confirmations\": n, (numeric) The number of blockchain confirmations for the transaction. Available for 'send' and \n" " 'receive' category of transactions. Negative confirmations indicate the\n" " transation conflicts with the block chain\n" " \"trusted\": xxx (bool) Whether we consider the outputs of this unconfirmed transaction safe to spend.\n" " \"blockhash\": \"hashvalue\", (string) The block hash containing the transaction. Available for 'send' and 'receive'\n" " category of transactions.\n" " \"blockindex\": n, (numeric) The index of the transaction in the block that includes it. Available for 'send' and 'receive'\n" " category of transactions.\n" " \"blocktime\": xxx, (numeric) The block time in seconds since epoch (1 Jan 1970 GMT).\n" " \"txid\": \"transactionid\", (string) The transaction id. Available for 'send' and 'receive' category of transactions.\n" " \"time\": xxx, (numeric) The transaction time in seconds since epoch (midnight Jan 1 1970 GMT).\n" " \"timereceived\": xxx, (numeric) The time received in seconds since epoch (midnight Jan 1 1970 GMT). Available \n" " for 'send' and 'receive' category of transactions.\n" " \"comment\": \"...\", (string) If a comment is associated with the transaction.\n" " \"label\": \"label\" (string) A comment for the address/transaction, if any\n" " \"otheraccount\": \"accountname\", (string) For the 'move' category of transactions, the account the funds came \n" " from (for receiving funds, positive amounts), or went to (for sending funds,\n" " negative amounts).\n" " \"bip125-replaceable\": \"yes|no|unknown\" (string) Whether this transaction could be replaced due to BIP125 (replace-by-fee);\n" " may be unknown for unconfirmed transactions not in the mempool\n" " }\n" "]\n" "\nExamples:\n" "\nList the most recent 10 transactions in the systems\n" + HelpExampleCli("listtransactions", "") + "\nList transactions 100 to 120\n" + HelpExampleCli("listtransactions", "\"*\" 20 100") + "\nAs a json rpc call\n" + HelpExampleRpc("listtransactions", "\"*\", 20, 100") ); LOCK2(cs_main, pwalletMain->cs_wallet); string strAccount = "*"; if (params.size() > 0) strAccount = params[0].get_str(); int nCount = 10; if (params.size() > 1) nCount = params[1].get_int(); int nFrom = 0; if (params.size() > 2) nFrom = params[2].get_int(); isminefilter filter = ISMINE_SPENDABLE; if(params.size() > 3) if(params[3].get_bool()) filter = filter | ISMINE_WATCH_ONLY; if (nCount < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative count"); if (nFrom < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative from"); UniValue ret(UniValue::VARR); const CWallet::TxItems & txOrdered = pwalletMain->wtxOrdered; // iterate backwards until we have nCount items to return: for (CWallet::TxItems::const_reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) { CWalletTx *const pwtx = (*it).second.first; if (pwtx != 0) ListTransactions(*pwtx, strAccount, 0, true, ret, filter); CAccountingEntry *const pacentry = (*it).second.second; if (pacentry != 0) AcentryToJSON(*pacentry, strAccount, ret); if ((int)ret.size() >= (nCount+nFrom)) break; } // ret is newest to oldest if (nFrom > (int)ret.size()) nFrom = ret.size(); if ((nFrom + nCount) > (int)ret.size()) nCount = ret.size() - nFrom; vector<UniValue> arrTmp = ret.getValues(); vector<UniValue>::iterator first = arrTmp.begin(); std::advance(first, nFrom); vector<UniValue>::iterator last = arrTmp.begin(); std::advance(last, nFrom+nCount); if (last != arrTmp.end()) arrTmp.erase(last, arrTmp.end()); if (first != arrTmp.begin()) arrTmp.erase(arrTmp.begin(), first); std::reverse(arrTmp.begin(), arrTmp.end()); // Return oldest to newest ret.clear(); ret.setArray(); ret.push_backV(arrTmp); return ret; } UniValue listaccounts(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() > 3) throw runtime_error( "listaccounts ( minconf addlockconf includeWatchonly)\n" "\nDEPRECATED. Returns Object that has account names as keys, account balances as values.\n" "\nArguments:\n" "1. minconf (numeric, optional, default=1) Only include transactions with at least this many confirmations\n" "2. addlockconf (bool, optional, default=false) Whether to add " + std::to_string(nInstantSendDepth) + " confirmations to transactions locked via InstantSend.\n" "3. includeWatchonly (bool, optional, default=false) Include balances in watchonly addresses (see 'importaddress')\n" "\nResult:\n" "{ (json object where keys are account names, and values are numeric balances\n" " \"account\": x.xxx, (numeric) The property name is the account name, and the value is the total balance for the account.\n" " ...\n" "}\n" "\nExamples:\n" "\nList account balances where there at least 1 confirmation\n" + HelpExampleCli("listaccounts", "") + "\nList account balances including zero confirmation transactions\n" + HelpExampleCli("listaccounts", "0") + "\nList account balances for 6 or more confirmations\n" + HelpExampleCli("listaccounts", "6") + "\nAs json rpc call\n" + HelpExampleRpc("listaccounts", "6") ); LOCK2(cs_main, pwalletMain->cs_wallet); int nMinDepth = 1; if (params.size() > 0) nMinDepth = params[0].get_int(); bool fAddLockConf = (params.size() > 1 && params[1].get_bool()); isminefilter includeWatchonly = ISMINE_SPENDABLE; if(params.size() > 2) if(params[2].get_bool()) includeWatchonly = includeWatchonly | ISMINE_WATCH_ONLY; map<string, CAmount> mapAccountBalances; BOOST_FOREACH(const PAIRTYPE(CTxDestination, CAddressBookData)& entry, pwalletMain->mapAddressBook) { if (IsMine(*pwalletMain, entry.first) & includeWatchonly) // This address belongs to me mapAccountBalances[entry.second.name] = 0; } for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; CAmount nFee; string strSentAccount; list<COutputEntry> listReceived; list<COutputEntry> listSent; int nDepth = wtx.GetDepthInMainChain(fAddLockConf); if (wtx.GetBlocksToMaturity() > 0 || nDepth < 0) continue; wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount, includeWatchonly); mapAccountBalances[strSentAccount] -= nFee; BOOST_FOREACH(const COutputEntry& s, listSent) mapAccountBalances[strSentAccount] -= s.amount; if (nDepth >= nMinDepth) { BOOST_FOREACH(const COutputEntry& r, listReceived) if (pwalletMain->mapAddressBook.count(r.destination)) mapAccountBalances[pwalletMain->mapAddressBook[r.destination].name] += r.amount; else mapAccountBalances[""] += r.amount; } } const list<CAccountingEntry> & acentries = pwalletMain->laccentries; BOOST_FOREACH(const CAccountingEntry& entry, acentries) mapAccountBalances[entry.strAccount] += entry.nCreditDebit; UniValue ret(UniValue::VOBJ); BOOST_FOREACH(const PAIRTYPE(string, CAmount)& accountBalance, mapAccountBalances) { ret.push_back(Pair(accountBalance.first, ValueFromAmount(accountBalance.second))); } return ret; } UniValue listsinceblock(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp) throw runtime_error( "listsinceblock ( \"blockhash\" target-confirmations includeWatchonly)\n" "\nGet all transactions in blocks since block [blockhash], or all transactions if omitted\n" "\nArguments:\n" "1. \"blockhash\" (string, optional) The block hash to list transactions since\n" "2. target-confirmations: (numeric, optional) The confirmations required, must be 1 or more\n" "3. includeWatchonly: (bool, optional, default=false) Include transactions to watchonly addresses (see 'importaddress')" "\nResult:\n" "{\n" " \"transactions\": [\n" " \"account\":\"accountname\", (string) DEPRECATED. The account name associated with the transaction. Will be \"\" for the default account.\n" " \"address\":\"newcoinaddress\", (string) The newcoin address of the transaction. Not present for move transactions (category = move).\n" " \"category\":\"send|receive\", (string) The transaction category. 'send' has negative amounts, 'receive' has positive amounts.\n" " \"amount\": x.xxx, (numeric) The amount in " + CURRENCY_UNIT + ". This is negative for the 'send' category, and for the 'move' category for moves \n" " outbound. It is positive for the 'receive' category, and for the 'move' category for inbound funds.\n" " \"vout\" : n, (numeric) the vout value\n" " \"fee\": x.xxx, (numeric) The amount of the fee in " + CURRENCY_UNIT + ". This is negative and only available for the 'send' category of transactions.\n" " \"instantlock\" : true|false, (bool) Current transaction lock state. Available for 'send' and 'receive' category of transactions.\n" " \"confirmations\" : n, (numeric) The number of blockchain confirmations for the transaction. Available for 'send' and 'receive' category of transactions.\n" " \"blockhash\": \"hashvalue\", (string) The block hash containing the transaction. Available for 'send' and 'receive' category of transactions.\n" " \"blockindex\": n, (numeric) The index of the transaction in the block that includes it. Available for 'send' and 'receive' category of transactions.\n" " \"blocktime\": xxx, (numeric) The block time in seconds since epoch (1 Jan 1970 GMT).\n" " \"txid\": \"transactionid\", (string) The transaction id. Available for 'send' and 'receive' category of transactions.\n" " \"time\": xxx, (numeric) The transaction time in seconds since epoch (Jan 1 1970 GMT).\n" " \"timereceived\": xxx, (numeric) The time received in seconds since epoch (Jan 1 1970 GMT). Available for 'send' and 'receive' category of transactions.\n" " \"comment\": \"...\", (string) If a comment is associated with the transaction.\n" " \"label\" : \"label\" (string) A comment for the address/transaction, if any\n" " \"to\": \"...\", (string) If a comment to is associated with the transaction.\n" " ],\n" " \"lastblock\": \"lastblockhash\" (string) The hash of the last block\n" "}\n" "\nExamples:\n" + HelpExampleCli("listsinceblock", "") + HelpExampleCli("listsinceblock", "\"000000000000000bacf66f7497b7dc45ef753ee9a7d38571037cdb1a57f663ad\" 6") + HelpExampleRpc("listsinceblock", "\"000000000000000bacf66f7497b7dc45ef753ee9a7d38571037cdb1a57f663ad\", 6") ); LOCK2(cs_main, pwalletMain->cs_wallet); CBlockIndex *pindex = NULL; int target_confirms = 1; isminefilter filter = ISMINE_SPENDABLE; if (params.size() > 0) { uint256 blockId; blockId.SetHex(params[0].get_str()); BlockMap::iterator it = mapBlockIndex.find(blockId); if (it != mapBlockIndex.end()) pindex = it->second; else throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid blockhash"); } if (params.size() > 1) { target_confirms = params[1].get_int(); if (target_confirms < 1) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter"); } if(params.size() > 2) if(params[2].get_bool()) filter = filter | ISMINE_WATCH_ONLY; int depth = pindex ? (1 + chainActive.Height() - pindex->nHeight) : -1; UniValue transactions(UniValue::VARR); for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); it++) { CWalletTx tx = (*it).second; if (depth == -1 || tx.GetDepthInMainChain(false) < depth) ListTransactions(tx, "*", 0, true, transactions, filter); } CBlockIndex *pblockLast = chainActive[chainActive.Height() + 1 - target_confirms]; uint256 lastblock = pblockLast ? pblockLast->GetBlockHash() : uint256(); UniValue ret(UniValue::VOBJ); ret.push_back(Pair("transactions", transactions)); ret.push_back(Pair("lastblock", lastblock.GetHex())); return ret; } UniValue gettransaction(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "gettransaction \"txid\" ( includeWatchonly )\n" "\nGet detailed information about in-wallet transaction <txid>\n" "\nArguments:\n" "1. \"txid\" (string, required) The transaction id\n" "2. \"includeWatchonly\" (bool, optional, default=false) Whether to include watchonly addresses in balance calculation and details[]\n" "\nResult:\n" "{\n" " \"amount\" : x.xxx, (numeric) The transaction amount in " + CURRENCY_UNIT + "\n" " \"instantlock\" : true|false, (bool) Current transaction lock state\n" " \"confirmations\" : n, (numeric) The number of blockchain confirmations\n" " \"blockhash\" : \"hash\", (string) The block hash\n" " \"blockindex\" : xx, (numeric) The index of the transaction in the block that includes it\n" " \"blocktime\" : ttt, (numeric) The time in seconds since epoch (1 Jan 1970 GMT)\n" " \"txid\" : \"transactionid\", (string) The transaction id.\n" " \"time\" : ttt, (numeric) The transaction time in seconds since epoch (1 Jan 1970 GMT)\n" " \"timereceived\" : ttt, (numeric) The time received in seconds since epoch (1 Jan 1970 GMT)\n" " \"bip125-replaceable\": \"yes|no|unknown\" (string) Whether this transaction could be replaced due to BIP125 (replace-by-fee);\n" " may be unknown for unconfirmed transactions not in the mempool\n" " \"details\" : [\n" " {\n" " \"account\" : \"accountname\", (string) DEPRECATED. The account name involved in the transaction, can be \"\" for the default account.\n" " \"address\" : \"newcoinaddress\", (string) The newcoin address involved in the transaction\n" " \"category\" : \"send|receive\", (string) The category, either 'send' or 'receive'\n" " \"amount\" : x.xxx, (numeric) The amount in " + CURRENCY_UNIT + "\n" " \"label\" : \"label\", (string) A comment for the address/transaction, if any\n" " \"vout\" : n, (numeric) the vout value\n" " }\n" " ,...\n" " ],\n" " \"hex\" : \"data\" (string) Raw data for transaction\n" "}\n" "\nExamples:\n" + HelpExampleCli("gettransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"") + HelpExampleCli("gettransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\" true") + HelpExampleRpc("gettransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); uint256 hash; hash.SetHex(params[0].get_str()); isminefilter filter = ISMINE_SPENDABLE; if(params.size() > 1) if(params[1].get_bool()) filter = filter | ISMINE_WATCH_ONLY; UniValue entry(UniValue::VOBJ); if (!pwalletMain->mapWallet.count(hash)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid or non-wallet transaction id"); const CWalletTx& wtx = pwalletMain->mapWallet[hash]; CAmount nCredit = wtx.GetCredit(filter); CAmount nDebit = wtx.GetDebit(filter); CAmount nNet = nCredit - nDebit; CAmount nFee = (wtx.IsFromMe(filter) ? wtx.GetValueOut() - nDebit : 0); entry.push_back(Pair("amount", ValueFromAmount(nNet - nFee))); if (wtx.IsFromMe(filter)) entry.push_back(Pair("fee", ValueFromAmount(nFee))); WalletTxToJSON(wtx, entry); UniValue details(UniValue::VARR); ListTransactions(wtx, "*", 0, false, details, filter); entry.push_back(Pair("details", details)); string strHex = EncodeHexTx(static_cast<CTransaction>(wtx)); entry.push_back(Pair("hex", strHex)); return entry; } UniValue abandontransaction(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() != 1) throw runtime_error( "abandontransaction \"txid\"\n" "\nMark in-wallet transaction <txid> as abandoned\n" "This will mark this transaction and all its in-wallet descendants as abandoned which will allow\n" "for their inputs to be respent. It can be used to replace \"stuck\" or evicted transactions.\n" "It only works on transactions which are not included in a block and are not currently in the mempool.\n" "It has no effect on transactions which are already conflicted or abandoned.\n" "\nArguments:\n" "1. \"txid\" (string, required) The transaction id\n" "\nResult:\n" "\nExamples:\n" + HelpExampleCli("abandontransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"") + HelpExampleRpc("abandontransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); uint256 hash; hash.SetHex(params[0].get_str()); if (!pwalletMain->mapWallet.count(hash)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid or non-wallet transaction id"); if (!pwalletMain->AbandonTransaction(hash)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not eligible for abandonment"); return NullUniValue; } UniValue backupwallet(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() != 1) throw runtime_error( "backupwallet \"destination\"\n" "\nSafely copies wallet.dat to destination, which can be a directory or a path with filename.\n" "\nArguments:\n" "1. \"destination\" (string) The destination directory or file\n" "\nExamples:\n" + HelpExampleCli("backupwallet", "\"backup.dat\"") + HelpExampleRpc("backupwallet", "\"backup.dat\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); string strDest = params[0].get_str(); if (!BackupWallet(*pwalletMain, strDest)) throw JSONRPCError(RPC_WALLET_ERROR, "Error: Wallet backup failed!"); return NullUniValue; } UniValue keypoolrefill(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() > 1) throw runtime_error( "keypoolrefill ( newsize )\n" "\nFills the keypool." + HelpRequiringPassphrase() + "\n" "\nArguments\n" "1. newsize (numeric, optional, default=" + itostr(DEFAULT_KEYPOOL_SIZE) + ") The new keypool size\n" "\nExamples:\n" + HelpExampleCli("keypoolrefill", "") + HelpExampleRpc("keypoolrefill", "") ); LOCK2(cs_main, pwalletMain->cs_wallet); // 0 is interpreted by TopUpKeyPool() as the default keypool size given by -keypool unsigned int kpSize = 0; if (params.size() > 0) { if (params[0].get_int() < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected valid size."); kpSize = (unsigned int)params[0].get_int(); } EnsureWalletIsUnlocked(); pwalletMain->TopUpKeyPool(kpSize); if (pwalletMain->GetKeyPoolSize() < (pwalletMain->IsHDEnabled() ? kpSize * 2 : kpSize)) throw JSONRPCError(RPC_WALLET_ERROR, "Error refreshing keypool."); return NullUniValue; } static void LockWallet(CWallet* pWallet) { LOCK(cs_nWalletUnlockTime); nWalletUnlockTime = 0; pWallet->Lock(); } UniValue walletpassphrase(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (pwalletMain->IsCrypted() && (fHelp || params.size() < 2 || params.size() > 3)) throw runtime_error( "walletpassphrase \"passphrase\" timeout ( mixingonly )\n" "\nStores the wallet decryption key in memory for 'timeout' seconds.\n" "This is needed prior to performing transactions related to private keys such as sending newcoins\n" "\nArguments:\n" "1. \"passphrase\" (string, required) The wallet passphrase\n" "2. timeout (numeric, required) The time to keep the decryption key in seconds.\n" "3. mixingonly (boolean, optional, default=false) If is true sending functions are disabled." "\nNote:\n" "Issuing the walletpassphrase command while the wallet is already unlocked will set a new unlock\n" "time that overrides the old one.\n" "\nExamples:\n" "\nUnlock the wallet for 60 seconds\n" + HelpExampleCli("walletpassphrase", "\"my pass phrase\" 60") + "\nUnlock the wallet for 60 seconds but allow PrivateSend mixing only\n" + HelpExampleCli("walletpassphrase", "\"my pass phrase\" 60 true") + "\nLock the wallet again (before 60 seconds)\n" + HelpExampleCli("walletlock", "") + "\nAs json rpc call\n" + HelpExampleRpc("walletpassphrase", "\"my pass phrase\", 60") ); LOCK2(cs_main, pwalletMain->cs_wallet); if (fHelp) return true; if (!pwalletMain->IsCrypted()) throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrase was called."); // Note that the walletpassphrase is stored in params[0] which is not mlock()ed SecureString strWalletPass; strWalletPass.reserve(100); // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string) // Alternately, find a way to make params[0] mlock()'d to begin with. strWalletPass = params[0].get_str().c_str(); int64_t nSleepTime = params[1].get_int64(); bool fForMixingOnly = false; if (params.size() >= 3) fForMixingOnly = params[2].get_bool(); if (fForMixingOnly && !pwalletMain->IsLocked(true) && pwalletMain->IsLocked()) throw JSONRPCError(RPC_WALLET_ALREADY_UNLOCKED, "Error: Wallet is already unlocked for mixing only."); if (!pwalletMain->IsLocked()) throw JSONRPCError(RPC_WALLET_ALREADY_UNLOCKED, "Error: Wallet is already fully unlocked."); if (!pwalletMain->Unlock(strWalletPass, fForMixingOnly)) throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect."); pwalletMain->TopUpKeyPool(); LOCK(cs_nWalletUnlockTime); nWalletUnlockTime = GetTime() + nSleepTime; RPCRunLater("lockwallet", boost::bind(LockWallet, pwalletMain), nSleepTime); return NullUniValue; } UniValue walletpassphrasechange(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2)) throw runtime_error( "walletpassphrasechange \"oldpassphrase\" \"newpassphrase\"\n" "\nChanges the wallet passphrase from 'oldpassphrase' to 'newpassphrase'.\n" "\nArguments:\n" "1. \"oldpassphrase\" (string) The current passphrase\n" "2. \"newpassphrase\" (string) The new passphrase\n" "\nExamples:\n" + HelpExampleCli("walletpassphrasechange", "\"old one\" \"new one\"") + HelpExampleRpc("walletpassphrasechange", "\"old one\", \"new one\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); if (fHelp) return true; if (!pwalletMain->IsCrypted()) throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrasechange was called."); // TODO: get rid of these .c_str() calls by implementing SecureString::operator=(std::string) // Alternately, find a way to make params[0] mlock()'d to begin with. SecureString strOldWalletPass; strOldWalletPass.reserve(100); strOldWalletPass = params[0].get_str().c_str(); SecureString strNewWalletPass; strNewWalletPass.reserve(100); strNewWalletPass = params[1].get_str().c_str(); if (strOldWalletPass.length() < 1 || strNewWalletPass.length() < 1) throw runtime_error( "walletpassphrasechange <oldpassphrase> <newpassphrase>\n" "Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>."); if (!pwalletMain->ChangeWalletPassphrase(strOldWalletPass, strNewWalletPass)) throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect."); return NullUniValue; } UniValue walletlock(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (pwalletMain->IsCrypted() && (fHelp || params.size() != 0)) throw runtime_error( "walletlock\n" "\nRemoves the wallet encryption key from memory, locking the wallet.\n" "After calling this method, you will need to call walletpassphrase again\n" "before being able to call any methods which require the wallet to be unlocked.\n" "\nExamples:\n" "\nSet the passphrase for 2 minutes to perform a transaction\n" + HelpExampleCli("walletpassphrase", "\"my pass phrase\" 120") + "\nPerform a send (requires passphrase set)\n" + HelpExampleCli("sendtoaddress", "\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" 1.0") + "\nClear the passphrase since we are done before 2 minutes is up\n" + HelpExampleCli("walletlock", "") + "\nAs json rpc call\n" + HelpExampleRpc("walletlock", "") ); LOCK2(cs_main, pwalletMain->cs_wallet); if (fHelp) return true; if (!pwalletMain->IsCrypted()) throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletlock was called."); { LOCK(cs_nWalletUnlockTime); pwalletMain->Lock(); nWalletUnlockTime = 0; } return NullUniValue; } UniValue encryptwallet(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (!pwalletMain->IsCrypted() && (fHelp || params.size() != 1)) throw runtime_error( "encryptwallet \"passphrase\"\n" "\nEncrypts the wallet with 'passphrase'. This is for first time encryption.\n" "After this, any calls that interact with private keys such as sending or signing \n" "will require the passphrase to be set prior the making these calls.\n" "Use the walletpassphrase call for this, and then walletlock call.\n" "If the wallet is already encrypted, use the walletpassphrasechange call.\n" "Note that this will shutdown the server.\n" "\nArguments:\n" "1. \"passphrase\" (string) The pass phrase to encrypt the wallet with. It must be at least 1 character, but should be long.\n" "\nExamples:\n" "\nEncrypt you wallet\n" + HelpExampleCli("encryptwallet", "\"my pass phrase\"") + "\nNow set the passphrase to use the wallet, such as for signing or sending newcoin\n" + HelpExampleCli("walletpassphrase", "\"my pass phrase\"") + "\nNow we can so something like sign\n" + HelpExampleCli("signmessage", "\"newcoinaddress\" \"test message\"") + "\nNow lock the wallet again by removing the passphrase\n" + HelpExampleCli("walletlock", "") + "\nAs a json rpc call\n" + HelpExampleRpc("encryptwallet", "\"my pass phrase\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); if (fHelp) return true; if (pwalletMain->IsCrypted()) throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an encrypted wallet, but encryptwallet was called."); // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string) // Alternately, find a way to make params[0] mlock()'d to begin with. SecureString strWalletPass; strWalletPass.reserve(100); strWalletPass = params[0].get_str().c_str(); if (strWalletPass.length() < 1) throw runtime_error( "encryptwallet <passphrase>\n" "Encrypts the wallet with <passphrase>."); if (!pwalletMain->EncryptWallet(strWalletPass)) throw JSONRPCError(RPC_WALLET_ENCRYPTION_FAILED, "Error: Failed to encrypt the wallet."); // BDB seems to have a bad habit of writing old data into // slack space in .dat files; that is bad if the old data is // unencrypted private keys. So: StartShutdown(); return "Wallet encrypted; NewCoin Core server stopping, restart to run with encrypted wallet. The keypool has been flushed and a new HD seed was generated (if you are using HD). You need to make a new backup."; } UniValue lockunspent(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "lockunspent unlock [{\"txid\":\"txid\",\"vout\":n},...]\n" "\nUpdates list of temporarily unspendable outputs.\n" "Temporarily lock (unlock=false) or unlock (unlock=true) specified transaction outputs.\n" "A locked transaction output will not be chosen by automatic coin selection, when spending newcoins.\n" "Locks are stored in memory only. Nodes start with zero locked outputs, and the locked output list\n" "is always cleared (by virtue of process exit) when a node stops or fails.\n" "Also see the listunspent call\n" "\nArguments:\n" "1. unlock (boolean, required) Whether to unlock (true) or lock (false) the specified transactions\n" "2. \"transactions\" (string, required) A json array of objects. Each object the txid (string) vout (numeric)\n" " [ (json array of json objects)\n" " {\n" " \"txid\":\"id\", (string) The transaction id\n" " \"vout\": n (numeric) The output number\n" " }\n" " ,...\n" " ]\n" "\nResult:\n" "true|false (boolean) Whether the command was successful or not\n" "\nExamples:\n" "\nList the unspent transactions\n" + HelpExampleCli("listunspent", "") + "\nLock an unspent transaction\n" + HelpExampleCli("lockunspent", "false \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") + "\nList the locked transactions\n" + HelpExampleCli("listlockunspent", "") + "\nUnlock the transaction again\n" + HelpExampleCli("lockunspent", "true \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") + "\nAs a json rpc call\n" + HelpExampleRpc("lockunspent", "false, \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); if (params.size() == 1) RPCTypeCheck(params, boost::assign::list_of(UniValue::VBOOL)); else RPCTypeCheck(params, boost::assign::list_of(UniValue::VBOOL)(UniValue::VARR)); bool fUnlock = params[0].get_bool(); if (params.size() == 1) { if (fUnlock) pwalletMain->UnlockAllCoins(); return true; } UniValue outputs = params[1].get_array(); for (unsigned int idx = 0; idx < outputs.size(); idx++) { const UniValue& output = outputs[idx]; if (!output.isObject()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected object"); const UniValue& o = output.get_obj(); RPCTypeCheckObj(o, boost::assign::map_list_of("txid", UniValue::VSTR)("vout", UniValue::VNUM)); string txid = find_value(o, "txid").get_str(); if (!IsHex(txid)) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected hex txid"); int nOutput = find_value(o, "vout").get_int(); if (nOutput < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive"); COutPoint outpt(uint256S(txid), nOutput); if (fUnlock) pwalletMain->UnlockCoin(outpt); else pwalletMain->LockCoin(outpt); } return true; } UniValue listlockunspent(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() > 0) throw runtime_error( "listlockunspent\n" "\nReturns list of temporarily unspendable outputs.\n" "See the lockunspent call to lock and unlock transactions for spending.\n" "\nResult:\n" "[\n" " {\n" " \"txid\" : \"transactionid\", (string) The transaction id locked\n" " \"vout\" : n (numeric) The vout value\n" " }\n" " ,...\n" "]\n" "\nExamples:\n" "\nList the unspent transactions\n" + HelpExampleCli("listunspent", "") + "\nLock an unspent transaction\n" + HelpExampleCli("lockunspent", "false \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") + "\nList the locked transactions\n" + HelpExampleCli("listlockunspent", "") + "\nUnlock the transaction again\n" + HelpExampleCli("lockunspent", "true \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") + "\nAs a json rpc call\n" + HelpExampleRpc("listlockunspent", "") ); LOCK2(cs_main, pwalletMain->cs_wallet); vector<COutPoint> vOutpts; pwalletMain->ListLockedCoins(vOutpts); UniValue ret(UniValue::VARR); BOOST_FOREACH(COutPoint &outpt, vOutpts) { UniValue o(UniValue::VOBJ); o.push_back(Pair("txid", outpt.hash.GetHex())); o.push_back(Pair("vout", (int)outpt.n)); ret.push_back(o); } return ret; } UniValue settxfee(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() < 1 || params.size() > 1) throw runtime_error( "settxfee amount\n" "\nSet the transaction fee per kB. Overwrites the paytxfee parameter.\n" "\nArguments:\n" "1. amount (numeric or sting, required) The transaction fee in " + CURRENCY_UNIT + "/kB\n" "\nResult\n" "true|false (boolean) Returns true if successful\n" "\nExamples:\n" + HelpExampleCli("settxfee", "0.00001") + HelpExampleRpc("settxfee", "0.00001") ); LOCK2(cs_main, pwalletMain->cs_wallet); // Amount CAmount nAmount = AmountFromValue(params[0]); payTxFee = CFeeRate(nAmount, 1000); return true; } UniValue getwalletinfo(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() != 0) throw runtime_error( "getwalletinfo\n" "Returns an object containing various wallet state info.\n" "\nResult:\n" "{\n" " \"walletversion\": xxxxx, (numeric) the wallet version\n" " \"balance\": xxxxxxx, (numeric) the total confirmed balance of the wallet in " + CURRENCY_UNIT + "\n" " \"unconfirmed_balance\": xxx, (numeric) the total unconfirmed balance of the wallet in " + CURRENCY_UNIT + "\n" " \"immature_balance\": xxxxxx, (numeric) the total immature balance of the wallet in " + CURRENCY_UNIT + "\n" " \"txcount\": xxxxxxx, (numeric) the total number of transactions in the wallet\n" " \"keypoololdest\": xxxxxx, (numeric) the timestamp (seconds since GMT epoch) of the oldest pre-generated key in the key pool\n" " \"keypoolsize\": xxxx, (numeric) how many new keys are pre-generated (only counts external keys)\n" " \"keypoolsize_hd_internal\": xxxx, (numeric) how many new keys are pre-generated for internal use (used for change outputs, only appears if the wallet is using this feature, otherwise external keys are used)\n" " \"keys_left\": xxxx, (numeric) how many new keys are left since last automatic backup\n" " \"unlocked_until\": ttt, (numeric) the timestamp in seconds since epoch (midnight Jan 1 1970 GMT) that the wallet is unlocked for transfers, or 0 if the wallet is locked\n" " \"paytxfee\": x.xxxx, (numeric) the transaction fee configuration, set in " + CURRENCY_UNIT + "/kB\n" " \"hdchainid\": \"<hash>\", (string) the ID of the HD chain\n" " \"hdaccountcount\": xxx, (numeric) how many accounts of the HD chain are in this wallet\n" " [\n" " {\n" " \"hdaccountindex\": xxx, (numeric) the index of the account\n" " \"hdexternalkeyindex\": xxxx, (numeric) current external childkey index\n" " \"hdinternalkeyindex\": xxxx, (numeric) current internal childkey index\n" " }\n" " ,...\n" " ]\n" "}\n" "\nExamples:\n" + HelpExampleCli("getwalletinfo", "") + HelpExampleRpc("getwalletinfo", "") ); LOCK2(cs_main, pwalletMain->cs_wallet); CHDChain hdChainCurrent; bool fHDEnabled = pwalletMain->GetHDChain(hdChainCurrent); UniValue obj(UniValue::VOBJ); obj.push_back(Pair("walletversion", pwalletMain->GetVersion())); obj.push_back(Pair("balance", ValueFromAmount(pwalletMain->GetBalance()))); obj.push_back(Pair("unconfirmed_balance", ValueFromAmount(pwalletMain->GetUnconfirmedBalance()))); obj.push_back(Pair("immature_balance", ValueFromAmount(pwalletMain->GetImmatureBalance()))); obj.push_back(Pair("txcount", (int)pwalletMain->mapWallet.size())); obj.push_back(Pair("keypoololdest", pwalletMain->GetOldestKeyPoolTime())); obj.push_back(Pair("keypoolsize", (int64_t)pwalletMain->KeypoolCountExternalKeys())); if (fHDEnabled) { obj.push_back(Pair("keypoolsize_hd_internal", (int64_t)(pwalletMain->KeypoolCountInternalKeys()))); } obj.push_back(Pair("keys_left", pwalletMain->nKeysLeftSinceAutoBackup)); if (pwalletMain->IsCrypted()) obj.push_back(Pair("unlocked_until", nWalletUnlockTime)); obj.push_back(Pair("paytxfee", ValueFromAmount(payTxFee.GetFeePerK()))); if (fHDEnabled) { obj.push_back(Pair("hdchainid", hdChainCurrent.GetID().GetHex())); obj.push_back(Pair("hdaccountcount", (int64_t)hdChainCurrent.CountAccounts())); UniValue accounts(UniValue::VARR); for (size_t i = 0; i < hdChainCurrent.CountAccounts(); ++i) { CHDAccount acc; UniValue account(UniValue::VOBJ); account.push_back(Pair("hdaccountindex", (int64_t)i)); if(hdChainCurrent.GetAccount(i, acc)) { account.push_back(Pair("hdexternalkeyindex", (int64_t)acc.nExternalChainCounter)); account.push_back(Pair("hdinternalkeyindex", (int64_t)acc.nInternalChainCounter)); } else { account.push_back(Pair("error", strprintf("account %d is missing", i))); } accounts.push_back(account); } obj.push_back(Pair("hdaccounts", accounts)); } return obj; } UniValue keepass(const UniValue& params, bool fHelp) { string strCommand; if (params.size() >= 1) strCommand = params[0].get_str(); if (fHelp || (strCommand != "genkey" && strCommand != "init" && strCommand != "setpassphrase")) throw runtime_error( "keepass <genkey|init|setpassphrase>\n"); if (strCommand == "genkey") { SecureString sResult; // Generate RSA key SecureString sKey = CKeePassIntegrator::generateKeePassKey(); sResult = "Generated Key: "; sResult += sKey; return sResult.c_str(); } else if(strCommand == "init") { // Generate base64 encoded 256 bit RSA key and associate with KeePassHttp SecureString sResult; SecureString sKey; std::string strId; keePassInt.rpcAssociate(strId, sKey); sResult = "Association successful. Id: "; sResult += strId.c_str(); sResult += " - Key: "; sResult += sKey.c_str(); return sResult.c_str(); } else if(strCommand == "setpassphrase") { if(params.size() != 2) { return "setlogin: invalid number of parameters. Requires a passphrase"; } SecureString sPassphrase = SecureString(params[1].get_str().c_str()); keePassInt.updatePassphrase(sPassphrase); return "setlogin: Updated credentials."; } return "Invalid command"; } UniValue resendwallettransactions(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() != 0) throw runtime_error( "resendwallettransactions\n" "Immediately re-broadcast unconfirmed wallet transactions to all peers.\n" "Intended only for testing; the wallet code periodically re-broadcasts\n" "automatically.\n" "Returns array of transaction ids that were re-broadcast.\n" ); if (!g_connman) throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); LOCK2(cs_main, pwalletMain->cs_wallet); std::vector<uint256> txids = pwalletMain->ResendWalletTransactionsBefore(GetTime(), g_connman.get()); UniValue result(UniValue::VARR); BOOST_FOREACH(const uint256& txid, txids) { result.push_back(txid.ToString()); } return result; } UniValue listunspent(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() > 3) throw runtime_error( "listunspent ( minconf maxconf [\"address\",...] )\n" "\nReturns array of unspent transaction outputs\n" "with between minconf and maxconf (inclusive) confirmations.\n" "Optionally filter to only include txouts paid to specified addresses.\n" "Results are an array of Objects, each of which has:\n" "{txid, vout, scriptPubKey, amount, confirmations}\n" "\nArguments:\n" "1. minconf (numeric, optional, default=1) The minimum confirmations to filter\n" "2. maxconf (numeric, optional, default=9999999) The maximum confirmations to filter\n" "3. \"addresses\" (string) A json array of newcoin addresses to filter\n" " [\n" " \"address\" (string) newcoin address\n" " ,...\n" " ]\n" "\nResult\n" "[ (array of json object)\n" " {\n" " \"txid\" : \"txid\", (string) the transaction id \n" " \"vout\" : n, (numeric) the vout value\n" " \"address\" : \"address\", (string) the newcoin address\n" " \"account\" : \"account\", (string) DEPRECATED. The associated account, or \"\" for the default account\n" " \"scriptPubKey\" : \"key\", (string) the script key\n" " \"amount\" : x.xxx, (numeric) the transaction amount in " + CURRENCY_UNIT + "\n" " \"confirmations\" : n (numeric) The number of confirmations\n" " \"ps_rounds\" : n (numeric) The number of PS round\n" " \"spendable\" : xxx, (bool) Whether we have the private keys to spend this output\n" " \"solvable\" : xxx (bool) Whether we know how to spend this output, ignoring the lack of keys\n" " }\n" " ,...\n" "]\n" "\nExamples\n" + HelpExampleCli("listunspent", "") + HelpExampleCli("listunspent", "6 9999999 \"[\\\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\\\",\\\"XuQQkwA4FYkq2XERzMY2CiAZhJTEDAbtcg\\\"]\"") + HelpExampleRpc("listunspent", "6, 9999999 \"[\\\"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\\\",\\\"XuQQkwA4FYkq2XERzMY2CiAZhJTEDAbtcg\\\"]\"") ); RPCTypeCheck(params, boost::assign::list_of(UniValue::VNUM)(UniValue::VNUM)(UniValue::VARR)); int nMinDepth = 1; if (params.size() > 0) nMinDepth = params[0].get_int(); int nMaxDepth = 9999999; if (params.size() > 1) nMaxDepth = params[1].get_int(); set<CBitcoinAddress> setAddress; if (params.size() > 2) { UniValue inputs = params[2].get_array(); for (unsigned int idx = 0; idx < inputs.size(); idx++) { const UniValue& input = inputs[idx]; CBitcoinAddress address(input.get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid NewCoin address: ")+input.get_str()); if (setAddress.count(address)) throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+input.get_str()); setAddress.insert(address); } } UniValue results(UniValue::VARR); vector<COutput> vecOutputs; assert(pwalletMain != NULL); LOCK2(cs_main, pwalletMain->cs_wallet); pwalletMain->AvailableCoins(vecOutputs, false, NULL, true); BOOST_FOREACH(const COutput& out, vecOutputs) { if (out.nDepth < nMinDepth || out.nDepth > nMaxDepth) continue; if (setAddress.size()) { CTxDestination address; if (!ExtractDestination(out.tx->vout[out.i].scriptPubKey, address)) continue; if (!setAddress.count(address)) continue; } CAmount nValue = out.tx->vout[out.i].nValue; const CScript& pk = out.tx->vout[out.i].scriptPubKey; UniValue entry(UniValue::VOBJ); entry.push_back(Pair("txid", out.tx->GetHash().GetHex())); entry.push_back(Pair("vout", out.i)); CTxDestination address; if (ExtractDestination(out.tx->vout[out.i].scriptPubKey, address)) { entry.push_back(Pair("address", CBitcoinAddress(address).ToString())); if (pwalletMain->mapAddressBook.count(address)) entry.push_back(Pair("account", pwalletMain->mapAddressBook[address].name)); } entry.push_back(Pair("scriptPubKey", HexStr(pk.begin(), pk.end()))); if (pk.IsPayToScriptHash()) { CTxDestination address; if (ExtractDestination(pk, address)) { const CScriptID& hash = boost::get<CScriptID>(address); CScript redeemScript; if (pwalletMain->GetCScript(hash, redeemScript)) entry.push_back(Pair("redeemScript", HexStr(redeemScript.begin(), redeemScript.end()))); } } entry.push_back(Pair("amount",ValueFromAmount(nValue))); entry.push_back(Pair("confirmations",out.nDepth)); entry.push_back(Pair("ps_rounds", pwalletMain->GetOutpointPrivateSendRounds(COutPoint(out.tx->GetHash(), out.i)))); entry.push_back(Pair("spendable", out.fSpendable)); entry.push_back(Pair("solvable", out.fSolvable)); results.push_back(entry); } return results; } UniValue fundrawtransaction(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "fundrawtransaction \"hexstring\" includeWatching\n" "\nAdd inputs to a transaction until it has enough in value to meet its out value.\n" "This will not modify existing inputs, and will add one change output to the outputs.\n" "Note that inputs which were signed may need to be resigned after completion since in/outputs have been added.\n" "The inputs added will not be signed, use signrawtransaction for that.\n" "Note that all existing inputs must have their previous output transaction be in the wallet.\n" "Note that all inputs selected must be of standard form and P2SH scripts must be" "in the wallet using importaddress or addmultisigaddress (to calculate fees).\n" "You can see whether this is the case by checking the \"solvable\" field in the listunspent output.\n" "Only pay-to-pubkey, multisig, and P2SH versions thereof are currently supported for watch-only\n" "\nArguments:\n" "1. \"hexstring\" (string, required) The hex string of the raw transaction\n" "2. includeWatching (boolean, optional, default false) Also select inputs which are watch only\n" "\nResult:\n" "{\n" " \"hex\": \"value\", (string) The resulting raw transaction (hex-encoded string)\n" " \"fee\": n, (numeric) Fee the resulting transaction pays\n" " \"changepos\": n (numeric) The position of the added change output, or -1\n" "}\n" "\"hex\" \n" "\nExamples:\n" "\nCreate a transaction with no inputs\n" + HelpExampleCli("createrawtransaction", "\"[]\" \"{\\\"myaddress\\\":0.01}\"") + "\nAdd sufficient unsigned inputs to meet the output value\n" + HelpExampleCli("fundrawtransaction", "\"rawtransactionhex\"") + "\nSign the transaction\n" + HelpExampleCli("signrawtransaction", "\"fundedtransactionhex\"") + "\nSend the transaction\n" + HelpExampleCli("sendrawtransaction", "\"signedtransactionhex\"") ); RPCTypeCheck(params, boost::assign::list_of(UniValue::VSTR)(UniValue::VBOOL)); // parse hex string from parameter CTransaction origTx; if (!DecodeHexTx(origTx, params[0].get_str())) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed"); if (origTx.vout.size() == 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "TX must have at least one output"); bool includeWatching = false; if (params.size() > 1) includeWatching = params[1].get_bool(); CMutableTransaction tx(origTx); CAmount nFee; string strFailReason; int nChangePos = -1; if(!pwalletMain->FundTransaction(tx, nFee, nChangePos, strFailReason, includeWatching)) throw JSONRPCError(RPC_INTERNAL_ERROR, strFailReason); UniValue result(UniValue::VOBJ); result.push_back(Pair("hex", EncodeHexTx(tx))); result.push_back(Pair("changepos", nChangePos)); result.push_back(Pair("fee", ValueFromAmount(nFee))); return result; }
// Copyright (C) 2018-2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <cassert> #include <deque> #include <iomanip> #include <memory> #include <string> #include <unordered_map> #include <unordered_set> #include <utility> #include <vector> #include "caseless.hpp" #include "precision_utils.h" #include "cnn_network_ngraph_impl.hpp" #include "ie_ngraph_utils.hpp" #include "legacy/ie_util_internal.hpp" #include "legacy/cnn_network_impl.hpp" #include "legacy/details/ie_cnn_network_tools.h" #include "legacy/graph_tools.hpp" #include "legacy/net_pass.h" #include <legacy/details/ie_cnn_network_iterator.hpp> #include <legacy/ie_layers.h> #include "ie_legacy_itt.hpp" using std::string; namespace InferenceEngine { using namespace details; DataPtr cloneData(const InferenceEngine::Data& source) { auto cloned = std::make_shared<InferenceEngine::Data>(source); if (cloned != nullptr) { getCreatorLayer(cloned).reset(); getInputTo(cloned).clear(); } return cloned; } namespace { template <typename T> CNNLayerPtr layerCloneImpl(const CNNLayer* source) { auto layer = dynamic_cast<const T*>(source); if (nullptr != layer) { auto newLayer = std::make_shared<T>(*layer); newLayer->_fusedWith = nullptr; newLayer->outData.clear(); newLayer->insData.clear(); return std::static_pointer_cast<CNNLayer>(newLayer); } return nullptr; } /* Make this function explicit for TensorIterator layer * because of specific handling of the body field */ template <> CNNLayerPtr layerCloneImpl<TensorIterator>(const CNNLayer* source) { auto layer = dynamic_cast<const TensorIterator*>(source); if (nullptr != layer) { auto newLayer = std::make_shared<TensorIterator>(*layer); newLayer->_fusedWith = nullptr; newLayer->outData.clear(); newLayer->insData.clear(); newLayer->body = NetPass::CopyTIBody(newLayer->body); return std::static_pointer_cast<CNNLayer>(newLayer); } return nullptr; } } // namespace CNNLayerPtr clonelayer(const CNNLayer& source) { using fptr = CNNLayerPtr (*)(const CNNLayer*); // Most derived layers must go first in this list static const fptr cloners[] = {&layerCloneImpl<ExperimentalDetectronTopKROIs>, &layerCloneImpl<ExperimentalDetectronGenerateProposalsSingleImageLayer>, &layerCloneImpl<ExperimentalDetectronPriorGridGeneratorLayer>, &layerCloneImpl<ScatterUpdateLayer>, &layerCloneImpl<ScatterElementsUpdateLayer>, &layerCloneImpl<NonMaxSuppressionLayer>, &layerCloneImpl<SelectLayer>, &layerCloneImpl<BatchNormalizationLayer>, &layerCloneImpl<TopKLayer>, &layerCloneImpl<PowerLayer>, &layerCloneImpl<ScaleShiftLayer>, &layerCloneImpl<PReLULayer>, &layerCloneImpl<TileLayer>, &layerCloneImpl<ReshapeLayer>, &layerCloneImpl<CropLayer>, &layerCloneImpl<EltwiseLayer>, &layerCloneImpl<GemmLayer>, &layerCloneImpl<PadLayer>, &layerCloneImpl<GatherLayer>, &layerCloneImpl<StridedSliceLayer>, &layerCloneImpl<ShuffleChannelsLayer>, &layerCloneImpl<DepthToSpaceLayer>, &layerCloneImpl<SpaceToDepthLayer>, &layerCloneImpl<SpaceToBatchLayer>, &layerCloneImpl<BatchToSpaceLayer>, &layerCloneImpl<SparseFillEmptyRowsLayer>, &layerCloneImpl<SparseSegmentReduceLayer>, &layerCloneImpl<ExperimentalSparseWeightedReduceLayer>, &layerCloneImpl<SparseToDenseLayer>, &layerCloneImpl<BucketizeLayer>, &layerCloneImpl<ReverseSequenceLayer>, &layerCloneImpl<RangeLayer>, &layerCloneImpl<FillLayer>, &layerCloneImpl<BroadcastLayer>, &layerCloneImpl<MathLayer>, &layerCloneImpl<ReduceLayer>, &layerCloneImpl<ClampLayer>, &layerCloneImpl<ReLULayer>, &layerCloneImpl<SoftMaxLayer>, &layerCloneImpl<GRNLayer>, &layerCloneImpl<MVNLayer>, &layerCloneImpl<NormLayer>, &layerCloneImpl<SplitLayer>, &layerCloneImpl<ConcatLayer>, &layerCloneImpl<FullyConnectedLayer>, &layerCloneImpl<PoolingLayer>, &layerCloneImpl<DeconvolutionLayer>, &layerCloneImpl<DeformableConvolutionLayer>, &layerCloneImpl<ConvolutionLayer>, &layerCloneImpl<TensorIterator>, &layerCloneImpl<RNNSequenceLayer>, &layerCloneImpl<LSTMCell>, &layerCloneImpl<GRUCell>, &layerCloneImpl<RNNCell>, &layerCloneImpl<QuantizeLayer>, &layerCloneImpl<BinaryConvolutionLayer>, &layerCloneImpl<WeightableLayer>, &layerCloneImpl<OneHotLayer>, &layerCloneImpl<CNNLayer>, &layerCloneImpl<UniqueLayer>}; for (auto cloner : cloners) { auto cloned = cloner(&source); if (nullptr != cloned) { return cloned; } } assert(!"All layers derived from CNNLayer so we must never get here"); return nullptr; // Silence "control may reach end of non-void function" warning } CNNNetwork cloneNetwork(const CNNNetwork& network) { OV_ITT_SCOPE(FIRST_INFERENCE, itt::domains::IELegacy_LT, "cloneNetwork"); if (network.getFunction()) { return InferenceEngine::details::cloneNetwork(network); } IE_SUPPRESS_DEPRECATED_START return CNNNetwork(InferenceEngine::cloneNet(network)); IE_SUPPRESS_DEPRECATED_END } details::CNNNetworkImplPtr cloneNet(const CNNNetwork& network) { OV_ITT_SCOPED_TASK(itt::domains::IELegacy, "cloneNet(CNNNetwork)"); IE_ASSERT(network.getFunction() == nullptr); std::vector<CNNLayerPtr> layers; details::CNNNetworkIterator i(network); while (i != details::CNNNetworkIterator()) { layers.push_back(*i); i++; } // copy of the network details::CNNNetworkImplPtr net = cloneNet(layers); // going over output layers and aligning output ports and outputs OutputsDataMap outputs = network.getOutputsInfo(); OutputsDataMap outputInfo; net->getOutputsInfo(outputInfo); for (auto o : outputs) { auto it = outputInfo.find(o.first); if (it != outputInfo.end()) { outputInfo.erase(it); } else { net->addOutput(o.first); } } // remove output ports which unconnected with outputs for (auto o : outputInfo) { net->removeOutput(o.first); } net->setName(network.getName()); InputsDataMap externalInputsData = network.getInputsInfo(); InputsDataMap clonedInputs; net->getInputsInfo(clonedInputs); for (auto&& it : externalInputsData) { auto inp = clonedInputs.find(it.first); if (inp != clonedInputs.end() && nullptr != inp->second) { inp->second->setPrecision(it.second->getPrecision()); inp->second->getPreProcess() = it.second->getPreProcess(); } } return net; } details::CNNNetworkImplPtr cloneNet(const std::vector<CNNLayerPtr>& layers) { OV_ITT_SCOPED_TASK(itt::domains::IELegacy, "cloneNet(std::vector<CNNLayerPtr>)"); auto net = std::make_shared<InferenceEngine::details::CNNNetworkImpl>(); // Src to cloned data map std::unordered_map<InferenceEngine::DataPtr, InferenceEngine::DataPtr> dataMap; // Cloned to src data map std::unordered_map<InferenceEngine::DataPtr, InferenceEngine::DataPtr> clonedDataMap; std::vector<InferenceEngine::DataPtr> clonedDatas; auto createDataImpl = [&](const InferenceEngine::DataPtr& data) { assert(nullptr != data); if (!contains(dataMap, data)) { auto clonedData = cloneData(*data); dataMap[data] = clonedData; clonedDataMap[clonedData] = data; clonedDatas.push_back(clonedData); net->getData(clonedData->getName()) = clonedData; return clonedData; } return dataMap[data]; }; auto cloneLayerImpl = [&](const CNNLayer& srcLayer) { CNNLayerPtr clonedLayer = clonelayer(srcLayer); clonedLayer->_fusedWith = nullptr; // We will need to reconstruct all connections in new graph clonedLayer->outData.clear(); clonedLayer->insData.clear(); net->addLayer(clonedLayer); return clonedLayer; }; for (auto&& srcLayer : layers) { CNNLayerPtr clonedLayer = cloneLayerImpl(*srcLayer); for (auto&& src : srcLayer->insData) { auto data = src.lock(); auto clonedData = createDataImpl(data); string inputName; // Find input name for (auto&& inp : getInputTo(data)) { if (srcLayer == inp.second) { inputName = inp.first; break; } } assert(!inputName.empty()); getInputTo(clonedData).insert({inputName, clonedLayer}); clonedLayer->insData.push_back(clonedData); } for (auto&& data : srcLayer->outData) { auto clonedData = createDataImpl(data); getCreatorLayer(clonedData) = clonedLayer; clonedLayer->outData.push_back(clonedData); for (auto&& inp : getInputTo(data)) { auto layer = inp.second; // TODO(amalyshe) is it the best place to check priorbox and remove // such edge from outputs? if (std::find(layers.begin(), layers.end(), layer) == layers.end() && !(CaselessEq<string>()(layer->type, "priorbox") || CaselessEq<string>()(layer->type, "PriorBoxClustered"))) { net->addOutput(data->getName()); break; } } } } for (auto&& data : clonedDatas) { auto layer = getCreatorLayer(data).lock(); // create an artificial input layer because logic in some algorithms rely // on existence of these layers in the network if (nullptr == layer) { assert(contains(clonedDataMap, data)); auto originalData = clonedDataMap[data]; assert(nullptr != originalData); if (auto originalLayer = getCreatorLayer(originalData).lock()) { if (CaselessEq<string>()(originalLayer->type, "input") || CaselessEq<string>()(originalLayer->type, "const") || CaselessEq<string>()(originalLayer->type, "memory")) { layer = cloneLayerImpl(*originalLayer); layer->outData.push_back(data); getCreatorLayer(data) = layer; } } if (nullptr == layer) { LayerParams params = { data->getName(), std::string("Input"), data->getPrecision() }; layer = std::make_shared<CNNLayer>(params); // this place should be transactional layer->outData.push_back(data); getCreatorLayer(data) = layer; net->addLayer(layer); } } if (CaselessEq<string>()(layer->type, "input")) { auto input = std::make_shared<InferenceEngine::InputInfo>(); input->setInputData(data); net->setInputInfo(input); } } net->resolveOutput(); return net; } struct NodePrinter { enum FILL_COLOR { DATA, SUPPORTED_LAYER, UNSOPPORTED_LAYER }; std::unordered_set<InferenceEngine::Data*> printed_data; std::unordered_set<InferenceEngine::CNNLayer*> printed_layers; std::ostream& out; printer_callback layer_cb; explicit NodePrinter(std::ostream& os, printer_callback cb): out(os), layer_cb(std::move(cb)) {} bool isPrinted(const CNNLayerPtr& layer) { return static_cast<bool>(printed_layers.count(layer.get())); } bool isPrinted(const DataPtr& datum) { return static_cast<bool>(printed_data.count(datum.get())); } string colorToStr(FILL_COLOR color) { switch (color) { case DATA: return "#FCF6E3"; case SUPPORTED_LAYER: return "#D9EAD3"; case UNSOPPORTED_LAYER: return "#F4CCCC"; default: return "#FFFFFF"; } } string formatSize_(const std::vector<unsigned int>& spatialDims) { string result; if (spatialDims.empty()) return result; result = std::to_string(spatialDims[0]); for (auto dim : spatialDims) { result += "x" + std::to_string(dim); } return result; } string cleanNodeName_(string node_name) const { // remove dot and dash symbols from node name. It is incorrectly displayed in xdot node_name.erase(remove(node_name.begin(), node_name.end(), '.'), node_name.end()); std::replace(node_name.begin(), node_name.end(), '-', '_'); std::replace(node_name.begin(), node_name.end(), ':', '_'); return node_name; } void printLayerNode(const CNNLayerPtr& layer) { auto node_name = "layer_" + cleanNodeName_(layer->name); printed_layers.insert(layer.get()); ordered_properties printed_properties; ordered_properties node_properties = {{"shape", "box"}, {"style", "filled"}, {"fillcolor", colorToStr(SUPPORTED_LAYER)}}; auto type = layer->type; printed_properties.emplace_back("type", type); if (type == "Convolution") { auto* conv = dynamic_cast<ConvolutionLayer*>(layer.get()); if (conv != nullptr) { unsigned int depth = conv->_out_depth, group = conv->_group; printed_properties.emplace_back( "kernel size", formatSize_({&(conv->_kernel[0]), &(conv->_kernel[conv->_kernel.size() - 1])})); printed_properties.emplace_back("output depth", std::to_string(depth)); printed_properties.emplace_back("group", std::to_string(group)); printed_properties.emplace_back( "padding begin", formatSize_({&(conv->_padding[0]), &(conv->_padding[conv->_padding.size() - 1])})); printed_properties.emplace_back( "padding end", formatSize_({&(conv->_pads_end[0]), &(conv->_pads_end[conv->_pads_end.size() - 1])})); printed_properties.emplace_back( "strides", formatSize_({&(conv->_stride[0]), &(conv->_stride[conv->_stride.size() - 1])})); printed_properties.emplace_back( "dilations", formatSize_({&(conv->_dilation[0]), &(conv->_dilation[conv->_dilation.size() - 1])})); } } else if (type == "Pooling") { auto* pool = dynamic_cast<PoolingLayer*>(layer.get()); if (pool != nullptr) { printed_properties.emplace_back( "window size", formatSize_({&(pool->_kernel[0]), &(pool->_kernel[pool->_kernel.size() - 1])})); printed_properties.emplace_back( "padding begin", formatSize_({&(pool->_padding[0]), &(pool->_padding[pool->_padding.size() - 1])})); printed_properties.emplace_back( "padding end", formatSize_({&(pool->_pads_end[0]), &(pool->_pads_end[pool->_pads_end.size() - 1])})); printed_properties.emplace_back( "strides", formatSize_({&(pool->_stride[0]), &(pool->_stride[pool->_stride.size() - 1])})); } } else if (type == "ReLU") { auto* relu = dynamic_cast<ReLULayer*>(layer.get()); if (relu != nullptr) { float negative_slope = relu->negative_slope; if (negative_slope != 0.0f) printed_properties.emplace_back("negative_slope", CNNLayer::ie_serialize_float(negative_slope)); } } else if (type == "Eltwise") { auto* eltwise = dynamic_cast<EltwiseLayer*>(layer.get()); if (eltwise != nullptr) { std::string operation; if (eltwise->_operation == EltwiseLayer::Sum) operation = "Sum"; else if (eltwise->_operation == EltwiseLayer::Prod) operation = "Prod"; else if (eltwise->_operation == EltwiseLayer::Max) operation = "Max"; else if (eltwise->_operation == EltwiseLayer::Sub) operation = "Sub"; else if (eltwise->_operation == EltwiseLayer::Min) operation = "Min"; else if (eltwise->_operation == EltwiseLayer::Div) operation = "Div"; else if (eltwise->_operation == EltwiseLayer::Squared_diff) operation = "Squared_diff"; else if (eltwise->_operation == EltwiseLayer::Equal) operation = "Equal"; else if (eltwise->_operation == EltwiseLayer::Not_equal) operation = "Not_equal"; else if (eltwise->_operation == EltwiseLayer::Less) operation = "Less"; else if (eltwise->_operation == EltwiseLayer::Less_equal) operation = "Less_equal"; else if (eltwise->_operation == EltwiseLayer::Greater) operation = "Greater"; else if (eltwise->_operation == EltwiseLayer::Greater_equal) operation = "Greater_equal"; else if (eltwise->_operation == EltwiseLayer::Logical_NOT) operation = "Logical_NOT"; else if (eltwise->_operation == EltwiseLayer::Logical_AND) operation = "Logical_AND"; else if (eltwise->_operation == EltwiseLayer::Logical_OR) operation = "Logical_OR"; else if (eltwise->_operation == EltwiseLayer::Logical_XOR) operation = "Logical_XOR"; else if (eltwise->_operation == EltwiseLayer::Floor_mod) operation = "Floor_mod"; else if (eltwise->_operation == EltwiseLayer::Pow) operation = "Pow"; else if (eltwise->_operation == EltwiseLayer::Mean) operation = "Mean"; printed_properties.emplace_back("operation", operation); } } if (layer_cb != nullptr) { layer_cb(layer, printed_properties, node_properties); } printNode(node_name, layer->name, node_properties, printed_properties); } void printDataNode(const std::shared_ptr<Data>& data) { auto node_name = "data_" + cleanNodeName_(data->getName()); printed_data.insert(data.get()); ordered_properties printed_properties; ordered_properties node_properties = {{"shape", "ellipse"}, {"style", "filled"}, {"fillcolor", colorToStr(DATA)}}; std::stringstream dims_ss; size_t idx = data->getTensorDesc().getDims().size(); dims_ss << '['; for (auto& dim : data->getTensorDesc().getDims()) { dims_ss << dim << ((--idx) != 0u ? ", " : ""); } dims_ss << ']'; printed_properties.emplace_back("dims", dims_ss.str()); printed_properties.emplace_back("precision", data->getPrecision().name()); std::stringstream ss; ss << data->getTensorDesc().getLayout(); printed_properties.emplace_back("layout", ss.str()); printed_properties.emplace_back("name", data->getName()); if (getCreatorLayer(data).lock() != nullptr) printed_properties.emplace_back("creator layer", getCreatorLayer(data).lock()->name); printNode(node_name, data->getName(), node_properties, printed_properties); } void printNode(string const& node_name, const string& node_title, ordered_properties const& node_properties, ordered_properties const& printed_properties) { // normalization of names, removing all prohibited symbols like "/" string nodeNameN = node_name; std::replace(nodeNameN.begin(), nodeNameN.end(), '/', '_'); string dataNameN = node_title; std::replace(dataNameN.begin(), dataNameN.end(), '/', '_'); out << '\t' << nodeNameN << " ["; for (auto& node_property : node_properties) { out << node_property.first << "=\"" << node_property.second << "\", "; } out << "label=\"" << node_title; for (auto& printed_property : printed_properties) { out << "\\n" << printed_property.first << ": " << printed_property.second; } out << "\"];\n"; } void printEdge(const CNNLayerPtr& from_, const DataPtr& to_, bool reverse) { auto from_name = "layer_" + cleanNodeName_(from_->name); auto to_name = "data_" + cleanNodeName_(to_->getName()); std::replace(from_name.begin(), from_name.end(), '/', '_'); std::replace(to_name.begin(), to_name.end(), '/', '_'); if (reverse) std::swap(from_name, to_name); out << '\t' << from_name << " -> " << to_name << ";\n"; } }; void saveGraphToDot(const InferenceEngine::CNNNetwork& network, std::ostream& out, printer_callback layer_cb) { NodePrinter printer(out, std::move(layer_cb)); out << "digraph Network {\n"; // Traverse graph and print nodes for (const auto& layer : details::CNNNetSortTopologically(network)) { printer.printLayerNode(layer); // Print output Data Object for (auto& dataptr : layer->outData) { if (!printer.isPrinted(dataptr)) { printer.printDataNode(dataptr); } printer.printEdge(layer, dataptr, false); } // Print input Data objects for (auto& datum : layer->insData) { auto dataptr = datum.lock(); if (!printer.isPrinted(dataptr)) { printer.printDataNode(dataptr); } printer.printEdge(layer, dataptr, true); } } out << "}" << std::endl; } } // namespace InferenceEngine
/** * @file stores.cpp * * Implementation of functionality for stores and towner dialogs. */ #include "stores.h" #include <algorithm> #include <fmt/format.h> #include "controls/plrctrls.h" #include "cursor.h" #include "engine/load_cel.hpp" #include "engine/random.hpp" #include "engine/render/cel_render.hpp" #include "engine/render/text_render.hpp" #include "init.h" #include "minitext.h" #include "options.h" #include "panels/info_box.hpp" #include "qol/stash.h" #include "towners.h" #include "utils/language.h" #include "utils/stdcompat/string_view.hpp" #include "utils/utf8.hpp" namespace devilution { talk_id stextflag; int storenumh; char storehidx[48]; Item storehold[48]; Item smithitem[SMITH_ITEMS]; int numpremium; int premiumlevel; Item premiumitems[SMITH_PREMIUM_ITEMS]; Item healitem[20]; Item witchitem[WITCH_ITEMS]; int boylevel; Item boyitem; namespace { /** The current towner being interacted with */ _talker_id talker; /** Is the current dialog full size */ bool stextsize; /** Number of text lines in the current dialog */ int stextsmax; /** Remember currently selected text line from stext while displaying a dialog */ int stextlhold; /** Currently selected text line from stext */ int stextsel; /** Text lines */ STextStruct stext[STORE_LINES]; /** Whether to render the player's gold amount in the top left */ bool RenderGold; /** Does the current panel have a scrollbar */ bool stextscrl; /** Remember last scoll position */ int stextvhold; /** Scoll position */ int stextsval; /** Next scoll position */ int stextdown; /** Previous scoll position */ int stextup; /** Count down for the push state of the scroll up button */ char stextscrlubtn; /** Count down for the push state of the scroll down button */ char stextscrldbtn; /** Remember current store while displaying a dialog */ talk_id stextshold; /** Start of possible gossip dialogs for current store */ _speech_id gossipstart; /** End of possible gossip dialogs for current store */ _speech_id gossipend; /** Temporary item used to hold the the item being traided */ Item StoreItem; /** Maps from towner IDs to NPC names. */ const char *const TownerNames[] = { N_("Griswold"), N_("Pepin"), "", N_("Ogden"), N_("Cain"), N_("Farnham"), N_("Adria"), N_("Gillian"), N_("Wirt"), }; constexpr int PaddingTop = 32; // For most languages, line height is always 12. // This includes blank lines and divider line. constexpr int SmallLineHeight = 12; constexpr int SmallTextHeight = 12; // For larger small fonts (Chinese and Japanese), text lines are // taller and overflow. // We space out blank lines a bit more to give space to 3-line store items. constexpr int LargeLineHeight = SmallLineHeight + 1; constexpr int LargeTextHeight = 18; /** * The line index with the Back / Leave button. * This is a special button that is always the last line. * * For lists with a scrollbar, it is not selectable (mouse-only). */ int BackButtonLine() { if (IsSmallFontTall()) { return stextscrl ? 21 : 20; } return 22; } int LineHeight() { return IsSmallFontTall() ? LargeLineHeight : SmallLineHeight; } int TextHeight() { return IsSmallFontTall() ? LargeTextHeight : SmallTextHeight; } void CalculateLineHeights() { stext[0].y = 0; if (IsSmallFontTall()) { for (int i = 1; i < STORE_LINES; ++i) { // Space out consecutive text lines, unless they are both selectable (never the case currently). if (stext[i].IsText() && stext[i - 1].IsText() && !(stext[i]._ssel && stext[i - 1]._ssel)) { stext[i].y = stext[i - 1].y + LargeTextHeight; } else { stext[i].y = i * LargeLineHeight; } } } else { for (int i = 1; i < STORE_LINES; ++i) { stext[i].y = i * SmallLineHeight; } } } void DrawSTextBack(const Surface &out) { CelDrawTo(out, { PANEL_X + 320 + 24, 327 + UI_OFFSET_Y }, *pSTextBoxCels, 0); DrawHalfTransparentRectTo(out, PANEL_X + 347, UI_OFFSET_Y + 28, 265, 297); } void DrawSSlider(const Surface &out, int y1, int y2) { int yd1 = y1 * 12 + 44 + UI_OFFSET_Y; int yd2 = y2 * 12 + 44 + UI_OFFSET_Y; if (stextscrlubtn != -1) CelDrawTo(out, { PANEL_X + 601, yd1 }, *pSTextSlidCels, 11); else CelDrawTo(out, { PANEL_X + 601, yd1 }, *pSTextSlidCels, 9); if (stextscrldbtn != -1) CelDrawTo(out, { PANEL_X + 601, yd2 }, *pSTextSlidCels, 10); else CelDrawTo(out, { PANEL_X + 601, yd2 }, *pSTextSlidCels, 8); yd1 += 12; int yd3 = yd1; for (; yd3 < yd2; yd3 += 12) { CelDrawTo(out, { PANEL_X + 601, yd3 }, *pSTextSlidCels, 13); } if (stextsel == BackButtonLine()) yd3 = stextlhold; else yd3 = stextsel; if (storenumh > 1) yd3 = 1000 * (stextsval + ((yd3 - stextup) / 4)) / (storenumh - 1) * (y2 * 12 - y1 * 12 - 24) / 1000; else yd3 = 0; CelDrawTo(out, { PANEL_X + 601, (y1 + 1) * 12 + 44 + UI_OFFSET_Y + yd3 }, *pSTextSlidCels, 12); } void AddSLine(int y) { stext[y]._sx = 0; stext[y]._syoff = 0; stext[y]._sstr[0] = 0; stext[y]._sline = 1; } void AddSTextVal(int y, int val) { stext[y]._sval = val; } void AddSText(int x, int y, string_view text, UiFlags flags, bool sel) { stext[y]._sx = x; stext[y]._syoff = 0; CopyUtf8(stext[y]._sstr, text, sizeof(stext[y]._sstr)); stext[y].flags = flags; stext[y]._sline = 0; stext[y]._ssel = sel; } void AddOptionsBackButton() { const int line = BackButtonLine(); AddSText(0, line, _("Back"), UiFlags::ColorWhite | UiFlags::AlignCenter, true); stext[line]._syoff = IsSmallFontTall() ? 0 : 6; } void AddItemListBackButton(bool selectable = false) { const int line = BackButtonLine(); string_view text = _("Back"); if (!selectable && IsSmallFontTall()) { AddSText(0, line, text, UiFlags::ColorWhite | UiFlags::AlignRight, selectable); } else { AddSLine(line - 1); AddSText(0, line, text, UiFlags::ColorWhite | UiFlags::AlignCenter, selectable); stext[line]._syoff = 6; } } void PrintStoreItem(const Item &item, int l, UiFlags flags) { std::string productLine = ""; if (item._iIdentified) { if (item._iMagical != ITEM_QUALITY_UNIQUE) { if (item._iPrePower != -1) { productLine.append(PrintItemPower(item._iPrePower, item)); } } if (item._iSufPower != -1) { if (!productLine.empty()) productLine.append(_(", ")); productLine.append(PrintItemPower(item._iSufPower, item)); } } if (item._iMiscId == IMISC_STAFF && item._iMaxCharges != 0) { if (!productLine.empty()) productLine.append(_(", ")); productLine.append(fmt::format(_("Charges: {:d}/{:d}"), item._iCharges, item._iMaxCharges)); } if (!productLine.empty()) { AddSText(40, l, productLine, flags, false); l++; productLine = ""; } if (item._itype != ItemType::Misc) { if (item._iClass == ICLASS_WEAPON) productLine = fmt::format(_("Damage: {:d}-{:d} "), item._iMinDam, item._iMaxDam); else if (item._iClass == ICLASS_ARMOR) productLine = fmt::format(_("Armor: {:d} "), item._iAC); if (item._iMaxDur != DUR_INDESTRUCTIBLE && item._iMaxDur != 0) productLine += fmt::format(_("Dur: {:d}/{:d}, "), item._iDurability, item._iMaxDur); else productLine += _("Indestructible, "); } int8_t str = item._iMinStr; uint8_t mag = item._iMinMag; int8_t dex = item._iMinDex; if (str == 0 && mag == 0 && dex == 0) { productLine.append(_("No required attributes")); } else { productLine.append(_("Required:")); if (str != 0) productLine.append(fmt::format(_(" {:d} Str"), str)); if (mag != 0) productLine.append(fmt::format(_(" {:d} Mag"), mag)); if (dex != 0) productLine.append(fmt::format(_(" {:d} Dex"), dex)); } AddSText(40, l++, productLine, flags, false); } bool StoreAutoPlace(Item &item, bool persistItem) { auto &myPlayer = Players[MyPlayerId]; if (AutoEquipEnabled(myPlayer, item) && AutoEquip(MyPlayerId, item, persistItem)) { return true; } if (AutoPlaceItemInBelt(myPlayer, item, persistItem)) { return true; } return AutoPlaceItemInInventory(myPlayer, item, persistItem); } void StartSmith() { stextsize = false; stextscrl = false; AddSText(0, 1, _("Welcome to the"), UiFlags::ColorWhitegold | UiFlags::AlignCenter, false); AddSText(0, 3, _("Blacksmith's shop"), UiFlags::ColorWhitegold | UiFlags::AlignCenter, false); AddSText(0, 7, _("Would you like to:"), UiFlags::ColorWhitegold | UiFlags::AlignCenter, false); AddSText(0, 10, _("Talk to Griswold"), UiFlags::ColorBlue | UiFlags::AlignCenter, true); AddSText(0, 12, _("Buy basic items"), UiFlags::ColorWhite | UiFlags::AlignCenter, true); AddSText(0, 14, _("Buy premium items"), UiFlags::ColorWhite | UiFlags::AlignCenter, true); AddSText(0, 16, _("Sell items"), UiFlags::ColorWhite | UiFlags::AlignCenter, true); AddSText(0, 18, _("Repair items"), UiFlags::ColorWhite | UiFlags::AlignCenter, true); AddSText(0, 20, _("Leave the shop"), UiFlags::ColorWhite | UiFlags::AlignCenter, true); AddSLine(5); storenumh = 20; } void ScrollSmithBuy(int idx) { ClearSText(5, 21); stextup = 5; for (int l = 5; l < 20; l += 4) { if (!smithitem[idx].isEmpty()) { UiFlags itemColor = smithitem[idx].getTextColorWithStatCheck(); if (smithitem[idx]._iMagical != ITEM_QUALITY_NORMAL) { AddSText(20, l, smithitem[idx]._iIName, itemColor, true); } else { AddSText(20, l, smithitem[idx]._iName, itemColor, true); } AddSTextVal(l, smithitem[idx]._iIvalue); PrintStoreItem(smithitem[idx], l + 1, itemColor); stextdown = l; idx++; } } if (stextsel != -1 && !stext[stextsel]._ssel && stextsel != BackButtonLine()) stextsel = stextdown; } uint32_t TotalPlayerGold() { return MyPlayer->_pGold + Stash.gold; } // TODO: Change `_iIvalue` to be unsigned instead of passing `int` here. bool PlayerCanAfford(int price) { return TotalPlayerGold() >= static_cast<uint32_t>(price); } void StartSmithBuy() { stextsize = true; stextscrl = true; stextsval = 0; RenderGold = true; AddSText(20, 1, _("I have these items for sale:"), UiFlags::ColorWhitegold, false); AddSLine(3); ScrollSmithBuy(stextsval); AddItemListBackButton(); storenumh = 0; for (Item &item : smithitem) { if (item.isEmpty()) continue; item._iStatFlag = MyPlayer->CanUseItem(item); storenumh++; } stextsmax = std::max(storenumh - 4, 0); } void ScrollSmithPremiumBuy(int boughtitems) { ClearSText(5, 21); stextup = 5; int idx = 0; for (; boughtitems != 0; idx++) { if (!premiumitems[idx].isEmpty()) boughtitems--; } for (int l = 5; l < 20 && idx < SMITH_PREMIUM_ITEMS; l += 4) { if (!premiumitems[idx].isEmpty()) { UiFlags itemColor = premiumitems[idx].getTextColorWithStatCheck(); AddSText(20, l, premiumitems[idx]._iIName, itemColor, true); AddSTextVal(l, premiumitems[idx]._iIvalue); PrintStoreItem(premiumitems[idx], l + 1, itemColor); stextdown = l; } else { l -= 4; } idx++; } if (stextsel != -1 && !stext[stextsel]._ssel && stextsel != BackButtonLine()) stextsel = stextdown; } bool StartSmithPremiumBuy() { storenumh = 0; for (Item &item : premiumitems) { if (item.isEmpty()) continue; item._iStatFlag = MyPlayer->CanUseItem(item); storenumh++; } if (storenumh == 0) { StartStore(STORE_SMITH); stextsel = 14; return false; } stextsize = true; stextscrl = true; stextsval = 0; RenderGold = true; AddSText(20, 1, _("I have these premium items for sale:"), UiFlags::ColorWhitegold, false); AddSLine(3); AddItemListBackButton(); stextsmax = std::max(storenumh - 4, 0); ScrollSmithPremiumBuy(stextsval); return true; } bool SmithSellOk(int i) { Item *pI; if (i >= 0) { pI = &Players[MyPlayerId].InvList[i]; } else { pI = &Players[MyPlayerId].SpdList[-(i + 1)]; } if (pI->isEmpty()) return false; if (pI->_iMiscId > IMISC_OILFIRST && pI->_iMiscId < IMISC_OILLAST) return true; if (pI->_itype == ItemType::Misc) return false; if (pI->_itype == ItemType::Gold) return false; if (pI->_itype == ItemType::Staff && (!gbIsHellfire || pI->_iSpell != SPL_NULL)) return false; if (pI->_iClass == ICLASS_QUEST) return false; if (pI->IDidx == IDI_LAZSTAFF) return false; return true; } void ScrollSmithSell(int idx) { ClearSText(5, 21); stextup = 5; for (int l = 5; l < 20; l += 4) { if (idx >= storenumh) break; if (!storehold[idx].isEmpty()) { UiFlags itemColor = storehold[idx].getTextColorWithStatCheck(); if (storehold[idx]._iMagical != ITEM_QUALITY_NORMAL && storehold[idx]._iIdentified) { AddSText(20, l, storehold[idx]._iIName, itemColor, true); AddSTextVal(l, storehold[idx]._iIvalue); } else { AddSText(20, l, storehold[idx]._iName, itemColor, true); AddSTextVal(l, storehold[idx]._ivalue); } PrintStoreItem(storehold[idx], l + 1, itemColor); stextdown = l; } idx++; } stextsmax = std::max(storenumh - 4, 0); } void StartSmithSell() { stextsize = true; bool sellOk = false; storenumh = 0; for (auto &item : storehold) { item.clear(); } const auto &myPlayer = Players[MyPlayerId]; for (int8_t i = 0; i < myPlayer._pNumInv; i++) { if (storenumh >= 48) break; if (SmithSellOk(i)) { sellOk = true; storehold[storenumh] = myPlayer.InvList[i]; if (storehold[storenumh]._iMagical != ITEM_QUALITY_NORMAL && storehold[storenumh]._iIdentified) storehold[storenumh]._ivalue = storehold[storenumh]._iIvalue; storehold[storenumh]._ivalue = std::max(storehold[storenumh]._ivalue / 4, 1); storehold[storenumh]._iIvalue = storehold[storenumh]._ivalue; storehidx[storenumh] = i; storenumh++; } } for (int i = 0; i < MAXBELTITEMS; i++) { if (storenumh >= 48) break; if (SmithSellOk(-(i + 1))) { sellOk = true; storehold[storenumh] = myPlayer.SpdList[i]; if (storehold[storenumh]._iMagical != ITEM_QUALITY_NORMAL && storehold[storenumh]._iIdentified) storehold[storenumh]._ivalue = storehold[storenumh]._iIvalue; storehold[storenumh]._ivalue = std::max(storehold[storenumh]._ivalue / 4, 1); storehold[storenumh]._iIvalue = storehold[storenumh]._ivalue; storehidx[storenumh] = -(i + 1); storenumh++; } } if (!sellOk) { stextscrl = false; RenderGold = true; AddSText(20, 1, _("You have nothing I want."), UiFlags::ColorWhitegold, false); AddSLine(3); AddItemListBackButton(/*selectable=*/true); return; } stextscrl = true; stextsval = 0; stextsmax = myPlayer._pNumInv; RenderGold = true; AddSText(20, 1, _("Which item is for sale?"), UiFlags::ColorWhitegold, false); AddSLine(3); ScrollSmithSell(stextsval); AddItemListBackButton(); } bool SmithRepairOk(int i) { const auto &myPlayer = Players[MyPlayerId]; if (myPlayer.InvList[i].isEmpty()) return false; if (myPlayer.InvList[i]._itype == ItemType::Misc) return false; if (myPlayer.InvList[i]._itype == ItemType::Gold) return false; if (myPlayer.InvList[i]._iDurability == myPlayer.InvList[i]._iMaxDur) return false; return true; } void StartSmithRepair() { stextsize = true; bool repairok = false; storenumh = 0; for (auto &item : storehold) { item.clear(); } auto &myPlayer = Players[MyPlayerId]; auto &helmet = myPlayer.InvBody[INVLOC_HEAD]; if (!helmet.isEmpty() && helmet._iDurability != helmet._iMaxDur) { repairok = true; AddStoreHoldRepair(&helmet, -1); } auto &armor = myPlayer.InvBody[INVLOC_CHEST]; if (!armor.isEmpty() && armor._iDurability != armor._iMaxDur) { repairok = true; AddStoreHoldRepair(&armor, -2); } auto &leftHand = myPlayer.InvBody[INVLOC_HAND_LEFT]; if (!leftHand.isEmpty() && leftHand._iDurability != leftHand._iMaxDur) { repairok = true; AddStoreHoldRepair(&leftHand, -3); } auto &rightHand = myPlayer.InvBody[INVLOC_HAND_RIGHT]; if (!rightHand.isEmpty() && rightHand._iDurability != rightHand._iMaxDur) { repairok = true; AddStoreHoldRepair(&rightHand, -4); } for (int i = 0; i < myPlayer._pNumInv; i++) { if (storenumh >= 48) break; if (SmithRepairOk(i)) { repairok = true; AddStoreHoldRepair(&myPlayer.InvList[i], i); } } if (!repairok) { stextscrl = false; RenderGold = true; AddSText(20, 1, _("You have nothing to repair."), UiFlags::ColorWhitegold, false); AddSLine(3); AddItemListBackButton(/*selectable=*/true); return; } stextscrl = true; stextsval = 0; stextsmax = myPlayer._pNumInv; RenderGold = true; AddSText(20, 1, _("Repair which item?"), UiFlags::ColorWhitegold, false); AddSLine(3); ScrollSmithSell(stextsval); AddItemListBackButton(); } void FillManaPlayer() { if (!*sgOptions.Gameplay.adriaRefillsMana) return; auto &myPlayer = Players[MyPlayerId]; if (myPlayer._pMana != myPlayer._pMaxMana) { PlaySFX(IS_CAST8); } myPlayer._pMana = myPlayer._pMaxMana; myPlayer._pManaBase = myPlayer._pMaxManaBase; drawmanaflag = true; } void StartWitch() { FillManaPlayer(); stextsize = false; stextscrl = false; AddSText(0, 2, _("Witch's shack"), UiFlags::ColorWhitegold | UiFlags::AlignCenter, false); AddSText(0, 9, _("Would you like to:"), UiFlags::ColorWhitegold | UiFlags::AlignCenter, false); AddSText(0, 12, _("Talk to Adria"), UiFlags::ColorBlue | UiFlags::AlignCenter, true); AddSText(0, 14, _("Buy items"), UiFlags::ColorWhite | UiFlags::AlignCenter, true); AddSText(0, 16, _("Sell items"), UiFlags::ColorWhite | UiFlags::AlignCenter, true); AddSText(0, 18, _("Recharge staves"), UiFlags::ColorWhite | UiFlags::AlignCenter, true); AddSText(0, 20, _("Leave the shack"), UiFlags::ColorWhite | UiFlags::AlignCenter, true); AddSLine(5); storenumh = 20; } void ScrollWitchBuy(int idx) { ClearSText(5, 21); stextup = 5; for (int l = 5; l < 20; l += 4) { if (!witchitem[idx].isEmpty()) { UiFlags itemColor = witchitem[idx].getTextColorWithStatCheck(); if (witchitem[idx]._iMagical != ITEM_QUALITY_NORMAL) { AddSText(20, l, witchitem[idx]._iIName, itemColor, true); } else { AddSText(20, l, witchitem[idx]._iName, itemColor, true); } AddSTextVal(l, witchitem[idx]._iIvalue); PrintStoreItem(witchitem[idx], l + 1, itemColor); stextdown = l; idx++; } } if (stextsel != -1 && !stext[stextsel]._ssel && stextsel != BackButtonLine()) stextsel = stextdown; } void WitchBookLevel(Item &bookItem) { if (bookItem._iMiscId != IMISC_BOOK) return; bookItem._iMinMag = spelldata[bookItem._iSpell].sMinInt; int8_t spellLevel = Players[MyPlayerId]._pSplLvl[bookItem._iSpell]; while (spellLevel > 0) { bookItem._iMinMag += 20 * bookItem._iMinMag / 100; spellLevel--; if (bookItem._iMinMag + 20 * bookItem._iMinMag / 100 > 255) { bookItem._iMinMag = 255; spellLevel = 0; } } } void StartWitchBuy() { stextsize = true; stextscrl = true; stextsval = 0; stextsmax = 20; RenderGold = true; AddSText(20, 1, _("I have these items for sale:"), UiFlags::ColorWhitegold, false); AddSLine(3); ScrollWitchBuy(stextsval); AddItemListBackButton(); storenumh = 0; for (Item &item : witchitem) { if (item.isEmpty()) continue; WitchBookLevel(item); item._iStatFlag = MyPlayer->CanUseItem(item); storenumh++; } stextsmax = std::max(storenumh - 4, 0); } bool WitchSellOk(int i) { Item *pI; bool rv = false; if (i >= 0) pI = &Players[MyPlayerId].InvList[i]; else pI = &Players[MyPlayerId].SpdList[-(i + 1)]; if (pI->_itype == ItemType::Misc) rv = true; if (pI->_iMiscId > 29 && pI->_iMiscId < 41) rv = false; if (pI->_iClass == ICLASS_QUEST) rv = false; if (pI->_itype == ItemType::Staff && (!gbIsHellfire || pI->_iSpell != SPL_NULL)) rv = true; if (pI->IDidx >= IDI_FIRSTQUEST && pI->IDidx <= IDI_LASTQUEST) rv = false; if (pI->IDidx == IDI_LAZSTAFF) rv = false; return rv; } void StartWitchSell() { stextsize = true; bool sellok = false; storenumh = 0; for (auto &item : storehold) { item.clear(); } const auto &myPlayer = Players[MyPlayerId]; for (int i = 0; i < myPlayer._pNumInv; i++) { if (storenumh >= 48) break; if (WitchSellOk(i)) { sellok = true; storehold[storenumh] = myPlayer.InvList[i]; if (storehold[storenumh]._iMagical != ITEM_QUALITY_NORMAL && storehold[storenumh]._iIdentified) storehold[storenumh]._ivalue = storehold[storenumh]._iIvalue; storehold[storenumh]._ivalue = std::max(storehold[storenumh]._ivalue / 4, 1); storehold[storenumh]._iIvalue = storehold[storenumh]._ivalue; storehidx[storenumh] = i; storenumh++; } } for (int i = 0; i < MAXBELTITEMS; i++) { if (storenumh >= 48) break; if (!myPlayer.SpdList[i].isEmpty() && WitchSellOk(-(i + 1))) { sellok = true; storehold[storenumh] = myPlayer.SpdList[i]; if (storehold[storenumh]._iMagical != ITEM_QUALITY_NORMAL && storehold[storenumh]._iIdentified) storehold[storenumh]._ivalue = storehold[storenumh]._iIvalue; storehold[storenumh]._ivalue = std::max(storehold[storenumh]._ivalue / 4, 1); storehold[storenumh]._iIvalue = storehold[storenumh]._ivalue; storehidx[storenumh] = -(i + 1); storenumh++; } } if (!sellok) { stextscrl = false; RenderGold = true; AddSText(20, 1, _("You have nothing I want."), UiFlags::ColorWhitegold, false); AddSLine(3); AddItemListBackButton(/*selectable=*/true); return; } stextscrl = true; stextsval = 0; stextsmax = myPlayer._pNumInv; RenderGold = true; AddSText(20, 1, _("Which item is for sale?"), UiFlags::ColorWhitegold, false); AddSLine(3); ScrollSmithSell(stextsval); AddItemListBackButton(); } bool WitchRechargeOk(int i) { const auto &item = Players[MyPlayerId].InvList[i]; if (item._itype == ItemType::Staff && item._iCharges != item._iMaxCharges) { return true; } if ((item._iMiscId == IMISC_UNIQUE || item._iMiscId == IMISC_STAFF) && item._iCharges < item._iMaxCharges) { return true; } return false; } void AddStoreHoldRecharge(Item itm, int8_t i) { storehold[storenumh] = itm; storehold[storenumh]._ivalue += spelldata[itm._iSpell].sStaffCost; storehold[storenumh]._ivalue = storehold[storenumh]._ivalue * (storehold[storenumh]._iMaxCharges - storehold[storenumh]._iCharges) / (storehold[storenumh]._iMaxCharges * 2); storehold[storenumh]._iIvalue = storehold[storenumh]._ivalue; storehidx[storenumh] = i; storenumh++; } void StartWitchRecharge() { stextsize = true; bool rechargeok = false; storenumh = 0; for (auto &item : storehold) { item.clear(); } const auto &myPlayer = Players[MyPlayerId]; const auto &leftHand = myPlayer.InvBody[INVLOC_HAND_LEFT]; if ((leftHand._itype == ItemType::Staff || leftHand._iMiscId == IMISC_UNIQUE) && leftHand._iCharges != leftHand._iMaxCharges) { rechargeok = true; AddStoreHoldRecharge(leftHand, -1); } for (int i = 0; i < myPlayer._pNumInv; i++) { if (storenumh >= 48) break; if (WitchRechargeOk(i)) { rechargeok = true; AddStoreHoldRecharge(myPlayer.InvList[i], i); } } if (!rechargeok) { stextscrl = false; RenderGold = true; AddSText(20, 1, _("You have nothing to recharge."), UiFlags::ColorWhitegold | UiFlags::AlignCenter, false); AddSLine(3); AddItemListBackButton(/*selectable=*/true); return; } stextscrl = true; stextsval = 0; stextsmax = myPlayer._pNumInv; RenderGold = true; AddSText(20, 1, _("Recharge which item?"), UiFlags::ColorWhitegold, false); AddSLine(3); ScrollSmithSell(stextsval); AddItemListBackButton(); } void StoreNoMoney() { StartStore(stextshold); stextscrl = false; stextsize = true; RenderGold = true; ClearSText(5, 23); AddSText(0, 14, _("You do not have enough gold"), UiFlags::ColorWhite | UiFlags::AlignCenter, true); } void StoreNoRoom() { StartStore(stextshold); stextscrl = false; ClearSText(5, 23); AddSText(0, 14, _("You do not have enough room in inventory"), UiFlags::ColorWhite | UiFlags::AlignCenter, true); } void StoreConfirm(Item &item) { StartStore(stextshold); stextscrl = false; ClearSText(5, 23); UiFlags itemColor = item.getTextColorWithStatCheck(); bool idprint = item._iMagical != ITEM_QUALITY_NORMAL; if (stextshold == STORE_SIDENTIFY) idprint = false; if (item._iMagical != ITEM_QUALITY_NORMAL && !item._iIdentified) { if (stextshold == STORE_SSELL) idprint = false; if (stextshold == STORE_WSELL) idprint = false; if (stextshold == STORE_SREPAIR) idprint = false; if (stextshold == STORE_WRECHARGE) idprint = false; } if (idprint) AddSText(20, 8, item._iIName, itemColor, false); else AddSText(20, 8, item._iName, itemColor, false); AddSTextVal(8, item._iIvalue); PrintStoreItem(item, 9, itemColor); string_view prompt; switch (stextshold) { case STORE_BBOY: prompt = _("Do we have a deal?"); break; case STORE_SIDENTIFY: prompt = _("Are you sure you want to identify this item?"); break; case STORE_HBUY: case STORE_SPBUY: case STORE_WBUY: case STORE_SBUY: prompt = _("Are you sure you want to buy this item?"); break; case STORE_WRECHARGE: prompt = _("Are you sure you want to recharge this item?"); break; case STORE_SSELL: case STORE_WSELL: prompt = _("Are you sure you want to sell this item?"); break; case STORE_SREPAIR: prompt = _("Are you sure you want to repair this item?"); break; default: app_fatal("Unknown store dialog %i", stextshold); } AddSText(0, 15, prompt, UiFlags::ColorWhite | UiFlags::AlignCenter, false); AddSText(0, 18, _("Yes"), UiFlags::ColorWhite | UiFlags::AlignCenter, true); AddSText(0, 20, _("No"), UiFlags::ColorWhite | UiFlags::AlignCenter, true); } void StartBoy() { stextsize = false; stextscrl = false; AddSText(0, 2, _("Wirt the Peg-legged boy"), UiFlags::ColorWhitegold | UiFlags::AlignCenter, false); AddSLine(5); if (!boyitem.isEmpty()) { AddSText(0, 8, _("Talk to Wirt"), UiFlags::ColorBlue | UiFlags::AlignCenter, true); AddSText(0, 12, _("I have something for sale,"), UiFlags::ColorWhitegold | UiFlags::AlignCenter, false); AddSText(0, 14, _("but it will cost 50 gold"), UiFlags::ColorWhitegold | UiFlags::AlignCenter, false); AddSText(0, 16, _("just to take a look. "), UiFlags::ColorWhitegold | UiFlags::AlignCenter, false); AddSText(0, 18, _("What have you got?"), UiFlags::ColorWhite | UiFlags::AlignCenter, true); AddSText(0, 20, _("Say goodbye"), UiFlags::ColorWhite | UiFlags::AlignCenter, true); } else { AddSText(0, 12, _("Talk to Wirt"), UiFlags::ColorBlue | UiFlags::AlignCenter, true); AddSText(0, 18, _("Say goodbye"), UiFlags::ColorWhite | UiFlags::AlignCenter, true); } } void SStartBoyBuy() { stextsize = true; stextscrl = false; RenderGold = true; AddSText(20, 1, _("I have this item for sale:"), UiFlags::ColorWhitegold, false); AddSLine(3); boyitem._iStatFlag = MyPlayer->CanUseItem(boyitem); UiFlags itemColor = boyitem.getTextColorWithStatCheck(); if (boyitem._iMagical != ITEM_QUALITY_NORMAL) AddSText(20, 10, boyitem._iIName, itemColor, true); else AddSText(20, 10, boyitem._iName, itemColor, true); if (gbIsHellfire) AddSTextVal(10, boyitem._iIvalue - (boyitem._iIvalue / 4)); else AddSTextVal(10, boyitem._iIvalue + (boyitem._iIvalue / 2)); PrintStoreItem(boyitem, 11, itemColor); { // Add a Leave button. Unlike the other item list back buttons, // this one has different text and different layout in LargerSmallFont locales. const int line = BackButtonLine(); AddSLine(line - 1); AddSText(0, line, _("Leave"), UiFlags::ColorWhite | UiFlags::AlignCenter, true); stext[line]._syoff = 6; } } void HealPlayer() { auto &myPlayer = Players[MyPlayerId]; if (myPlayer._pHitPoints != myPlayer._pMaxHP) { PlaySFX(IS_CAST8); } myPlayer._pHitPoints = myPlayer._pMaxHP; myPlayer._pHPBase = myPlayer._pMaxHPBase; drawhpflag = true; } void StartHealer() { HealPlayer(); stextsize = false; stextscrl = false; AddSText(0, 1, _("Welcome to the"), UiFlags::ColorWhitegold | UiFlags::AlignCenter, false); AddSText(0, 3, _("Healer's home"), UiFlags::ColorWhitegold | UiFlags::AlignCenter, false); AddSText(0, 9, _("Would you like to:"), UiFlags::ColorWhitegold | UiFlags::AlignCenter, false); AddSText(0, 12, _("Talk to Pepin"), UiFlags::ColorBlue | UiFlags::AlignCenter, true); AddSText(0, 14, _("Buy items"), UiFlags::ColorWhite | UiFlags::AlignCenter, true); AddSText(0, 18, _("Leave Healer's home"), UiFlags::ColorWhite | UiFlags::AlignCenter, true); AddSLine(5); storenumh = 20; } void ScrollHealerBuy(int idx) { ClearSText(5, 21); stextup = 5; for (int l = 5; l < 20; l += 4) { if (!healitem[idx].isEmpty()) { UiFlags itemColor = healitem[idx].getTextColorWithStatCheck(); AddSText(20, l, healitem[idx]._iName, itemColor, true); AddSTextVal(l, healitem[idx]._iIvalue); PrintStoreItem(healitem[idx], l + 1, itemColor); stextdown = l; idx++; } } if (stextsel != -1 && !stext[stextsel]._ssel && stextsel != BackButtonLine()) stextsel = stextdown; } void StartHealerBuy() { stextsize = true; stextscrl = true; stextsval = 0; RenderGold = true; AddSText(20, 1, _("I have these items for sale:"), UiFlags::ColorWhitegold, false); AddSLine(3); ScrollHealerBuy(stextsval); AddItemListBackButton(); storenumh = 0; for (Item &item : healitem) { if (item.isEmpty()) continue; item._iStatFlag = MyPlayer->CanUseItem(item); storenumh++; } stextsmax = std::max(storenumh - 4, 0); } void StartStoryteller() { stextsize = false; stextscrl = false; AddSText(0, 2, _("The Town Elder"), UiFlags::ColorWhitegold | UiFlags::AlignCenter, false); AddSText(0, 9, _("Would you like to:"), UiFlags::ColorWhitegold | UiFlags::AlignCenter, false); AddSText(0, 12, _("Talk to Cain"), UiFlags::ColorBlue | UiFlags::AlignCenter, true); AddSText(0, 14, _("Identify an item"), UiFlags::ColorWhite | UiFlags::AlignCenter, true); AddSText(0, 18, _("Say goodbye"), UiFlags::ColorWhite | UiFlags::AlignCenter, true); AddSLine(5); } bool IdItemOk(Item *i) { if (i->isEmpty()) { return false; } if (i->_iMagical == ITEM_QUALITY_NORMAL) { return false; } return !i->_iIdentified; } void AddStoreHoldId(Item itm, int8_t i) { storehold[storenumh] = itm; storehold[storenumh]._ivalue = 100; storehold[storenumh]._iIvalue = 100; storehidx[storenumh] = i; storenumh++; } void StartStorytellerIdentify() { bool idok = false; stextsize = true; storenumh = 0; for (auto &item : storehold) { item.clear(); } auto &myPlayer = Players[MyPlayerId]; auto &helmet = myPlayer.InvBody[INVLOC_HEAD]; if (IdItemOk(&helmet)) { idok = true; AddStoreHoldId(helmet, -1); } auto &armor = myPlayer.InvBody[INVLOC_CHEST]; if (IdItemOk(&armor)) { idok = true; AddStoreHoldId(armor, -2); } auto &leftHand = myPlayer.InvBody[INVLOC_HAND_LEFT]; if (IdItemOk(&leftHand)) { idok = true; AddStoreHoldId(leftHand, -3); } auto &rightHand = myPlayer.InvBody[INVLOC_HAND_RIGHT]; if (IdItemOk(&rightHand)) { idok = true; AddStoreHoldId(rightHand, -4); } auto &leftRing = myPlayer.InvBody[INVLOC_RING_LEFT]; if (IdItemOk(&leftRing)) { idok = true; AddStoreHoldId(leftRing, -5); } auto &rightRing = myPlayer.InvBody[INVLOC_RING_RIGHT]; if (IdItemOk(&rightRing)) { idok = true; AddStoreHoldId(rightRing, -6); } auto &amulet = myPlayer.InvBody[INVLOC_AMULET]; if (IdItemOk(&amulet)) { idok = true; AddStoreHoldId(amulet, -7); } for (int i = 0; i < myPlayer._pNumInv; i++) { if (storenumh >= 48) break; auto &item = myPlayer.InvList[i]; if (IdItemOk(&item)) { idok = true; AddStoreHoldId(item, i); } } if (!idok) { stextscrl = false; RenderGold = true; AddSText(20, 1, _("You have nothing to identify."), UiFlags::ColorWhitegold, false); AddSLine(3); AddItemListBackButton(/*selectable=*/true); return; } stextscrl = true; stextsval = 0; stextsmax = myPlayer._pNumInv; RenderGold = true; AddSText(20, 1, _("Identify which item?"), UiFlags::ColorWhitegold, false); AddSLine(3); ScrollSmithSell(stextsval); AddItemListBackButton(); } void StartStorytellerIdentifyShow(Item &item) { StartStore(stextshold); stextscrl = false; ClearSText(5, 23); UiFlags itemColor = item.getTextColorWithStatCheck(); AddSText(0, 7, _("This item is:"), UiFlags::ColorWhite | UiFlags::AlignCenter, false); AddSText(20, 11, item._iIName, itemColor, false); PrintStoreItem(item, 12, itemColor); AddSText(0, 18, _("Done"), UiFlags::ColorWhite | UiFlags::AlignCenter, true); } void StartTalk() { int la; stextsize = false; stextscrl = false; AddSText(0, 2, fmt::format(_("Talk to {:s}"), _(TownerNames[talker])), UiFlags::ColorWhitegold | UiFlags::AlignCenter, false); AddSLine(5); if (gbIsSpawn) { AddSText(0, 10, fmt::format(_("Talking to {:s}"), _(TownerNames[talker])), UiFlags::ColorWhite | UiFlags::AlignCenter, false); AddSText(0, 12, _("is not available"), UiFlags::ColorWhite | UiFlags::AlignCenter, false); AddSText(0, 14, _("in the shareware"), UiFlags::ColorWhite | UiFlags::AlignCenter, false); AddSText(0, 16, _("version"), UiFlags::ColorWhite | UiFlags::AlignCenter, false); AddOptionsBackButton(); return; } int sn = 0; for (auto &quest : Quests) { if (quest._qactive == QUEST_ACTIVE && QuestDialogTable[talker][quest._qidx] != TEXT_NONE && quest._qlog) sn++; } if (sn > 6) { sn = 14 - (sn / 2); la = 1; } else { sn = 15 - sn; la = 2; } int sn2 = sn - 2; for (auto &quest : Quests) { if (quest._qactive == QUEST_ACTIVE && QuestDialogTable[talker][quest._qidx] != TEXT_NONE && quest._qlog) { AddSText(0, sn, _(QuestsData[quest._qidx]._qlstr), UiFlags::ColorWhite | UiFlags::AlignCenter, true); sn += la; } } AddSText(0, sn2, _("Gossip"), UiFlags::ColorBlue | UiFlags::AlignCenter, true); AddOptionsBackButton(); } void StartTavern() { stextsize = false; stextscrl = false; AddSText(0, 1, _("Welcome to the"), UiFlags::ColorWhitegold | UiFlags::AlignCenter, false); AddSText(0, 3, _("Rising Sun"), UiFlags::ColorWhitegold | UiFlags::AlignCenter, false); AddSText(0, 9, _("Would you like to:"), UiFlags::ColorWhitegold | UiFlags::AlignCenter, false); AddSText(0, 12, _("Talk to Ogden"), UiFlags::ColorBlue | UiFlags::AlignCenter, true); AddSText(0, 18, _("Leave the tavern"), UiFlags::ColorWhite | UiFlags::AlignCenter, true); AddSLine(5); storenumh = 20; } void StartBarmaid() { stextsize = false; stextscrl = false; AddSText(0, 2, _("Gillian"), UiFlags::ColorWhitegold | UiFlags::AlignCenter, false); AddSText(0, 9, _("Would you like to:"), UiFlags::ColorWhitegold | UiFlags::AlignCenter, false); AddSText(0, 12, _("Talk to Gillian"), UiFlags::ColorBlue | UiFlags::AlignCenter, true); AddSText(0, 14, _("Access Storage"), UiFlags::ColorWhite | UiFlags::AlignCenter, true); AddSText(0, 18, _("Say goodbye"), UiFlags::ColorWhite | UiFlags::AlignCenter, true); AddSLine(5); storenumh = 20; } void StartDrunk() { stextsize = false; stextscrl = false; AddSText(0, 2, _("Farnham the Drunk"), UiFlags::ColorWhitegold | UiFlags::AlignCenter, false); AddSText(0, 9, _("Would you like to:"), UiFlags::ColorWhitegold | UiFlags::AlignCenter, false); AddSText(0, 12, _("Talk to Farnham"), UiFlags::ColorBlue | UiFlags::AlignCenter, true); AddSText(0, 18, _("Say Goodbye"), UiFlags::ColorWhite | UiFlags::AlignCenter, true); AddSLine(5); storenumh = 20; } void SmithEnter() { switch (stextsel) { case 10: talker = TOWN_SMITH; stextlhold = 10; stextshold = STORE_SMITH; gossipstart = TEXT_GRISWOLD2; gossipend = TEXT_GRISWOLD13; StartStore(STORE_GOSSIP); break; case 12: StartStore(STORE_SBUY); break; case 14: StartStore(STORE_SPBUY); break; case 16: StartStore(STORE_SSELL); break; case 18: StartStore(STORE_SREPAIR); break; case 20: stextflag = STORE_NONE; break; } } /** * @brief Purchases an item from the smith. */ void SmithBuyItem(Item &item) { TakePlrsMoney(item._iIvalue); if (item._iMagical == ITEM_QUALITY_NORMAL) item._iIdentified = false; StoreAutoPlace(item, true); int idx = stextvhold + ((stextlhold - stextup) / 4); if (idx == SMITH_ITEMS - 1) { smithitem[SMITH_ITEMS - 1].clear(); } else { for (; !smithitem[idx + 1].isEmpty(); idx++) { smithitem[idx] = std::move(smithitem[idx + 1]); } smithitem[idx].clear(); } CalcPlrInv(*MyPlayer, true); } void SmithBuyEnter() { if (stextsel == BackButtonLine()) { StartStore(STORE_SMITH); stextsel = 12; return; } stextlhold = stextsel; stextvhold = stextsval; stextshold = STORE_SBUY; int idx = stextsval + ((stextsel - stextup) / 4); if (!PlayerCanAfford(smithitem[idx]._iIvalue)) { StartStore(STORE_NOMONEY); return; } if (!StoreAutoPlace(smithitem[idx], false)) { StartStore(STORE_NOROOM); return; } StoreItem = smithitem[idx]; StartStore(STORE_CONFIRM); } /** * @brief Purchases a premium item from the smith. */ void SmithBuyPItem(Item &item) { TakePlrsMoney(item._iIvalue); if (item._iMagical == ITEM_QUALITY_NORMAL) item._iIdentified = false; StoreAutoPlace(item, true); int idx = stextvhold + ((stextlhold - stextup) / 4); int xx = 0; for (int i = 0; idx >= 0; i++) { if (!premiumitems[i].isEmpty()) { idx--; xx = i; } } premiumitems[xx].clear(); numpremium--; SpawnPremium(MyPlayerId); } void SmithPremiumBuyEnter() { if (stextsel == BackButtonLine()) { StartStore(STORE_SMITH); stextsel = 14; return; } stextshold = STORE_SPBUY; stextlhold = stextsel; stextvhold = stextsval; int xx = stextsval + ((stextsel - stextup) / 4); int idx = 0; for (int i = 0; xx >= 0; i++) { if (!premiumitems[i].isEmpty()) { xx--; idx = i; } } if (!PlayerCanAfford(premiumitems[idx]._iIvalue)) { StartStore(STORE_NOMONEY); return; } if (!StoreAutoPlace(premiumitems[idx], false)) { StartStore(STORE_NOROOM); return; } StoreItem = premiumitems[idx]; StartStore(STORE_CONFIRM); } bool StoreGoldFit(Item &item) { int cost = item._iIvalue; Size itemSize = GetInventorySize(item); int itemRoomForGold = itemSize.width * itemSize.height * MaxGold; if (cost <= itemRoomForGold) { return true; } return cost <= itemRoomForGold + RoomForGold(); } /** * @brief Sells an item from the player's inventory or belt. */ void StoreSellItem() { auto &myPlayer = Players[MyPlayerId]; int idx = stextvhold + ((stextlhold - stextup) / 4); if (storehidx[idx] >= 0) myPlayer.RemoveInvItem(storehidx[idx]); else myPlayer.RemoveSpdBarItem(-(storehidx[idx] + 1)); int cost = storehold[idx]._iIvalue; storenumh--; if (idx != storenumh) { while (idx < storenumh) { storehold[idx] = storehold[idx + 1]; storehidx[idx] = storehidx[idx + 1]; idx++; } } AddGoldToInventory(myPlayer, cost); myPlayer._pGold += cost; } void SmithSellEnter() { if (stextsel == BackButtonLine()) { StartStore(STORE_SMITH); stextsel = 16; return; } stextlhold = stextsel; stextshold = STORE_SSELL; stextvhold = stextsval; int idx = stextsval + ((stextsel - stextup) / 4); if (!StoreGoldFit(storehold[idx])) { StartStore(STORE_NOROOM); return; } StoreItem = storehold[idx]; StartStore(STORE_CONFIRM); } /** * @brief Repairs an item in the player's inventory or body in the smith. */ void SmithRepairItem(int price) { TakePlrsMoney(price); int idx = stextvhold + ((stextlhold - stextup) / 4); storehold[idx]._iDurability = storehold[idx]._iMaxDur; int8_t i = storehidx[idx]; auto &myPlayer = *MyPlayer; if (i < 0) { if (i == -1) myPlayer.InvBody[INVLOC_HEAD]._iDurability = myPlayer.InvBody[INVLOC_HEAD]._iMaxDur; if (i == -2) myPlayer.InvBody[INVLOC_CHEST]._iDurability = myPlayer.InvBody[INVLOC_CHEST]._iMaxDur; if (i == -3) myPlayer.InvBody[INVLOC_HAND_LEFT]._iDurability = myPlayer.InvBody[INVLOC_HAND_LEFT]._iMaxDur; if (i == -4) myPlayer.InvBody[INVLOC_HAND_RIGHT]._iDurability = myPlayer.InvBody[INVLOC_HAND_RIGHT]._iMaxDur; return; } myPlayer.InvList[i]._iDurability = myPlayer.InvList[i]._iMaxDur; } void SmithRepairEnter() { if (stextsel == BackButtonLine()) { StartStore(STORE_SMITH); stextsel = 18; return; } stextshold = STORE_SREPAIR; stextlhold = stextsel; stextvhold = stextsval; int idx = stextsval + ((stextsel - stextup) / 4); if (!PlayerCanAfford(storehold[idx]._iIvalue)) { StartStore(STORE_NOMONEY); return; } StoreItem = storehold[idx]; StartStore(STORE_CONFIRM); } void WitchEnter() { switch (stextsel) { case 12: stextlhold = 12; talker = TOWN_WITCH; stextshold = STORE_WITCH; gossipstart = TEXT_ADRIA2; gossipend = TEXT_ADRIA13; StartStore(STORE_GOSSIP); break; case 14: StartStore(STORE_WBUY); break; case 16: StartStore(STORE_WSELL); break; case 18: StartStore(STORE_WRECHARGE); break; case 20: stextflag = STORE_NONE; break; } } /** * @brief Purchases an item from the witch. */ void WitchBuyItem(Item &item) { int idx = stextvhold + ((stextlhold - stextup) / 4); if (idx < 3) item._iSeed = AdvanceRndSeed(); TakePlrsMoney(item._iIvalue); StoreAutoPlace(item, true); if (idx >= 3) { if (idx == WITCH_ITEMS - 1) { witchitem[WITCH_ITEMS - 1].clear(); } else { for (; !witchitem[idx + 1].isEmpty(); idx++) { witchitem[idx] = std::move(witchitem[idx + 1]); } witchitem[idx].clear(); } } CalcPlrInv(*MyPlayer, true); } void WitchBuyEnter() { if (stextsel == BackButtonLine()) { StartStore(STORE_WITCH); stextsel = 14; return; } stextlhold = stextsel; stextvhold = stextsval; stextshold = STORE_WBUY; int idx = stextsval + ((stextsel - stextup) / 4); if (!PlayerCanAfford(witchitem[idx]._iIvalue)) { StartStore(STORE_NOMONEY); return; } if (!StoreAutoPlace(witchitem[idx], false)) { StartStore(STORE_NOROOM); return; } StoreItem = witchitem[idx]; StartStore(STORE_CONFIRM); } void WitchSellEnter() { if (stextsel == BackButtonLine()) { StartStore(STORE_WITCH); stextsel = 16; return; } stextlhold = stextsel; stextshold = STORE_WSELL; stextvhold = stextsval; int idx = stextsval + ((stextsel - stextup) / 4); if (!StoreGoldFit(storehold[idx])) { StartStore(STORE_NOROOM); return; } StoreItem = storehold[idx]; StartStore(STORE_CONFIRM); } /** * @brief Recharges an item in the player's inventory or body in the witch. */ void WitchRechargeItem(int price) { TakePlrsMoney(price); int idx = stextvhold + ((stextlhold - stextup) / 4); storehold[idx]._iCharges = storehold[idx]._iMaxCharges; auto &myPlayer = *MyPlayer; int8_t i = storehidx[idx]; if (i < 0) myPlayer.InvBody[INVLOC_HAND_LEFT]._iCharges = myPlayer.InvBody[INVLOC_HAND_LEFT]._iMaxCharges; else myPlayer.InvList[i]._iCharges = myPlayer.InvList[i]._iMaxCharges; CalcPlrInv(myPlayer, true); } void WitchRechargeEnter() { if (stextsel == BackButtonLine()) { StartStore(STORE_WITCH); stextsel = 18; return; } stextshold = STORE_WRECHARGE; stextlhold = stextsel; stextvhold = stextsval; int idx = stextsval + ((stextsel - stextup) / 4); if (!PlayerCanAfford(storehold[idx]._iIvalue)) { StartStore(STORE_NOMONEY); return; } StoreItem = storehold[idx]; StartStore(STORE_CONFIRM); } void BoyEnter() { if (!boyitem.isEmpty() && stextsel == 18) { if (!PlayerCanAfford(50)) { stextshold = STORE_BOY; stextlhold = 18; stextvhold = stextsval; StartStore(STORE_NOMONEY); } else { TakePlrsMoney(50); StartStore(STORE_BBOY); } return; } if ((stextsel != 8 && !boyitem.isEmpty()) || (stextsel != 12 && boyitem.isEmpty())) { stextflag = STORE_NONE; return; } talker = TOWN_PEGBOY; stextshold = STORE_BOY; stextlhold = stextsel; gossipstart = TEXT_WIRT2; gossipend = TEXT_WIRT12; StartStore(STORE_GOSSIP); } void BoyBuyItem(Item &item) { TakePlrsMoney(item._iIvalue); StoreAutoPlace(item, true); boyitem.clear(); stextshold = STORE_BOY; CalcPlrInv(*MyPlayer, true); stextlhold = 12; } /** * @brief Purchases an item from the healer. */ void HealerBuyItem(Item &item) { int idx = stextvhold + ((stextlhold - stextup) / 4); if (!gbIsMultiplayer) { if (idx < 2) item._iSeed = AdvanceRndSeed(); } else { if (idx < 3) item._iSeed = AdvanceRndSeed(); } TakePlrsMoney(item._iIvalue); if (item._iMagical == ITEM_QUALITY_NORMAL) item._iIdentified = false; StoreAutoPlace(item, true); if (!gbIsMultiplayer) { if (idx < 2) return; } else { if (idx < 3) return; } idx = stextvhold + ((stextlhold - stextup) / 4); if (idx == 19) { healitem[19].clear(); } else { for (; !healitem[idx + 1].isEmpty(); idx++) { healitem[idx] = std::move(healitem[idx + 1]); } healitem[idx].clear(); } CalcPlrInv(*MyPlayer, true); } void BoyBuyEnter() { if (stextsel != 10) { stextflag = STORE_NONE; return; } stextshold = STORE_BBOY; stextvhold = stextsval; stextlhold = 10; int price = boyitem._iIvalue; if (gbIsHellfire) price -= boyitem._iIvalue / 4; else price += boyitem._iIvalue / 2; if (TotalPlayerGold() < price) { StartStore(STORE_NOMONEY); return; } if (!StoreAutoPlace(boyitem, false)) { StartStore(STORE_NOROOM); return; } StoreItem = boyitem; StoreItem._iIvalue = price; StartStore(STORE_CONFIRM); } void StorytellerIdentifyItem(Item &item) { auto &myPlayer = Players[MyPlayerId]; int8_t idx = storehidx[((stextlhold - stextup) / 4) + stextvhold]; if (idx < 0) { if (idx == -1) myPlayer.InvBody[INVLOC_HEAD]._iIdentified = true; if (idx == -2) myPlayer.InvBody[INVLOC_CHEST]._iIdentified = true; if (idx == -3) myPlayer.InvBody[INVLOC_HAND_LEFT]._iIdentified = true; if (idx == -4) myPlayer.InvBody[INVLOC_HAND_RIGHT]._iIdentified = true; if (idx == -5) myPlayer.InvBody[INVLOC_RING_LEFT]._iIdentified = true; if (idx == -6) myPlayer.InvBody[INVLOC_RING_RIGHT]._iIdentified = true; if (idx == -7) myPlayer.InvBody[INVLOC_AMULET]._iIdentified = true; } else { myPlayer.InvList[idx]._iIdentified = true; } item._iIdentified = true; TakePlrsMoney(item._iIvalue); CalcPlrInv(myPlayer, true); } void ConfirmEnter(Item &item) { if (stextsel == 18) { switch (stextshold) { case STORE_SBUY: SmithBuyItem(item); break; case STORE_SSELL: case STORE_WSELL: StoreSellItem(); break; case STORE_SREPAIR: SmithRepairItem(item._iIvalue); break; case STORE_WBUY: WitchBuyItem(item); break; case STORE_WRECHARGE: WitchRechargeItem(item._iIvalue); break; case STORE_BBOY: BoyBuyItem(item); break; case STORE_HBUY: HealerBuyItem(item); break; case STORE_SIDENTIFY: StorytellerIdentifyItem(item); StartStore(STORE_IDSHOW); return; case STORE_SPBUY: SmithBuyPItem(item); break; default: break; } } StartStore(stextshold); if (stextsel == BackButtonLine()) return; stextsel = stextlhold; stextsval = std::min(stextvhold, stextsmax); while (stextsel != -1 && !stext[stextsel]._ssel) { stextsel--; } } void HealerEnter() { switch (stextsel) { case 12: stextlhold = 12; talker = TOWN_HEALER; stextshold = STORE_HEALER; gossipstart = TEXT_PEPIN2; gossipend = TEXT_PEPIN11; StartStore(STORE_GOSSIP); break; case 14: StartStore(STORE_HBUY); break; case 18: stextflag = STORE_NONE; break; } } void HealerBuyEnter() { if (stextsel == BackButtonLine()) { StartStore(STORE_HEALER); stextsel = 14; return; } stextlhold = stextsel; stextvhold = stextsval; stextshold = STORE_HBUY; int idx = stextsval + ((stextsel - stextup) / 4); if (TotalPlayerGold() < healitem[idx]._iIvalue) { StartStore(STORE_NOMONEY); return; } if (!StoreAutoPlace(healitem[idx], false)) { StartStore(STORE_NOROOM); return; } StoreItem = healitem[idx]; StartStore(STORE_CONFIRM); } void StorytellerEnter() { switch (stextsel) { case 12: stextlhold = 12; talker = TOWN_STORY; stextshold = STORE_STORY; gossipstart = TEXT_STORY2; gossipend = TEXT_STORY11; StartStore(STORE_GOSSIP); break; case 14: StartStore(STORE_SIDENTIFY); break; case 18: stextflag = STORE_NONE; break; } } void StorytellerIdentifyEnter() { if (stextsel == BackButtonLine()) { StartStore(STORE_STORY); stextsel = 14; return; } stextshold = STORE_SIDENTIFY; stextlhold = stextsel; stextvhold = stextsval; int idx = stextsval + ((stextsel - stextup) / 4); if (!PlayerCanAfford(storehold[idx]._iIvalue)) { StartStore(STORE_NOMONEY); return; } StoreItem = storehold[idx]; StartStore(STORE_CONFIRM); } void TalkEnter() { if (stextsel == BackButtonLine()) { StartStore(stextshold); stextsel = stextlhold; return; } int sn = 0; for (auto &quest : Quests) { if (quest._qactive == QUEST_ACTIVE && QuestDialogTable[talker][quest._qidx] != TEXT_NONE && quest._qlog) sn++; } int la = 2; if (sn > 6) { sn = 14 - (sn / 2); la = 1; } else { sn = 15 - sn; } if (stextsel == sn - 2) { SetRndSeed(Towners[talker].seed); auto tq = static_cast<_speech_id>(gossipstart + GenerateRnd(gossipend - gossipstart + 1)); InitQTextMsg(tq); return; } for (auto &quest : Quests) { if (quest._qactive == QUEST_ACTIVE && QuestDialogTable[talker][quest._qidx] != TEXT_NONE && quest._qlog) { if (sn == stextsel) { InitQTextMsg(QuestDialogTable[talker][quest._qidx]); } sn += la; } } } void TavernEnter() { switch (stextsel) { case 12: stextlhold = 12; talker = TOWN_TAVERN; stextshold = STORE_TAVERN; gossipstart = TEXT_OGDEN2; gossipend = TEXT_OGDEN10; StartStore(STORE_GOSSIP); break; case 18: stextflag = STORE_NONE; break; } } void BarmaidEnter() { switch (stextsel) { case 12: stextlhold = 12; talker = TOWN_BMAID; stextshold = STORE_BARMAID; gossipstart = TEXT_GILLIAN2; gossipend = TEXT_GILLIAN10; StartStore(STORE_GOSSIP); break; case 14: stextflag = STORE_NONE; IsStashOpen = true; Stash.RefreshItemStatFlags(); invflag = true; if (ControlMode != ControlTypes::KeyboardAndMouse) { if (pcurs == CURSOR_DISARM) NewCursor(CURSOR_HAND); FocusOnInventory(); } break; case 18: stextflag = STORE_NONE; break; } } void DrunkEnter() { switch (stextsel) { case 12: stextlhold = 12; talker = TOWN_DRUNK; stextshold = STORE_DRUNK; gossipstart = TEXT_FARNHAM2; gossipend = TEXT_FARNHAM13; StartStore(STORE_GOSSIP); break; case 18: stextflag = STORE_NONE; break; } } int TakeGold(Player &player, int cost, bool skipMaxPiles) { for (int i = 0; i < player._pNumInv; i++) { auto &item = player.InvList[i]; if (item._itype != ItemType::Gold || (skipMaxPiles && item._ivalue == MaxGold)) continue; if (cost < item._ivalue) { item._ivalue -= cost; SetPlrHandGoldCurs(player.InvList[i]); return 0; } cost -= item._ivalue; player.RemoveInvItem(i); i = -1; } return cost; } void DrawSelector(const Surface &out, const Rectangle &rect, const char *text, UiFlags flags) { int lineWidth = GetLineWidth(text); int x1 = rect.position.x - 20; if (HasAnyOf(flags, UiFlags::AlignCenter)) x1 += (rect.size.width - lineWidth) / 2; CelDrawTo(out, { x1, rect.position.y + 13 }, *pSPentSpn2Cels, PentSpn2Spin()); int x2 = rect.position.x + rect.size.width + 5; if (HasAnyOf(flags, UiFlags::AlignCenter)) x2 = rect.position.x + (rect.size.width - lineWidth) / 2 + lineWidth + 5; CelDrawTo(out, { x2, rect.position.y + 13 }, *pSPentSpn2Cels, PentSpn2Spin()); } } // namespace void AddStoreHoldRepair(Item *itm, int8_t i) { Item *item; int v; item = &storehold[storenumh]; storehold[storenumh] = *itm; int due = item->_iMaxDur - item->_iDurability; if (item->_iMagical != ITEM_QUALITY_NORMAL && item->_iIdentified) { v = 30 * item->_iIvalue * due / (item->_iMaxDur * 100 * 2); if (v == 0) return; } else { v = item->_ivalue * due / (item->_iMaxDur * 2); v = std::max(v, 1); } item->_iIvalue = v; item->_ivalue = v; storehidx[storenumh] = i; storenumh++; } void InitStores() { ClearSText(0, STORE_LINES); stextflag = STORE_NONE; stextsize = false; stextscrl = false; numpremium = 0; premiumlevel = 1; for (auto &premiumitem : premiumitems) premiumitem.clear(); boyitem.clear(); boylevel = 0; } void SetupTownStores() { auto &myPlayer = Players[MyPlayerId]; int l = myPlayer._pLevel / 2; if (!gbIsMultiplayer) { l = 0; for (int i = 0; i < NUMLEVELS; i++) { if (myPlayer._pLvlVisited[i]) l = i; } } l = clamp(l + 2, 6, 16); SpawnSmith(l); SpawnWitch(l); SpawnHealer(l); SpawnBoy(myPlayer._pLevel); SpawnPremium(MyPlayerId); } void FreeStoreMem() { stextflag = STORE_NONE; } void PrintSString(const Surface &out, int margin, int line, const char *text, UiFlags flags, int price) { int sx = PANEL_X + 32 + margin; if (!stextsize) { sx += 320; } const int sy = UI_OFFSET_Y + PaddingTop + stext[line].y + stext[line]._syoff; int width = stextsize ? 575 : 255; if (stextscrl && line >= 4 && line <= 20) { width -= 9; // Space for the selector } width -= margin * 2; const Rectangle rect { { sx, sy }, { width, 0 } }; DrawString(out, text, rect, flags); if (price > 0) { char valstr[32]; sprintf(valstr, "%i", price); DrawString(out, valstr, rect, flags | UiFlags::AlignRight); } if (stextsel == line) { DrawSelector(out, rect, text, flags); } } void DrawSLine(const Surface &out, int sy) { int sx = 26; int width = 587; if (!stextsize) { sx += SPANEL_WIDTH; width -= SPANEL_WIDTH; } BYTE *src = out.at(PANEL_LEFT + sx, UI_OFFSET_Y + 25); BYTE *dst = out.at(PANEL_X + sx, sy); for (int i = 0; i < 3; i++, src += out.pitch(), dst += out.pitch()) memcpy(dst, src, width); } void DrawSTextHelp() { stextsel = -1; stextsize = true; } void ClearSText(int s, int e) { for (int i = s; i < e; i++) { stext[i]._sx = 0; stext[i]._syoff = 0; stext[i]._sstr[0] = 0; stext[i].flags = UiFlags::None; stext[i]._sline = 0; stext[i]._ssel = false; stext[i]._sval = 0; } } void StartStore(talk_id s) { sbookflag = false; CloseInventory(); chrflag = false; RenderGold = false; QuestLogIsOpen = false; CloseGoldDrop(); ClearSText(0, STORE_LINES); ReleaseStoreBtn(); switch (s) { case STORE_SMITH: StartSmith(); break; case STORE_SBUY: { bool hasAnyItems = false; for (int i = 0; !smithitem[i].isEmpty(); i++) { hasAnyItems = true; break; } if (hasAnyItems) StartSmithBuy(); else { stextflag = STORE_SBUY; stextlhold = 12; StoreESC(); return; } break; } case STORE_SSELL: StartSmithSell(); break; case STORE_SREPAIR: StartSmithRepair(); break; case STORE_WITCH: StartWitch(); break; case STORE_WBUY: if (storenumh > 0) StartWitchBuy(); break; case STORE_WSELL: StartWitchSell(); break; case STORE_WRECHARGE: StartWitchRecharge(); break; case STORE_NOMONEY: StoreNoMoney(); break; case STORE_NOROOM: StoreNoRoom(); break; case STORE_CONFIRM: StoreConfirm(StoreItem); break; case STORE_BOY: StartBoy(); break; case STORE_BBOY: SStartBoyBuy(); break; case STORE_HEALER: StartHealer(); break; case STORE_STORY: StartStoryteller(); break; case STORE_HBUY: if (storenumh > 0) StartHealerBuy(); break; case STORE_SIDENTIFY: StartStorytellerIdentify(); break; case STORE_SPBUY: if (!StartSmithPremiumBuy()) return; break; case STORE_GOSSIP: StartTalk(); break; case STORE_IDSHOW: StartStorytellerIdentifyShow(StoreItem); break; case STORE_TAVERN: StartTavern(); break; case STORE_DRUNK: StartDrunk(); break; case STORE_BARMAID: StartBarmaid(); break; case STORE_NONE: break; } stextsel = -1; for (int i = 0; i < STORE_LINES; i++) { if (stext[i]._ssel) { stextsel = i; break; } } stextflag = s; } void DrawSText(const Surface &out) { if (!stextsize) DrawSTextBack(out); else DrawQTextBack(out); if (stextscrl) { switch (stextflag) { case STORE_SBUY: ScrollSmithBuy(stextsval); break; case STORE_SSELL: case STORE_SREPAIR: case STORE_WSELL: case STORE_WRECHARGE: case STORE_SIDENTIFY: ScrollSmithSell(stextsval); break; case STORE_WBUY: ScrollWitchBuy(stextsval); break; case STORE_HBUY: ScrollHealerBuy(stextsval); break; case STORE_SPBUY: ScrollSmithPremiumBuy(stextsval); break; default: break; } } CalculateLineHeights(); for (int i = 0; i < STORE_LINES; i++) { if (stext[i].IsDivider()) DrawSLine(out, UI_OFFSET_Y + PaddingTop + stext[i].y + TextHeight() / 2); if (stext[i].IsText()) PrintSString(out, stext[i]._sx, i, stext[i]._sstr, stext[i].flags, stext[i]._sval); } if (RenderGold) { PrintSString(out, 28, 1, fmt::format(_("Your gold: {:d}"), TotalPlayerGold()).c_str(), UiFlags::ColorWhitegold | UiFlags::AlignRight); } if (stextscrl) DrawSSlider(out, 4, 20); } void StoreESC() { if (qtextflag) { qtextflag = false; if (leveltype == DTYPE_TOWN) stream_stop(); return; } switch (stextflag) { case STORE_SMITH: case STORE_WITCH: case STORE_BOY: case STORE_BBOY: case STORE_HEALER: case STORE_STORY: case STORE_TAVERN: case STORE_DRUNK: case STORE_BARMAID: stextflag = STORE_NONE; break; case STORE_GOSSIP: StartStore(stextshold); stextsel = stextlhold; break; case STORE_SBUY: StartStore(STORE_SMITH); stextsel = 12; break; case STORE_SPBUY: StartStore(STORE_SMITH); stextsel = 14; break; case STORE_SSELL: StartStore(STORE_SMITH); stextsel = 16; break; case STORE_SREPAIR: StartStore(STORE_SMITH); stextsel = 18; break; case STORE_WBUY: StartStore(STORE_WITCH); stextsel = 14; break; case STORE_WSELL: StartStore(STORE_WITCH); stextsel = 16; break; case STORE_WRECHARGE: StartStore(STORE_WITCH); stextsel = 18; break; case STORE_HBUY: StartStore(STORE_HEALER); stextsel = 14; break; case STORE_SIDENTIFY: StartStore(STORE_STORY); stextsel = 14; break; case STORE_IDSHOW: StartStore(STORE_SIDENTIFY); break; case STORE_NOMONEY: case STORE_NOROOM: case STORE_CONFIRM: StartStore(stextshold); stextsel = stextlhold; stextsval = stextvhold; break; case STORE_NONE: break; } } void StoreUp() { PlaySFX(IS_TITLEMOV); if (stextsel == -1) { return; } if (stextscrl) { if (stextsel == stextup) { if (stextsval != 0) stextsval--; return; } stextsel--; while (!stext[stextsel]._ssel) { if (stextsel == 0) stextsel = STORE_LINES - 1; else stextsel--; } return; } if (stextsel == 0) stextsel = STORE_LINES - 1; else stextsel--; while (!stext[stextsel]._ssel) { if (stextsel == 0) stextsel = STORE_LINES - 1; else stextsel--; } } void StoreDown() { PlaySFX(IS_TITLEMOV); if (stextsel == -1) { return; } if (stextscrl) { if (stextsel == stextdown) { if (stextsval < stextsmax) stextsval++; return; } stextsel++; while (!stext[stextsel]._ssel) { if (stextsel == STORE_LINES - 1) stextsel = 0; else stextsel++; } return; } if (stextsel == STORE_LINES - 1) stextsel = 0; else stextsel++; while (!stext[stextsel]._ssel) { if (stextsel == STORE_LINES - 1) stextsel = 0; else stextsel++; } } void StorePrior() { PlaySFX(IS_TITLEMOV); if (stextsel != -1 && stextscrl) { if (stextsel == stextup) { stextsval = std::max(stextsval - 4, 0); } else { stextsel = stextup; } } } void StoreNext() { PlaySFX(IS_TITLEMOV); if (stextsel != -1 && stextscrl) { if (stextsel == stextdown) { if (stextsval < stextsmax) stextsval += 4; if (stextsval > stextsmax) stextsval = stextsmax; } else { stextsel = stextdown; } } } void TakePlrsMoney(int cost) { auto &myPlayer = Players[MyPlayerId]; myPlayer._pGold -= std::min(cost, myPlayer._pGold); cost = TakeGold(myPlayer, cost, true); if (cost != 0) { cost = TakeGold(myPlayer, cost, false); } Stash.gold -= cost; Stash.dirty = true; } void StoreEnter() { if (qtextflag) { qtextflag = false; if (leveltype == DTYPE_TOWN) stream_stop(); return; } PlaySFX(IS_TITLSLCT); switch (stextflag) { case STORE_SMITH: SmithEnter(); break; case STORE_SPBUY: SmithPremiumBuyEnter(); break; case STORE_SBUY: SmithBuyEnter(); break; case STORE_SSELL: SmithSellEnter(); break; case STORE_SREPAIR: SmithRepairEnter(); break; case STORE_WITCH: WitchEnter(); break; case STORE_WBUY: WitchBuyEnter(); break; case STORE_WSELL: WitchSellEnter(); break; case STORE_WRECHARGE: WitchRechargeEnter(); break; case STORE_NOMONEY: case STORE_NOROOM: StartStore(stextshold); stextsel = stextlhold; stextsval = stextvhold; break; case STORE_CONFIRM: ConfirmEnter(StoreItem); break; case STORE_BOY: BoyEnter(); break; case STORE_BBOY: BoyBuyEnter(); break; case STORE_HEALER: HealerEnter(); break; case STORE_STORY: StorytellerEnter(); break; case STORE_HBUY: HealerBuyEnter(); break; case STORE_SIDENTIFY: StorytellerIdentifyEnter(); break; case STORE_GOSSIP: TalkEnter(); break; case STORE_IDSHOW: StartStore(STORE_SIDENTIFY); break; case STORE_DRUNK: DrunkEnter(); break; case STORE_TAVERN: TavernEnter(); break; case STORE_BARMAID: BarmaidEnter(); break; case STORE_NONE: break; } } void CheckStoreBtn() { if (qtextflag) { qtextflag = false; if (leveltype == DTYPE_TOWN) stream_stop(); } else if (stextsel != -1 && MousePosition.y >= (PaddingTop + UI_OFFSET_Y) && MousePosition.y <= (320 + UI_OFFSET_Y)) { if (!stextsize) { if (MousePosition.x < 344 + PANEL_LEFT || MousePosition.x > 616 + PANEL_LEFT) return; } else { if (MousePosition.x < 24 + PANEL_LEFT || MousePosition.x > 616 + PANEL_LEFT) return; } const int relativeY = MousePosition.y - (UI_OFFSET_Y + PaddingTop); if (stextscrl && MousePosition.x > 600 + PANEL_LEFT) { // Scroll bar is always measured in terms of the small line height. int y = relativeY / SmallLineHeight; if (y == 4) { if (stextscrlubtn <= 0) { StoreUp(); stextscrlubtn = 10; } else { stextscrlubtn--; } } if (y == 20) { if (stextscrldbtn <= 0) { StoreDown(); stextscrldbtn = 10; } else { stextscrldbtn--; } } return; } int y = relativeY / LineHeight(); // Large small fonts draw beyond LineHeight. Check if the click was on the overflow text. if (IsSmallFontTall() && y > 0 && y < STORE_LINES && stext[y - 1].IsText() && !stext[y].IsText() && relativeY < stext[y - 1].y + LargeTextHeight) { --y; } if (y >= 5) { if (y >= BackButtonLine() + 1) y = BackButtonLine(); if (stextscrl && y <= 20 && !stext[y]._ssel) { if (stext[y - 2]._ssel) { y -= 2; } else if (stext[y - 1]._ssel) { y--; } } if (stext[y]._ssel || (stextscrl && y == BackButtonLine())) { stextsel = y; StoreEnter(); } } } } void ReleaseStoreBtn() { stextscrlubtn = -1; stextscrldbtn = -1; } } // namespace devilution
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/camera/drivers/hw_accel/ge2d/ge2d.h" #include <fuchsia/hardware/amlogiccanvas/cpp/banjo.h> #include <lib/ddk/debug.h> #include <lib/ddk/driver.h> #include <lib/ddk/trace/event.h> #include <lib/image-format/image_format.h> #include <lib/syslog/cpp/macros.h> #include <stdint.h> #include <zircon/assert.h> #include <zircon/threads.h> #include <zircon/types.h> #include <memory> #include <ddktl/device.h> #include <fbl/auto_lock.h> #include "src/camera/drivers/hw_accel/ge2d/ge2d_regs.h" namespace ge2d { namespace { constexpr uint32_t kGe2d = 0; constexpr auto kTag = "ge2d"; } // namespace zx_status_t Ge2dDevice::Ge2dInitTaskResize( const buffer_collection_info_2_t* input_buffer_collection, const buffer_collection_info_2_t* output_buffer_collection, const resize_info_t* info, const image_format_2_t* input_image_format, const image_format_2_t* output_image_format_table_list, size_t output_image_format_table_count, uint32_t output_image_format_index, const hw_accel_frame_callback_t* frame_callback, const hw_accel_res_change_callback_t* res_callback, const hw_accel_remove_task_callback_t* task_remove_callback, uint32_t* out_task_index) { if (out_task_index == nullptr) { return ZX_ERR_INVALID_ARGS; } auto task = std::make_unique<Ge2dTask>(); zx_status_t status = task->InitResize( input_buffer_collection, output_buffer_collection, info, input_image_format, output_image_format_table_list, output_image_format_table_count, output_image_format_index, frame_callback, res_callback, task_remove_callback, bti_, canvas_); if (status != ZX_OK) { FX_PLOGST(ERROR, kTag, status) << "Task Creation Failed"; return status; } fbl::AutoLock al(&interface_lock_); // Put an entry in the hashmap. task_map_[next_task_index_] = std::move(task); *out_task_index = next_task_index_; next_task_index_++; return status; } zx_status_t Ge2dDevice::Ge2dInitTaskWaterMark( const buffer_collection_info_2_t* input_buffer_collection, const buffer_collection_info_2_t* output_buffer_collection, const water_mark_info_t* info_list, size_t info_count, const image_format_2_t* image_format_table_list, size_t image_format_table_count, uint32_t image_format_index, const hw_accel_frame_callback_t* frame_callback, const hw_accel_res_change_callback_t* res_callback, const hw_accel_remove_task_callback_t* task_remove_callback, uint32_t* out_task_index) { if (out_task_index == nullptr) { return ZX_ERR_INVALID_ARGS; } if (info_count != image_format_table_count) return ZX_ERR_INVALID_ARGS; auto task = std::make_unique<Ge2dTask>(); zx_status_t status = task->InitWatermark(input_buffer_collection, output_buffer_collection, info_list, image_format_table_list, image_format_table_count, image_format_index, frame_callback, res_callback, task_remove_callback, bti_, canvas_); if (status != ZX_OK) { FX_PLOGST(ERROR, kTag, status) << "Task Creation Failed"; return status; } fbl::AutoLock al(&interface_lock_); // Put an entry in the hashmap. task_map_[next_task_index_] = std::move(task); *out_task_index = next_task_index_; next_task_index_++; return status; } zx_status_t Ge2dDevice::Ge2dInitTaskInPlaceWaterMark( const buffer_collection_info_2_t* buffer_collection, const water_mark_info_t* info_list, size_t info_count, const image_format_2_t* image_format_table_list, size_t image_format_table_count, uint32_t image_format_index, const hw_accel_frame_callback_t* frame_callback, const hw_accel_res_change_callback_t* res_callback, const hw_accel_remove_task_callback_t* task_remove_callback, uint32_t* out_task_index) { if (out_task_index == nullptr) { return ZX_ERR_INVALID_ARGS; } if (info_count != image_format_table_count) return ZX_ERR_INVALID_ARGS; auto task = std::make_unique<Ge2dTask>(); zx_status_t status = task->InitInPlaceWatermark( buffer_collection, info_list, image_format_table_list, image_format_table_count, image_format_index, frame_callback, res_callback, task_remove_callback, bti_, canvas_); if (status != ZX_OK) { FX_PLOGST(ERROR, kTag, status) << "Task Creation Failed"; return status; } fbl::AutoLock al(&interface_lock_); // Put an entry in the hashmap. task_map_[next_task_index_] = std::move(task); *out_task_index = next_task_index_; next_task_index_++; return status; } void Ge2dDevice::Ge2dRemoveTask(uint32_t task_index) { fbl::AutoLock al(&interface_lock_); // Find the entry in hashmap. auto task_entry = task_map_.find(task_index); if (task_entry == task_map_.end()) { // Release lock so death test doesn't hang. al.release(); ZX_ASSERT(false); } TaskInfo info; info.op = GE2D_OP_REMOVETASK; info.task = task_entry->second.get(); info.task_index = task_index; // Put the task on the queue. fbl::AutoLock lock(&lock_); processing_queue_.push_front(info); frame_processing_signal_.Signal(); } void Ge2dDevice::Ge2dReleaseFrame(uint32_t task_index, uint32_t buffer_index) { fbl::AutoLock al(&interface_lock_); // Find the entry in hashmap. auto task_entry = task_map_.find(task_index); ZX_ASSERT(task_entry != task_map_.end()); auto task = task_entry->second.get(); ZX_ASSERT(ZX_OK == task->ReleaseOutputBuffer(buffer_index)); } zx_status_t Ge2dDevice::Ge2dSetOutputResolution(uint32_t task_index, uint32_t new_output_image_format_index) { fbl::AutoLock al(&interface_lock_); // Find the entry in hashmap. auto task_entry = task_map_.find(task_index); if (task_entry == task_map_.end()) { return ZX_ERR_INVALID_ARGS; } if (task_entry->second->Ge2dTaskType() != Ge2dTask::GE2D_RESIZE) { return ZX_ERR_INVALID_ARGS; } // Validate new image format index|. if (!task_entry->second->IsOutputFormatIndexValid(new_output_image_format_index)) { return ZX_ERR_INVALID_ARGS; } TaskInfo info; info.op = GE2D_OP_SETOUTPUTRES; info.task = task_entry->second.get(); info.index = new_output_image_format_index; // Put the task on queue. fbl::AutoLock lock(&lock_); processing_queue_.push_front(info); frame_processing_signal_.Signal(); return ZX_OK; } zx_status_t Ge2dDevice::Ge2dSetInputAndOutputResolution(uint32_t task_index, uint32_t new_image_format_index) { fbl::AutoLock al(&interface_lock_); // Find the entry in hashmap. auto task_entry = task_map_.find(task_index); if (task_entry == task_map_.end()) { return ZX_ERR_INVALID_ARGS; } if (task_entry->second->Ge2dTaskType() != Ge2dTask::GE2D_WATERMARK && task_entry->second->Ge2dTaskType() != Ge2dTask::GE2D_IN_PLACE_WATERMARK) { return ZX_ERR_INVALID_ARGS; } // Validate new image format index|. if (!task_entry->second->IsInputFormatIndexValid(new_image_format_index)) { return ZX_ERR_INVALID_ARGS; } if (task_entry->second->has_output_images() && !task_entry->second->IsOutputFormatIndexValid(new_image_format_index)) { return ZX_ERR_INVALID_ARGS; } TaskInfo info; info.op = GE2D_OP_SETINPUTOUTPUTRES; info.task = task_entry->second.get(); info.index = new_image_format_index; // Put the task on queue. fbl::AutoLock lock(&lock_); processing_queue_.push_front(info); frame_processing_signal_.Signal(); return ZX_OK; } zx_status_t Ge2dDevice::Ge2dProcessFrame(uint32_t task_index, uint32_t input_buffer_index, uint64_t capture_timestamp) { TRACE_DURATION("camera", "Ge2dDevice::Ge2dProcessFrame"); fbl::AutoLock al(&interface_lock_); // Find the entry in hashmap. auto task_entry = task_map_.find(task_index); if (task_entry == task_map_.end()) { return ZX_ERR_INVALID_ARGS; } // Validate |input_buffer_index|. if (!task_entry->second->IsInputBufferIndexValid(input_buffer_index)) { return ZX_ERR_INVALID_ARGS; } TaskInfo info; info.op = GE2D_OP_FRAME; info.task = task_entry->second.get(); info.index = input_buffer_index; info.capture_timestamp = capture_timestamp; // Put the task on queue. TRACE_FLOW_BEGIN("camera", "ge2d_process_frame", info.index); fbl::AutoLock lock(&lock_); processing_queue_.push_front(info); frame_processing_signal_.Signal(); return ZX_OK; } void Ge2dDevice::Ge2dSetCropRect(uint32_t task_index, const rect_t* crop) { fbl::AutoLock al(&interface_lock_); // Find the entry in hashmap. auto task_entry = task_map_.find(task_index); if (task_entry == task_map_.end()) { return; } if (task_entry->second->Ge2dTaskType() != Ge2dTask::GE2D_RESIZE) return; TaskInfo info; info.op = GE2D_OP_SETCROPRECT; info.task = task_entry->second.get(); info.index = 0; info.crop_rect = *crop; // Put the task on queue. fbl::AutoLock lock(&lock_); processing_queue_.push_front(info); frame_processing_signal_.Signal(); } void Ge2dDevice::InitializeScalingCoefficients() { // 33x4 FIR coefficients to use. First takes 100% of pixel[1], while the last takes 50% of // pixel[1] and pixel[2]. constexpr uint32_t kBilinearCoefficients[] = { 0x00800000, 0x007e0200, 0x007c0400, 0x007a0600, 0x00780800, 0x00760a00, 0x00740c00, 0x00720e00, 0x00701000, 0x006e1200, 0x006c1400, 0x006a1600, 0x00681800, 0x00661a00, 0x00641c00, 0x00621e00, 0x00602000, 0x005e2200, 0x005c2400, 0x005a2600, 0x00582800, 0x00562a00, 0x00542c00, 0x00522e00, 0x00503000, 0x004e3200, 0x004c3400, 0x004a3600, 0x00483800, 0x00463a00, 0x00443c00, 0x00423e00, 0x00404000}; // Vertical scaler autoincrementing write ScaleCoefIdx::Get().FromValue(0).WriteTo(&ge2d_mmio_); for (uint32_t value : kBilinearCoefficients) { ScaleCoef::Get().FromValue(value).WriteTo(&ge2d_mmio_); } // Horizontal scaler autoincrementing write ScaleCoefIdx::Get().FromValue(0).set_horizontal(1).WriteTo(&ge2d_mmio_); for (uint32_t value : kBilinearCoefficients) { ScaleCoef::Get().FromValue(value).WriteTo(&ge2d_mmio_); } } void Ge2dDevice::ProcessTask(TaskInfo& info) { TRACE_DURATION("camera", "Ge2dDevice::ProcessTask"); TRACE_FLOW_END("camera", "ge2d_process_frame", info.index); switch (info.op) { case GE2D_OP_SETOUTPUTRES: case GE2D_OP_SETINPUTOUTPUTRES: return ProcessChangeResolution(info); case GE2D_OP_SETCROPRECT: return ProcessSetCropRect(info); case GE2D_OP_FRAME: return ProcessFrame(info); case GE2D_OP_REMOVETASK: return ProcessRemoveTask(info); } } void Ge2dDevice::ProcessSetCropRect(TaskInfo& info) { info.task->SetCropRect(info.crop_rect); } void Ge2dDevice::ProcessChangeResolution(TaskInfo& info) { auto task = info.task; if (task->has_output_images()) { // This has to free and reallocate the output buffer canvas ids. task->Ge2dChangeOutputRes(info.index); } if (info.op == GE2D_OP_SETINPUTOUTPUTRES) { // This has to free and reallocate the input buffer canvas ids. task->Ge2dChangeInputRes(info.index); } frame_available_info f_info; f_info.frame_status = FRAME_STATUS_OK; f_info.metadata.timestamp = static_cast<uint64_t>(zx_clock_get_monotonic()); f_info.metadata.image_format_index = info.index; return task->ResolutionChangeCallback(&f_info); } // Floors. static uint32_t ConvertToFixedPoint24(double input) { return static_cast<uint32_t>((1 << 24) * input); } static void CalculateInitialPhase(uint32_t input_dim, uint32_t output_dim, uint32_t* phase_out, uint32_t* repeat_out) { // Linux uses a multiplied-by-10 fixed-point, but this seems simpler and more precise. double rate_ratio = static_cast<double>(output_dim) / input_dim; if (rate_ratio == 1.0) { *phase_out = 0; *repeat_out = 0; } else { // We subtract 0.5 here because the pixel value itself is at phase 0, not 0.5. double pixel_initial_phase = 0.5 / rate_ratio - 0.5; // We need to decide how to fill in the FIR filter initially. if (pixel_initial_phase >= 0) { // When scaling down the first output pixel center is after the first input pixel center, so // we set repeat = 1 so the inputs looks like (image[0], image[0], image[1], image[2]) and we // interpolate between image[0] and image[1]. *repeat_out = 1; } else { // When scaling up the first output pixel center is before the first input pixel center, so we // set repeat = 2 and the input looks like (image[0], image[0], image[0], image[1]) so the // first output must be image[0] (due to the bilinear filter coefficients we're using). *repeat_out = 2; // Increase initial phase by 1 to compensate. pixel_initial_phase++; } *phase_out = ConvertToFixedPoint24(pixel_initial_phase); } } void Ge2dDevice::InitializeScaler(uint32_t input_width, uint32_t input_height, uint32_t output_width, uint32_t output_height) { bool horizontal_scaling = (input_width != output_width); bool vertical_scaling = (input_height != output_height); InitializeScalingCoefficients(); bool use_preh_scaler = input_width > output_width * 2; bool use_prev_scaler = input_height > output_height * 2; // Prescaler seems to divide size by 2. uint32_t scaler_input_width = use_preh_scaler ? ((input_width + 1) / 2) : input_width; uint32_t scaler_input_height = use_prev_scaler ? ((input_height + 1) / 2) : input_height; // The scaler starts at an initial phase value, and for every output pixel increments it by a // step. Integer values (in 5.24 fixed-point) are the input pixel values themselves (starting at // 0). The scaler is a polyphase scaler, so the phase picks the FIR coefficients to use (from the // table above). For bilinear filtering, a phase of 0 takes all its input from pixel[1], and 1 // would take it all from pixel[2]. constexpr uint32_t kFixedPoint = 24; uint32_t hsc_phase_step = ConvertToFixedPoint24(static_cast<double>(scaler_input_width) / output_width); uint32_t vsc_phase_step = ConvertToFixedPoint24(static_cast<double>(scaler_input_height) / output_height); // Horizontal scaler dividing provides more efficiency (somehow). It seems like it allows // calculating phases at larger blocks. // The dividing length is roughly 124 * (output_width / input_width). uint32_t hsc_dividing_length = ConvertToFixedPoint24(124) / hsc_phase_step; uint32_t hsc_rounded_step = hsc_dividing_length * hsc_phase_step; uint32_t hsc_advance_num = hsc_rounded_step >> kFixedPoint; uint32_t hsc_advance_phase = hsc_rounded_step & ((1 << kFixedPoint) - 1); uint32_t horizontal_initial_phase, horizontal_repeat; uint32_t vertical_initial_phase, vertical_repeat; // The linux driver uses |input_width| and |input_height| here, but that seems incorrect. CalculateInitialPhase(scaler_input_width, output_width, &horizontal_initial_phase, &horizontal_repeat); CalculateInitialPhase(scaler_input_height, output_height, &vertical_initial_phase, &vertical_repeat); ScMiscCtrl::Get() .ReadFrom(&ge2d_mmio_) .set_hsc_div_en(horizontal_scaling) .set_hsc_dividing_length(hsc_dividing_length) .set_pre_hsc_enable(use_preh_scaler) .set_pre_vsc_enable(use_prev_scaler) .set_vsc_enable(vertical_scaling) .set_hsc_enable(horizontal_scaling) .set_hsc_rpt_ctrl(1) .set_vsc_rpt_ctrl(1) .WriteTo(&ge2d_mmio_); HscStartPhaseStep::Get().FromValue(0).set_phase_step(hsc_phase_step).WriteTo(&ge2d_mmio_); HscAdvCtrl::Get() .FromValue(0) .set_advance_num(hsc_advance_num & 0xff) .set_advance_phase(hsc_advance_phase) .WriteTo(&ge2d_mmio_); // We clamp the initial phases, because that's what the hardware // supports. This can mess up scaling down to <= 1/3, though the prescaler can // help reduce how often that's a problem. The linux driver wraps these // values, which seems worse. HscIniCtrl::Get() .FromValue(0) .set_horizontal_repeat_p0(horizontal_repeat) .set_horizontal_advance_num_upper(hsc_advance_num >> 8) .set_horizontal_initial_phase(std::min(horizontal_initial_phase, 0xffffffu)) .WriteTo(&ge2d_mmio_); VscStartPhaseStep::Get().FromValue(0).set_phase_step(vsc_phase_step).WriteTo(&ge2d_mmio_); VscIniCtrl::Get() .FromValue(0) .set_vertical_repeat_p0(vertical_repeat) .set_vertical_initial_phase(std::min(vertical_initial_phase, 0xffffffu)) .WriteTo(&ge2d_mmio_); // Leave horizontal and vertical phase slopes set to 0. } void Ge2dDevice::SetupInputOutputFormats(bool scaling_enabled, const image_format_2_t& input_format, const image_format_2_t& output_format, const image_format_2_t& src2_format) { bool is_src_nv12 = input_format.pixel_format.type == fuchsia_sysmem_PixelFormatType_NV12; bool is_dst_nv12 = output_format.pixel_format.type == fuchsia_sysmem_PixelFormatType_NV12; // When using NV12 output DST1 gets Y and DST2 gets CbCr. GenCtrl0::Get() .FromValue(0) .set_src1_separate_enable(is_src_nv12) .set_x_yc_ratio(1) .set_y_yc_ratio(1) .WriteTo(&ge2d_mmio_); GenCtrl2::Get() .FromValue(0) .set_dst_little_endian(0) // endianness conversion happens in canvas .set_dst1_color_map(is_dst_nv12 ? 0 : GenCtrl2::kColorMap32RGBA8888) .set_dst1_format(is_dst_nv12 ? GenCtrl2::kFormat8Bit : GenCtrl2::kFormat32Bit) .set_src1_little_endian(0) // endianness conversion happens in canvas .set_src1_color_map(is_src_nv12 ? GenCtrl2::kColorMap24NV12 : GenCtrl2::kColorMap32RGBA8888) .set_src1_format(is_src_nv12 ? GenCtrl2::kFormat24Bit : GenCtrl2::kFormat32Bit) .set_src1_color_expand_mode(1) .set_src2_little_endian(0) // endianness conversion happens in canvas .set_src2_color_map(GenCtrl2::kColorMap32RGBA8888) .set_src2_format(GenCtrl2::kFormat32Bit) .WriteTo(&ge2d_mmio_); GenCtrl3::Get() .FromValue(0) .set_dst2_color_map(GenCtrl2::kColorMap16CbCr) .set_dst2_format(GenCtrl2::kFormat16Bit) .set_dst2_x_discard_mode(GenCtrl3::kDiscardModeOdd) .set_dst2_y_discard_mode(GenCtrl3::kDiscardModeOdd) .set_dst2_enable(is_dst_nv12) .set_dst1_enable(1) .WriteTo(&ge2d_mmio_); if (is_src_nv12 && !is_dst_nv12) { // YCbCr BT.601 studio swing to RGB. Outputs of matrix multiplication seem // to be divided by 1024. MatrixCoef00_01::Get().FromValue(0).set_coef00(0x4a8).WriteTo(&ge2d_mmio_); MatrixCoef02_10::Get().FromValue(0).set_coef02(0x662).set_coef10(0x4a8).WriteTo(&ge2d_mmio_); MatrixCoef11_12::Get().FromValue(0).set_coef11(0x1e6f).set_coef12(0x1cbf).WriteTo(&ge2d_mmio_); MatrixCoef20_21::Get().FromValue(0).set_coef20(0x4a8).set_coef21(0x811).WriteTo(&ge2d_mmio_); MatrixCoef22Ctrl::Get() .FromValue(0) .set_saturation_enable(true) .set_matrix_enable(true) .WriteTo(&ge2d_mmio_); MatrixPreOffset::Get() .FromValue(0) .set_offset0(0x1f0) .set_offset1(0x180) .set_offset2(0x180) .WriteTo(&ge2d_mmio_); MatrixOffset::Get().FromValue(0).set_offset0(0).set_offset1(0).set_offset2(0).WriteTo( &ge2d_mmio_); } else if (!is_src_nv12 && is_dst_nv12) { // RGB to BT.601 studio swing. Outputs of matrix multiplication seem // to be divided by 1024. MatrixCoef00_01::Get().FromValue(0).set_coef00(0x107).set_coef01(0x204).WriteTo(&ge2d_mmio_); MatrixCoef02_10::Get().FromValue(0).set_coef02(0x64).set_coef10(0x1f68).WriteTo(&ge2d_mmio_); MatrixCoef11_12::Get().FromValue(0).set_coef11(0x1ed6).set_coef12(0x1c2).WriteTo(&ge2d_mmio_); MatrixCoef20_21::Get().FromValue(0).set_coef20(0x1c2).set_coef21(0x1e87).WriteTo(&ge2d_mmio_); MatrixCoef22Ctrl::Get() .FromValue(0) .set_coef22(0x1fb7) .set_saturation_enable(false) .set_matrix_enable(true) .WriteTo(&ge2d_mmio_); MatrixPreOffset::Get().FromValue(0).set_offset0(0).set_offset1(0).set_offset2(0).WriteTo( &ge2d_mmio_); MatrixOffset::Get().FromValue(0).set_offset0(16).set_offset1(128).set_offset2(128).WriteTo( &ge2d_mmio_); } else { // No colorspace conversion. MatrixCoef22Ctrl::Get().FromValue(0).set_matrix_enable(false).WriteTo(&ge2d_mmio_); } // To match the linux driver we repeat the UV planes instead of interpolating if we're not // scaling the output. This is arguably incorrect, depending on chroma siting. Src1FmtCtrl::Get() .FromValue(0) .set_horizontal_enable(is_src_nv12) .set_vertical_enable(is_src_nv12) .set_y_chroma_phase(0x4c) .set_x_chroma_phase(0x8) .set_horizontal_repeat(!scaling_enabled) .set_vertical_repeat(!scaling_enabled) .WriteTo(&ge2d_mmio_); } void Ge2dDevice::SetBlending(bool enable) { if (enable) { // Blend src2 (non-premultiplied) on top of src1. The hardware considers // SRC1 to be source and SRC2 to be dest. AluOpCtrl::Get() .ReadFrom(&ge2d_mmio_) .set_src2_cmult_ad(0) .set_src1_color_mult(AluOpCtrl::kColorMultNone) .set_src2_color_mult(AluOpCtrl::kColorMultNonPremult) .set_blending_mode(AluOpCtrl::kBlendingModeAdd) .set_source_factor(AluOpCtrl::kBlendingFactorOneMinusDstAlpha) .set_logic_operation(AluOpCtrl::kBlendingFactorOne) .set_alpha_blending_mode(AluOpCtrl::kBlendingModeAdd) .set_alpha_source_factor(AluOpCtrl::kBlendingFactorZero) .set_alpha_logic_operation(AluOpCtrl::kBlendingFactorOne) .WriteTo(&ge2d_mmio_); } else { // Copy src1 color to output, but set alpha to 0xff. AluOpCtrl::Get() .ReadFrom(&ge2d_mmio_) .set_src1_color_mult(AluOpCtrl::kColorMultNone) .set_blending_mode(AluOpCtrl::kBlendingModeLogicOp) .set_source_factor(AluOpCtrl::kBlendingFactorOne) .set_logic_operation(AluOpCtrl::kLogicOperationCopy) .set_alpha_blending_mode(AluOpCtrl::kBlendingModeLogicOp) .set_alpha_logic_operation(AluOpCtrl::kLogicOperationSet) .WriteTo(&ge2d_mmio_); } AluConstColor::Get().FromValue(0).set_a(0xff).WriteTo(&ge2d_mmio_); GenCtrl1::Get().ReadFrom(&ge2d_mmio_).set_global_alpha(0xff).WriteTo(&ge2d_mmio_); } void Ge2dDevice::SetInputRect(const rect_t& rect) { uint32_t input_x_start = rect.x; uint32_t input_x_end = rect.x + rect.width - 1; uint32_t input_y_start = rect.y; uint32_t input_y_end = rect.y + rect.height - 1; Src1ClipXStartEnd::Get() .FromValue(0) .set_end(input_x_end) .set_start(input_x_start) .WriteTo(&ge2d_mmio_); // The linux driver does Src1XStartEnd.set_start_extra(2).set_end_extra(3) but that seems to cause // the first columns's chroma to be duplicated. Src1XStartEnd::Get() .FromValue(0) .set_end(input_x_end) .set_start(input_x_start) .WriteTo(&ge2d_mmio_); Src1ClipYStartEnd::Get() .FromValue(0) .set_end(input_y_end) .set_start(input_y_start) .WriteTo(&ge2d_mmio_); // The linux driver does Src1YStartEnd.set_start_extra(2) but that seems to cause the first row's // chroma to be duplicated. Src1YStartEnd::Get() .FromValue(0) .set_end(input_y_end) .set_start(input_y_start) .set_end_extra(3) .WriteTo(&ge2d_mmio_); } void Ge2dDevice::SetSrc2InputRect(const rect_t& rect) { uint32_t input_x_start = rect.x; uint32_t input_x_end = rect.x + rect.width - 1; uint32_t input_y_start = rect.y; uint32_t input_y_end = rect.y + rect.height - 1; Src2ClipXStartEnd::Get() .FromValue(0) .set_end(input_x_end) .set_start(input_x_start) .WriteTo(&ge2d_mmio_); Src2XStartEnd::Get() .FromValue(0) .set_end(input_x_end) .set_start(input_x_start) .WriteTo(&ge2d_mmio_); Src2ClipYStartEnd::Get() .FromValue(0) .set_end(input_y_end) .set_start(input_y_start) .WriteTo(&ge2d_mmio_); Src2YStartEnd::Get() .FromValue(0) .set_end(input_y_end) .set_start(input_y_start) .WriteTo(&ge2d_mmio_); } void Ge2dDevice::SetOutputRect(const rect_t& rect) { uint32_t output_x_start = rect.x; uint32_t output_x_end = rect.x + rect.width - 1; uint32_t output_y_start = rect.y; uint32_t output_y_end = rect.y + rect.height - 1; DstClipXStartEnd::Get() .FromValue(0) .set_end(output_x_end) .set_start(output_x_start) .WriteTo(&ge2d_mmio_); DstXStartEnd::Get() .FromValue(0) .set_end(output_x_end) .set_start(output_x_start) .WriteTo(&ge2d_mmio_); DstClipYStartEnd::Get() .FromValue(0) .set_end(output_y_end) .set_start(output_y_start) .WriteTo(&ge2d_mmio_); DstYStartEnd::Get() .FromValue(0) .set_end(output_y_end) .set_start(output_y_start) .WriteTo(&ge2d_mmio_); } void Ge2dDevice::SetRects(const rect_t& input_rect, const rect_t& output_rect) { InitializeScaler(input_rect.width, input_rect.height, output_rect.width, output_rect.height); SetInputRect(input_rect); SetOutputRect(output_rect); } void Ge2dDevice::ProcessAndWaitForIdle() { TRACE_DURATION("camera", "Ge2dDevice::ProcessAndWaitForIdle"); CmdCtrl::Get().FromValue(0).set_cmd_wr(1).WriteTo(&ge2d_mmio_); zx_port_packet_t packet; ZX_ASSERT(ZX_OK == WaitForInterrupt(&packet)); if (packet.key == kPortKeyIrqMsg) { ZX_ASSERT(ge2d_irq_.ack() == ZX_OK); } ZX_ASSERT(!Status0::Get().ReadFrom(&ge2d_mmio_).busy()); } static rect_t FullImageRect(const image_format_2_t& format) { return { .x = 0, .y = 0, .width = format.coded_width, .height = format.coded_height, }; } void Ge2dDevice::SetSrc1Input(const image_canvas_id_t& canvas) { Src1Canvas::Get() .FromValue(0) .set_y(canvas.canvas_idx[kYComponent].id()) .set_u(canvas.canvas_idx[kUVComponent].id()) .set_v(canvas.canvas_idx[kUVComponent].id()) .WriteTo(&ge2d_mmio_); } void Ge2dDevice::SetSrc2Input(const image_canvas_id_t& canvas) { // Src2 doesn't support multiplanar images. ZX_ASSERT(!canvas.canvas_idx[kUVComponent].valid()); ZX_ASSERT(canvas.canvas_idx[kYComponent].valid()); Src2DstCanvas::Get() .ReadFrom(&ge2d_mmio_) .set_src2(canvas.canvas_idx[kYComponent].id()) .WriteTo(&ge2d_mmio_); } void Ge2dDevice::SetDstOutput(const image_canvas_id_t& canvas) { Src2DstCanvas::Get() .ReadFrom(&ge2d_mmio_) .set_dst1(canvas.canvas_idx[kYComponent].id()) .set_dst2(canvas.canvas_idx[kUVComponent].id()) .WriteTo(&ge2d_mmio_); } void Ge2dDevice::ProcessResizeTask(Ge2dTask* task, uint32_t input_buffer_index, const fzl::VmoPool::Buffer& output_buffer) { TRACE_DURATION("camera", "Ge2dDevice::ProcessResizeTask"); image_format_2_t input_format = task->input_format(); image_format_2_t output_format = task->output_format(); rect_t output_rect = FullImageRect(output_format); resize_info_t resize_info = task->resize_info(); bool scaling_enabled = (resize_info.crop.width != output_format.coded_width) || (resize_info.crop.height != output_format.coded_height); SetRects(resize_info.crop, output_rect); SetupInputOutputFormats(scaling_enabled, input_format, output_format); SetBlending(false); SetSrc1Input(task->GetInputCanvasIds(input_buffer_index)); SetDstOutput(task->GetOutputCanvasIds(output_buffer.vmo_handle())); ProcessAndWaitForIdle(); } void Ge2dDevice::ProcessWatermarkTask(Ge2dTask* task, uint32_t input_buffer_index, const fzl::VmoPool::Buffer& output_buffer) { TRACE_DURATION("camera", "Ge2dDevice::ProcessWatermarkTask"); image_format_2_t input_format = task->input_format(); image_format_2_t output_format = task->output_format(); rect_t output_rect = FullImageRect(output_format); image_format_2_t watermark_format = task->WatermarkFormat(); rect_t input_rect = { .x = task->watermark_loc_x(), .y = task->watermark_loc_y(), .width = watermark_format.coded_width, .height = watermark_format.coded_height, }; rect_t watermark_origin_rect = FullImageRect(watermark_format); auto& input_ids = task->GetInputCanvasIds(input_buffer_index); auto& output_canvas = task->GetOutputCanvasIds(output_buffer.vmo_handle()); // Copy entire input into output, unmodified. SetRects(output_rect, output_rect); SetupInputOutputFormats(/*scaling_enabled=*/false, input_format, output_format); SetSrc1Input(input_ids); SetDstOutput(output_canvas); SetBlending(false); ProcessAndWaitForIdle(); // Blend portion of input with watermark into temporary image (does colorspace conversion). SetRects(input_rect, watermark_origin_rect); SetSrc2InputRect(watermark_origin_rect); SetBlending(true); SetupInputOutputFormats(/*scaling_enabled=*/false, input_format, watermark_format); SetSrc1Input(input_ids); SetSrc2Input(task->watermark_input_canvas()); auto& intermediate_canvas = task->watermark_blended_canvas(); SetDstOutput(intermediate_canvas); ProcessAndWaitForIdle(); // Copy from temporary image to correct region of output (does colorspace conversion). SetRects(watermark_origin_rect, input_rect); SetBlending(false); SetupInputOutputFormats(/*scaling_enabled=*/false, watermark_format, output_format); SetSrc1Input(intermediate_canvas); SetDstOutput(output_canvas); ProcessAndWaitForIdle(); } void Ge2dDevice::ProcessInPlaceWatermarkTask(Ge2dTask* task, uint32_t input_buffer_index) { TRACE_DURATION("camera", "Ge2dDevice::ProcessInPlaceWatermarkTask"); image_format_2_t input_format = task->input_format(); image_format_2_t output_format = input_format; image_format_2_t watermark_format = task->WatermarkFormat(); rect_t input_rect = { .x = task->watermark_loc_x(), .y = task->watermark_loc_y(), .width = watermark_format.coded_width, .height = watermark_format.coded_height, }; rect_t watermark_origin_rect = FullImageRect(watermark_format); auto& input_ids = task->GetInputCanvasIds(input_buffer_index); auto& output_canvas = input_ids; // Blend portion of input with watermark into temporary image (does colorspace conversion). SetRects(input_rect, watermark_origin_rect); SetSrc2InputRect(watermark_origin_rect); SetBlending(true); SetupInputOutputFormats(/*scaling_enabled=*/false, input_format, watermark_format); SetSrc1Input(input_ids); SetSrc2Input(task->watermark_input_canvas()); auto& intermediate_canvas = task->watermark_blended_canvas(); SetDstOutput(intermediate_canvas); ProcessAndWaitForIdle(); // Copy from temporary image to correct region of output (does colorspace conversion). SetRects(watermark_origin_rect, input_rect); SetBlending(false); SetupInputOutputFormats(/*scaling_enabled=*/false, watermark_format, output_format); SetSrc1Input(intermediate_canvas); SetDstOutput(output_canvas); ProcessAndWaitForIdle(); } void Ge2dDevice::ProcessFrame(TaskInfo& info) { TRACE_DURATION("camera", "Ge2dDevice::ProcessFrame"); auto task = info.task; auto input_buffer_index = info.index; if (task->Ge2dTaskType() == Ge2dTask::GE2D_IN_PLACE_WATERMARK) { ProcessInPlaceWatermarkTask(task, input_buffer_index); // Invoke the callback function and tell about the output buffer index // which is ready to be used. frame_available_info f_info; f_info.frame_status = FRAME_STATUS_OK; f_info.buffer_id = input_buffer_index; f_info.metadata.timestamp = static_cast<uint64_t>(zx_clock_get_monotonic()); f_info.metadata.image_format_index = task->input_format_index(); f_info.metadata.input_buffer_index = input_buffer_index; f_info.metadata.capture_timestamp = info.capture_timestamp; task->FrameReadyCallback(&f_info); return; } ZX_DEBUG_ASSERT(task->has_output_images()); auto output_buffer = task->WriteLockOutputBuffer(); if (!output_buffer) { frame_available_info f_info; f_info.frame_status = FRAME_STATUS_ERROR_FRAME; f_info.buffer_id = 0; f_info.metadata.timestamp = static_cast<uint64_t>(zx_clock_get_monotonic()); f_info.metadata.image_format_index = task->output_format_index(); f_info.metadata.input_buffer_index = input_buffer_index; f_info.metadata.capture_timestamp = info.capture_timestamp; task->FrameReadyCallback(&f_info); return; } if (task->Ge2dTaskType() == Ge2dTask::GE2D_RESIZE) { ProcessResizeTask(task, input_buffer_index, *output_buffer); } else { ZX_DEBUG_ASSERT(task->Ge2dTaskType() == Ge2dTask::GE2D_WATERMARK); ProcessWatermarkTask(task, input_buffer_index, *output_buffer); } // Invoke the callback function and tell about the output buffer index // which is ready to be used. frame_available_info f_info; f_info.frame_status = FRAME_STATUS_OK; f_info.buffer_id = output_buffer->ReleaseWriteLockAndGetIndex(); f_info.metadata.timestamp = static_cast<uint64_t>(zx_clock_get_monotonic()); f_info.metadata.image_format_index = task->output_format_index(); f_info.metadata.input_buffer_index = input_buffer_index; f_info.metadata.capture_timestamp = info.capture_timestamp; task->FrameReadyCallback(&f_info); } void Ge2dDevice::ProcessRemoveTask(TaskInfo& info) { fbl::AutoLock al(&interface_lock_); auto task = info.task; auto task_index = info.task_index; // Find the entry in hashmap. auto task_entry = task_map_.find(task_index); if (task_entry == task_map_.end()) { task->RemoveTaskCallback(TASK_REMOVE_STATUS_ERROR_INVALID); return; } task->RemoveTaskCallback(TASK_REMOVE_STATUS_OK); // Remove map entry. task_map_.erase(task_entry); } int Ge2dDevice::FrameProcessingThread() { FX_LOGST(TRACE, kTag) << "start"; for (;;) { fbl::AutoLock al(&lock_); while (processing_queue_.empty() && !shutdown_) { frame_processing_signal_.Wait(&lock_); } if (shutdown_) { break; } auto info = processing_queue_.back(); processing_queue_.pop_back(); al.release(); ProcessTask(info); } return ZX_OK; } zx_status_t Ge2dDevice::StartThread() { return thrd_status_to_zx_status(thrd_create_with_name( &processing_thread_, [](void* arg) -> int { return reinterpret_cast<Ge2dDevice*>(arg)->FrameProcessingThread(); }, this, "ge2d-processing-thread")); } zx_status_t Ge2dDevice::StopThread() { // Signal the worker thread and wait for it to terminate. { fbl::AutoLock al(&lock_); shutdown_ = true; frame_processing_signal_.Signal(); } JoinThread(); return ZX_OK; } zx_status_t Ge2dDevice::WaitForInterrupt(zx_port_packet_t* packet) { return port_.wait(zx::time::infinite(), packet); } // static zx_status_t Ge2dDevice::Setup(zx_device_t* parent, std::unique_ptr<Ge2dDevice>* out) { auto pdev = ddk::PDev::FromFragment(parent); if (!pdev.is_valid()) { FX_LOGST(ERROR, kTag) << "ZX_PROTOCOL_PDEV not available"; return ZX_ERR_NO_RESOURCES; } std::optional<ddk::MmioBuffer> ge2d_mmio; zx_status_t status = pdev.MapMmio(kGe2d, &ge2d_mmio); if (status != ZX_OK) { FX_PLOGST(ERROR, kTag, status) << "pdev_.MapMmio failed"; return status; } zx::interrupt ge2d_irq; status = pdev.GetInterrupt(0, &ge2d_irq); if (status != ZX_OK) { FX_PLOGST(ERROR, kTag, status) << "pdev_.GetInterrupt failed"; return status; } zx::port port; status = zx::port::create(ZX_PORT_BIND_TO_INTERRUPT, &port); if (status != ZX_OK) { FX_PLOGST(ERROR, kTag, status) << "port create failed"; return status; } status = ge2d_irq.bind(port, kPortKeyIrqMsg, 0 /*options*/); if (status != ZX_OK) { FX_PLOGST(ERROR, kTag, status) << "interrupt bind failed"; return status; } zx::bti bti; status = pdev.GetBti(0, &bti); if (status != ZX_OK) { FX_PLOGST(ERROR, kTag, status) << "could not obtain bti"; return status; } ddk::AmlogicCanvasProtocolClient canvas(parent, "canvas"); if (!canvas.is_valid()) { FX_LOGST(ERROR, kTag) << "Could not get Amlogic Canvas protocol"; return ZX_ERR_NO_RESOURCES; } amlogic_canvas_protocol_t c; canvas.GetProto(&c); // TODO(fxbug.dev/43822): Initialize clock. GenCtrl1::Get().FromValue(0).set_soft_reset(1).WriteTo(&*ge2d_mmio); GenCtrl1::Get().FromValue(0).set_soft_reset(0).WriteTo(&*ge2d_mmio); GenCtrl1::Get().FromValue(0).set_interrupt_on_idling(1).WriteTo(&*ge2d_mmio); auto ge2d_device = std::make_unique<Ge2dDevice>( parent, std::move(*ge2d_mmio), std::move(ge2d_irq), std::move(bti), std::move(port), c); status = ge2d_device->StartThread(); *out = std::move(ge2d_device); return status; } void Ge2dDevice::DdkUnbind(ddk::UnbindTxn txn) { ShutDown(); txn.Reply(); } void Ge2dDevice::DdkRelease() { StopThread(); delete this; } void Ge2dDevice::ShutDown() {} } // namespace ge2d
/** * Copyright (c) 2016-present, Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <htrace.hpp> #include "caffe2/contrib/prof/htrace_conf.h" #include "caffe2/core/net_async_dag_gpu.h" #include "caffe2/core/operator.h" namespace caffe2 { namespace { class HTraceAsyncDAGNet : public AsyncDAGNet { public: HTraceAsyncDAGNet(const std::shared_ptr<const NetDef>& net_def, Workspace* ws) : AsyncDAGNet(net_def, ws) { VLOG(1) << "Constructing HTraceAsyncDAGNet " << net_def->name(); for (auto& worker : workers_) { std::thread::id worker_id = worker.get_id(); std::stringstream stream; stream << "worker-scope-" << worker_id; htrace_worker_scope_map_[worker_id] = std::make_shared<htrace::Scope>( htrace_tracer_, htrace_root_scope_.GetSpanId(), stream.str()); } } ~HTraceAsyncDAGNet() { VLOG(1) << "Closing all htrace scopes for workers"; // Due to the implementation of htrace, // we need to make sure we delete the scopes in order. // Simply calling map.clear() may not preserve the order. auto iter = htrace_worker_scope_map_.begin(); while (iter != htrace_worker_scope_map_.end()) { iter = htrace_worker_scope_map_.erase(iter); } } protected: bool DoRunAsync() override { htrace::Scope run_scope( htrace_tracer_, htrace_root_scope_.GetSpanId(), "run-scope-" + caffe2::to_string(run_count_++)); return AsyncDAGNet::DoRunAsync(); } htrace::Conf htrace_conf_{defaultHTraceConf(name_)}; htrace::Tracer htrace_tracer_{"htrace-tracer", htrace_conf_}; htrace::Sampler htrace_sampler_{&htrace_tracer_, htrace_conf_}; htrace::Scope htrace_root_scope_{htrace_tracer_, htrace_sampler_, "root-scope"}; std::map<std::thread::id, std::shared_ptr<htrace::Scope>> htrace_worker_scope_map_; int run_count_ = 0; }; REGISTER_NET(htrace_async_dag, HTraceAsyncDAGNet); } // namespace } // namespace caffe2
// Distributed under the MIT License. // See LICENSE.txt for details. #pragma once #include "Framework/TestingFramework.hpp" #include <array> #include <cstddef> #include "DataStructures/DataBox/Prefixes.hpp" // IWYU pragma: keep #include "DataStructures/DataVector.hpp" // IWYU pragma: keep #include "DataStructures/Tensor/EagerMath/DeterminantAndInverse.hpp" #include "DataStructures/Tensor/Tensor.hpp" #include "DataStructures/Variables.hpp" #include "Domain/CoordinateMaps/Affine.hpp" #include "Domain/CoordinateMaps/CoordinateMap.hpp" #include "Domain/CoordinateMaps/CoordinateMap.tpp" #include "Domain/CoordinateMaps/ProductMaps.hpp" #include "Domain/CoordinateMaps/ProductMaps.tpp" #include "Domain/LogicalCoordinates.hpp" #include "Evolution/Systems/GeneralizedHarmonic/Constraints.hpp" #include "Evolution/Systems/GeneralizedHarmonic/DuDtTempTags.hpp" #include "Evolution/Systems/GeneralizedHarmonic/Tags.hpp" #include "Evolution/Systems/GeneralizedHarmonic/TimeDerivative.hpp" #include "Evolution/TypeTraits.hpp" // IWYU pragma: keep #include "Framework/TestHelpers.hpp" #include "NumericalAlgorithms/LinearOperators/PartialDerivatives.tpp" #include "NumericalAlgorithms/Spectral/Mesh.hpp" #include "NumericalAlgorithms/Spectral/Spectral.hpp" #include "PointwiseFunctions/GeneralRelativity/Christoffel.hpp" #include "PointwiseFunctions/GeneralRelativity/ExtrinsicCurvature.hpp" #include "PointwiseFunctions/GeneralRelativity/GeneralizedHarmonic/GaugeSource.hpp" #include "PointwiseFunctions/GeneralRelativity/GeneralizedHarmonic/Phi.hpp" #include "PointwiseFunctions/GeneralRelativity/GeneralizedHarmonic/Pi.hpp" #include "PointwiseFunctions/GeneralRelativity/IndexManipulation.hpp" #include "PointwiseFunctions/GeneralRelativity/InverseSpacetimeMetric.hpp" #include "PointwiseFunctions/GeneralRelativity/SpacetimeMetric.hpp" #include "PointwiseFunctions/GeneralRelativity/SpacetimeNormalOneForm.hpp" #include "PointwiseFunctions/GeneralRelativity/SpacetimeNormalVector.hpp" #include "PointwiseFunctions/GeneralRelativity/Tags.hpp" #include "Utilities/ConstantExpressions.hpp" #include "Utilities/Gsl.hpp" #include "Utilities/MakeWithValue.hpp" #include "Utilities/StdArrayHelpers.hpp" #include "Utilities/TMPL.hpp" #include "Utilities/TypeTraits.hpp" /// \cond // IWYU pragma: no_forward_declare Tensor // IWYU pragma: no_forward_declare Tags::deriv /// \endcond namespace TestHelpers { /// \ingroup TestingFrameworkGroup /// Functions for testing GR analytic solutions namespace VerifyGrSolution { /// Determines if the given `solution` is a time-independent solution /// of the Einstein equations. Uses numerical derivatives to compute /// the solution, on a grid extending from `lower_bound` to `upper_bound` /// with `grid_size_each_dimension` points in each dimension. /// The right-hand side of the Einstein equations must be zero within /// `error_tolerance` template <typename Solution> void verify_time_independent_einstein_solution( const Solution& solution, const size_t grid_size_each_dimension, const std::array<double, 3>& lower_bound, const std::array<double, 3>& upper_bound, const double error_tolerance) noexcept { static_assert(evolution::is_analytic_solution_v<Solution>, "Solution was not derived from AnalyticSolution"); // Shorter names for tags. using SpacetimeMetric = gr::Tags::SpacetimeMetric<3, Frame::Inertial>; using Pi = ::GeneralizedHarmonic::Tags::Pi<3, Frame::Inertial>; using Phi = ::GeneralizedHarmonic::Tags::Phi<3, Frame::Inertial>; using GaugeH = ::GeneralizedHarmonic::Tags::GaugeH<3, Frame::Inertial>; using VariablesTags = tmpl::list<SpacetimeMetric, Pi, Phi, GaugeH>; // Set up grid const size_t data_size = pow<3>(grid_size_each_dimension); Mesh<3> mesh{grid_size_each_dimension, Spectral::Basis::Legendre, Spectral::Quadrature::GaussLobatto}; using Affine = domain::CoordinateMaps::Affine; using Affine3D = domain::CoordinateMaps::ProductOf3Maps<Affine, Affine, Affine>; const auto coord_map = domain::make_coordinate_map<Frame::ElementLogical, Frame::Inertial>( Affine3D{ Affine{-1., 1., lower_bound[0], upper_bound[0]}, Affine{-1., 1., lower_bound[1], upper_bound[1]}, Affine{-1., 1., lower_bound[2], upper_bound[2]}, }); // Set up coordinates const auto x_logical = logical_coordinates(mesh); const auto x = coord_map(x_logical); const double t = 1.3; // Arbitrary time for time-independent solution. // Evaluate analytic solution const auto vars = solution.variables(x, t, typename Solution::template tags<DataVector>{}); const auto& lapse = get<gr::Tags::Lapse<>>(vars); const auto& dt_lapse = get<Tags::dt<gr::Tags::Lapse<>>>(vars); const auto& d_lapse = get<typename Solution::template DerivLapse<DataVector>>(vars); const auto& shift = get<gr::Tags::Shift<3>>(vars); const auto& d_shift = get<typename Solution::template DerivShift<DataVector>>(vars); const auto& dt_shift = get<Tags::dt<gr::Tags::Shift<3>>>(vars); const auto& g = get<gr::Tags::SpatialMetric<3>>(vars); const auto& dt_g = get<Tags::dt<gr::Tags::SpatialMetric<3>>>(vars); const auto& d_g = get<typename Solution::template DerivSpatialMetric<DataVector>>(vars); // Check those quantities that should vanish identically. CHECK(get(dt_lapse) == make_with_value<DataVector>(x, 0.)); CHECK(dt_shift == make_with_value<cpp20::remove_cvref_t<decltype(dt_shift)>>(x, 0.)); CHECK(dt_g == make_with_value<cpp20::remove_cvref_t<decltype(dt_g)>>(x, 0.)); // Need upper spatial metric for many things below. const auto upper_spatial_metric = determinant_and_inverse(g).second; // Compute generalized harmonic quantities. Put them in a Variables // so that we can take numerical derivatives of them. // Also put gauge_function into this list since we need a numerical // derivative of it too. Variables<VariablesTags> gh_vars(data_size); auto& psi = get<SpacetimeMetric>(gh_vars); auto& pi = get<Pi>(gh_vars); auto& phi = get<Phi>(gh_vars); auto& gauge_function = get<GaugeH>(gh_vars); psi = gr::spacetime_metric(lapse, shift, g); phi = GeneralizedHarmonic::phi(lapse, d_lapse, shift, d_shift, g, d_g); pi = GeneralizedHarmonic::pi(lapse, dt_lapse, shift, dt_shift, g, dt_g, phi); // Compute gauge_function compatible with d/dt(lapse) and d/dt(shift). gauge_function = GeneralizedHarmonic::gauge_source( lapse, dt_lapse, d_lapse, shift, dt_shift, d_shift, g, trace(gr::extrinsic_curvature(lapse, shift, d_shift, g, dt_g, d_g), upper_spatial_metric), trace_last_indices(gr::christoffel_first_kind(d_g), upper_spatial_metric)); // Compute numerical derivatives of psi,pi,phi,H. // Normally one should not take numerical derivatives of H for // plugging into the RHS of the generalized harmonic equations, but // here this is just a test. const auto gh_derivs = partial_derivatives<VariablesTags, VariablesTags, 3, Frame::Inertial>( gh_vars, mesh, coord_map.inv_jacobian(x_logical)); const auto& d_psi = get<Tags::deriv<SpacetimeMetric, tmpl::size_t<3>, Frame::Inertial>>( gh_derivs); const auto& d_pi = get<Tags::deriv<Pi, tmpl::size_t<3>, Frame::Inertial>>(gh_derivs); const auto& d_phi = get<Tags::deriv<Phi, tmpl::size_t<3>, Frame::Inertial>>(gh_derivs); const auto& d_H = get<Tags::deriv<GaugeH, tmpl::size_t<3>, Frame::Inertial>>(gh_derivs); Approx numerical_approx = Approx::custom().epsilon(error_tolerance).scale(1.0); // Test 3-index constraint CHECK_ITERABLE_CUSTOM_APPROX(d_psi, phi, numerical_approx); // Compute spacetime deriv of H. // Assume time derivative of H is zero, for time-independent solution auto d4_H = make_with_value<tnsr::ab<DataVector, 3>>(x, 0.0); for (size_t a = 0; a < 4; ++a) { for (size_t i = 0; i < 3; ++i) { d4_H.get(i + 1, a) = d_H.get(i, a); } } // Compute analytic derivatives of psi, for use in computing // christoffel symbols. auto d4_psi = make_with_value<tnsr::abb<DataVector, 3>>(x, 0.0); for (size_t b = 0; b < 4; ++b) { for (size_t c = b; c < 4; ++c) { // symmetry d4_psi.get(0, b, c) = -get(lapse) * pi.get(b, c); for (size_t k = 0; k < 3; ++k) { d4_psi.get(0, b, c) += shift.get(k) * phi.get(k, b, c); d4_psi.get(k + 1, b, c) = phi.get(k, b, c); } } } // Compute derived spacetime quantities const auto upper_psi = gr::inverse_spacetime_metric(lapse, shift, upper_spatial_metric); const auto christoffel_first_kind = gr::christoffel_first_kind(d4_psi); const auto christoffel_second_kind = raise_or_lower_first_index(christoffel_first_kind, upper_psi); const auto trace_christoffel_first_kind = trace_last_indices(christoffel_first_kind, upper_psi); const auto normal_one_form = gr::spacetime_normal_one_form<3, Frame::Inertial>(lapse); const auto normal_vector = gr::spacetime_normal_vector(lapse, shift); // Test ADM evolution equation gives zero auto dt_g_adm = make_with_value<tnsr::ii<DataVector, 3>>(x, 0.0); { auto ex_curv = gr::extrinsic_curvature(lapse, shift, d_shift, g, dt_g, d_g); for (size_t i = 0; i < 3; ++i) { for (size_t j = i; j < 3; ++j) { // Symmetry dt_g_adm.get(i, j) -= 2.0 * get(lapse) * ex_curv.get(i, j); for (size_t k = 0; k < 3; ++k) { dt_g_adm.get(i, j) += shift.get(k) * d_g.get(k, i, j) + g.get(k, i) * d_shift.get(j, k) + g.get(k, j) * d_shift.get(i, k); } } } CHECK_ITERABLE_APPROX(dt_g_adm, make_with_value<decltype(dt_g_adm)>(x, 0.0)); } // Test 1-index constraint auto C_1 = GeneralizedHarmonic::gauge_constraint( gauge_function, normal_one_form, normal_vector, upper_spatial_metric, upper_psi, pi, phi); CHECK_ITERABLE_CUSTOM_APPROX(C_1, make_with_value<decltype(C_1)>(x, 0.0), numerical_approx); // Constraint-damping parameters: Set to arbitrary values. // gamma = 0 (for all gammas) and gamma1 = -1 are special because, // they zero out various terms in the equations, so don't choose those. const auto gamma0 = make_with_value<Scalar<DataVector>>(x, 1.0); const auto gamma1 = make_with_value<Scalar<DataVector>>(x, 1.0); const auto gamma2 = make_with_value<Scalar<DataVector>>(x, 1.0); // Compute RHS of generalized harmonic Einstein equations. auto dt_psi = make_with_value<tnsr::aa<DataVector, 3, Frame::Inertial>>(x, 0.0); auto dt_pi = make_with_value<tnsr::aa<DataVector, 3, Frame::Inertial>>(x, 0.0); auto dt_phi = make_with_value<tnsr::iaa<DataVector, 3, Frame::Inertial>>(x, 0.0); Variables<tmpl::list< GeneralizedHarmonic::ConstraintDamping::Tags::ConstraintGamma1, GeneralizedHarmonic::ConstraintDamping::Tags::ConstraintGamma2, GeneralizedHarmonic::Tags::GaugeH<3>, GeneralizedHarmonic::Tags::SpacetimeDerivGaugeH<3>, GeneralizedHarmonic::Tags::Gamma1Gamma2, GeneralizedHarmonic::Tags::PiTwoNormals, GeneralizedHarmonic::Tags::NormalDotOneIndexConstraint, GeneralizedHarmonic::Tags::Gamma1Plus1, GeneralizedHarmonic::Tags::PiOneNormal<3>, GeneralizedHarmonic::Tags::GaugeConstraint<3, Frame::Inertial>, GeneralizedHarmonic::Tags::PhiTwoNormals<3>, GeneralizedHarmonic::Tags::ShiftDotThreeIndexConstraint<3>, GeneralizedHarmonic::Tags::PhiOneNormal<3>, GeneralizedHarmonic::Tags::PiSecondIndexUp<3>, GeneralizedHarmonic::Tags::ThreeIndexConstraint<3, Frame::Inertial>, GeneralizedHarmonic::Tags::PhiFirstIndexUp<3>, GeneralizedHarmonic::Tags::PhiThirdIndexUp<3>, GeneralizedHarmonic::Tags::SpacetimeChristoffelFirstKindThirdIndexUp<3>, gr::Tags::Lapse<DataVector>, gr::Tags::Shift<3, Frame::Inertial, DataVector>, gr::Tags::SpatialMetric<3, Frame::Inertial, DataVector>, gr::Tags::InverseSpatialMetric<3, Frame::Inertial, DataVector>, gr::Tags::DetSpatialMetric<DataVector>, gr::Tags::InverseSpacetimeMetric<3, Frame::Inertial, DataVector>, gr::Tags::SpacetimeChristoffelFirstKind<3, Frame::Inertial, DataVector>, gr::Tags::SpacetimeChristoffelSecondKind<3, Frame::Inertial, DataVector>, gr::Tags::TraceSpacetimeChristoffelFirstKind<3, Frame::Inertial, DataVector>, gr::Tags::SpacetimeNormalVector<3, Frame::Inertial, DataVector>, gr::Tags::SpacetimeNormalOneForm<3, Frame::Inertial, DataVector>, gr::Tags::DerivativesOfSpacetimeMetric<3, Frame::Inertial, DataVector>>> buffer(mesh.number_of_grid_points()); GeneralizedHarmonic::TimeDerivative<3>::apply( make_not_null(&dt_psi), make_not_null(&dt_pi), make_not_null(&dt_phi), make_not_null( &get<GeneralizedHarmonic::ConstraintDamping::Tags::ConstraintGamma1>( buffer)), make_not_null( &get<GeneralizedHarmonic::ConstraintDamping::Tags::ConstraintGamma2>( buffer)), make_not_null(&get<GeneralizedHarmonic::Tags::GaugeH<3>>(buffer)), make_not_null( &get<GeneralizedHarmonic::Tags::SpacetimeDerivGaugeH<3>>(buffer)), make_not_null(&get<GeneralizedHarmonic::Tags::Gamma1Gamma2>(buffer)), make_not_null(&get<GeneralizedHarmonic::Tags::PiTwoNormals>(buffer)), make_not_null( &get<GeneralizedHarmonic::Tags::NormalDotOneIndexConstraint>(buffer)), make_not_null(&get<GeneralizedHarmonic::Tags::Gamma1Plus1>(buffer)), make_not_null(&get<GeneralizedHarmonic::Tags::PiOneNormal<3>>(buffer)), make_not_null( &get<GeneralizedHarmonic::Tags::GaugeConstraint<3, Frame::Inertial>>( buffer)), make_not_null(&get<GeneralizedHarmonic::Tags::PhiTwoNormals<3>>(buffer)), make_not_null( &get<GeneralizedHarmonic::Tags::ShiftDotThreeIndexConstraint<3>>( buffer)), make_not_null(&get<GeneralizedHarmonic::Tags::PhiOneNormal<3>>(buffer)), make_not_null( &get<GeneralizedHarmonic::Tags::PiSecondIndexUp<3>>(buffer)), make_not_null(&get<GeneralizedHarmonic::Tags::ThreeIndexConstraint< 3, Frame::Inertial>>(buffer)), make_not_null( &get<GeneralizedHarmonic::Tags::PhiFirstIndexUp<3>>(buffer)), make_not_null( &get<GeneralizedHarmonic::Tags::PhiThirdIndexUp<3>>(buffer)), make_not_null( &get<GeneralizedHarmonic::Tags:: SpacetimeChristoffelFirstKindThirdIndexUp<3>>(buffer)), make_not_null(&get<gr::Tags::Lapse<DataVector>>(buffer)), make_not_null( &get<gr::Tags::Shift<3, Frame::Inertial, DataVector>>(buffer)), make_not_null( &get<gr::Tags::SpatialMetric<3, Frame::Inertial, DataVector>>( buffer)), make_not_null( &get<gr::Tags::InverseSpatialMetric<3, Frame::Inertial, DataVector>>( buffer)), make_not_null(&get<gr::Tags::DetSpatialMetric<DataVector>>(buffer)), make_not_null(&get<gr::Tags::InverseSpacetimeMetric<3, Frame::Inertial, DataVector>>(buffer)), make_not_null( &get<gr::Tags::SpacetimeChristoffelFirstKind<3, Frame::Inertial, DataVector>>(buffer)), make_not_null( &get<gr::Tags::SpacetimeChristoffelSecondKind<3, Frame::Inertial, DataVector>>(buffer)), make_not_null(&get<gr::Tags::TraceSpacetimeChristoffelFirstKind< 3, Frame::Inertial, DataVector>>(buffer)), make_not_null( &get<gr::Tags::SpacetimeNormalVector<3, Frame::Inertial, DataVector>>( buffer)), make_not_null(&get<gr::Tags::SpacetimeNormalOneForm<3, Frame::Inertial, DataVector>>(buffer)), make_not_null( &get<gr::Tags::DerivativesOfSpacetimeMetric<3, Frame::Inertial, DataVector>>(buffer)), d_psi, d_pi, d_phi, psi, pi, phi, gamma0, gamma1, gamma2, gauge_function, d4_H); // Make sure the RHS is zero. CHECK_ITERABLE_CUSTOM_APPROX( dt_psi, make_with_value<decltype(dt_psi)>(x, 0.0), numerical_approx); CHECK_ITERABLE_CUSTOM_APPROX(dt_pi, make_with_value<decltype(dt_pi)>(x, 0.0), numerical_approx); CHECK_ITERABLE_CUSTOM_APPROX( dt_phi, make_with_value<decltype(dt_phi)>(x, 0.0), numerical_approx); } namespace detail { template <typename Tag, typename Frame> using deriv = Tags::deriv<Tag, tmpl::size_t<3>, Frame>; template <typename Tag, typename Solution, typename Frame> auto time_derivative(const Solution& solution, const tnsr::I<double, 3, Frame>& x, const double time, const double dt) noexcept { typename Tag::type result{}; for (auto it = result.begin(); it != result.end(); ++it) { const auto index = result.get_tensor_index(it); *it = numerical_derivative( [&index, &solution, &x](const std::array<double, 1>& t_array) noexcept { return std::array<double, 1>{ {get<Tag>(solution.variables(x, t_array[0], tmpl::list<Tag>{})) .get(index)}}; }, std::array<double, 1>{{time}}, 0, dt)[0]; } return result; } template <typename Tag, typename Solution, typename Frame> auto space_derivative(const Solution& solution, const tnsr::I<double, 3, Frame>& x, const double time, const double dx) noexcept { typename deriv<Tag, Frame>::type result{}; for (auto it = result.begin(); it != result.end(); ++it) { const auto index = result.get_tensor_index(it); *it = numerical_derivative( [&index, &solution, &time, &x](const std::array<double, 1>& offset) noexcept { auto position = x; position.get(index[0]) += offset[0]; return std::array<double, 1>{ {get<Tag>(solution.variables(position, time, tmpl::list<Tag>{})) .get(all_but_specified_element_of(index, 0))}}; }, std::array<double, 1>{{0.0}}, 0, dx)[0]; } return result; } } // namespace detail /// Check the consistency of dependent quantities returned by a /// solution. This includes checking pointwise relations such as /// consistency of the metric and inverse and comparing returned and /// numerical derivatives. template <typename Solution, typename Frame> void verify_consistency(const Solution& solution, const double time, const tnsr::I<double, 3, Frame>& position, const double derivative_delta, const double derivative_tolerance) noexcept { using Lapse = gr::Tags::Lapse<double>; using Shift = gr::Tags::Shift<3, Frame, double>; using SpatialMetric = gr::Tags::SpatialMetric<3, Frame, double>; using SqrtDetSpatialMetric = gr::Tags::SqrtDetSpatialMetric<double>; using InverseSpatialMetric = gr::Tags::InverseSpatialMetric<3, Frame, double>; using ExtrinsicCurvature = gr::Tags::ExtrinsicCurvature<3, Frame, double>; using tags = tmpl::list<SpatialMetric, SqrtDetSpatialMetric, InverseSpatialMetric, ExtrinsicCurvature, Lapse, Shift, detail::deriv<Shift, Frame>, Tags::dt<SpatialMetric>, detail::deriv<SpatialMetric, Frame>, Tags::dt<Lapse>, Tags::dt<Shift>, detail::deriv<Lapse, Frame>>; auto derivative_approx = approx.epsilon(derivative_tolerance); const auto vars = solution.variables(position, time, tags{}); const auto numerical_metric_det_and_inverse = determinant_and_inverse(get<SpatialMetric>(vars)); CHECK_ITERABLE_APPROX(get(get<SqrtDetSpatialMetric>(vars)), sqrt(get(numerical_metric_det_and_inverse.first))); CHECK_ITERABLE_APPROX(get<InverseSpatialMetric>(vars), numerical_metric_det_and_inverse.second); CHECK_ITERABLE_APPROX( get<ExtrinsicCurvature>(vars), gr::extrinsic_curvature(get<Lapse>(vars), get<Shift>(vars), get<detail::deriv<Shift, Frame>>(vars), get<SpatialMetric>(vars), get<Tags::dt<SpatialMetric>>(vars), get<detail::deriv<SpatialMetric, Frame>>(vars))); CHECK_ITERABLE_CUSTOM_APPROX(get<Tags::dt<Lapse>>(vars), detail::time_derivative<Lapse>( solution, position, time, derivative_delta), derivative_approx); CHECK_ITERABLE_CUSTOM_APPROX(get<Tags::dt<Shift>>(vars), detail::time_derivative<Shift>( solution, position, time, derivative_delta), derivative_approx); CHECK_ITERABLE_CUSTOM_APPROX(get<Tags::dt<SpatialMetric>>(vars), detail::time_derivative<SpatialMetric>( solution, position, time, derivative_delta), derivative_approx); CHECK_ITERABLE_CUSTOM_APPROX( SINGLE_ARG(get<detail::deriv<Lapse, Frame>>(vars)), detail::space_derivative<Lapse>(solution, position, time, derivative_delta), derivative_approx); CHECK_ITERABLE_CUSTOM_APPROX( SINGLE_ARG(get<detail::deriv<Shift, Frame>>(vars)), detail::space_derivative<Shift>(solution, position, time, derivative_delta), derivative_approx); CHECK_ITERABLE_CUSTOM_APPROX( SINGLE_ARG(get<detail::deriv<SpatialMetric, Frame>>(vars)), detail::space_derivative<SpatialMetric>(solution, position, time, derivative_delta), derivative_approx); } } // namespace VerifyGrSolution } // namespace TestHelpers
#define USING_TEST_MEMORY #include "Test.h" TEST_CONSTRUCT; #include "test/type/Value.h" #include <cstdio> int main() { typedef test::type::Value<int, 4> ValueInt4; ValueInt4 i1; printf("%d\n", ValueInt4{}.Get()); }
/*************************************************************************/ /* scene_tree.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "scene_tree.h" #include "core/io/marshalls.h" #include "core/io/resource_loader.h" #include "core/message_queue.h" #include "core/os/keyboard.h" #include "core/os/os.h" #include "core/print_string.h" #include "core/project_settings.h" #include "editor/editor_node.h" #include "main/input_default.h" #include "node.h" #include "scene/resources/dynamic_font.h" #include "scene/resources/material.h" #include "scene/resources/mesh.h" #include "scene/resources/packed_scene.h" #include "scene/scene_string_names.h" #include "servers/physics_2d_server.h" #include "servers/physics_server.h" #include "viewport.h" #include <stdio.h> void SceneTreeTimer::_bind_methods() { ClassDB::bind_method(D_METHOD("set_time_left", "time"), &SceneTreeTimer::set_time_left); ClassDB::bind_method(D_METHOD("get_time_left"), &SceneTreeTimer::get_time_left); ADD_PROPERTY(PropertyInfo(Variant::REAL, "time_left"), "set_time_left", "get_time_left"); ADD_SIGNAL(MethodInfo("timeout")); } void SceneTreeTimer::set_time_left(float p_time) { time_left = p_time; } float SceneTreeTimer::get_time_left() const { return time_left; } void SceneTreeTimer::set_pause_mode_process(bool p_pause_mode_process) { if (process_pause != p_pause_mode_process) { process_pause = p_pause_mode_process; } } bool SceneTreeTimer::is_pause_mode_process() { return process_pause; } SceneTreeTimer::SceneTreeTimer() { time_left = 0; process_pause = true; } void SceneTree::tree_changed() { tree_version++; emit_signal(tree_changed_name); } void SceneTree::node_added(Node *p_node) { emit_signal(node_added_name, p_node); } void SceneTree::node_removed(Node *p_node) { if (current_scene == p_node) { current_scene = NULL; } emit_signal(node_removed_name, p_node); if (call_lock > 0) call_skip.insert(p_node); } SceneTree::Group *SceneTree::add_to_group(const StringName &p_group, Node *p_node) { Map<StringName, Group>::Element *E = group_map.find(p_group); if (!E) { E = group_map.insert(p_group, Group()); } if (E->get().nodes.find(p_node) != -1) { ERR_EXPLAIN("Already in group: " + p_group); ERR_FAIL_V(&E->get()); } E->get().nodes.push_back(p_node); //E->get().last_tree_version=0; E->get().changed = true; return &E->get(); } void SceneTree::remove_from_group(const StringName &p_group, Node *p_node) { Map<StringName, Group>::Element *E = group_map.find(p_group); ERR_FAIL_COND(!E); E->get().nodes.erase(p_node); if (E->get().nodes.empty()) group_map.erase(E); } void SceneTree::make_group_changed(const StringName &p_group) { Map<StringName, Group>::Element *E = group_map.find(p_group); if (E) E->get().changed = true; } void SceneTree::flush_transform_notifications() { SelfList<Node> *n = xform_change_list.first(); while (n) { Node *node = n->self(); SelfList<Node> *nx = n->next(); xform_change_list.remove(n); n = nx; node->notification(NOTIFICATION_TRANSFORM_CHANGED); } } void SceneTree::_flush_ugc() { ugc_locked = true; while (unique_group_calls.size()) { Map<UGCall, Vector<Variant> >::Element *E = unique_group_calls.front(); Variant v[VARIANT_ARG_MAX]; for (int i = 0; i < E->get().size(); i++) v[i] = E->get()[i]; call_group_flags(GROUP_CALL_REALTIME, E->key().group, E->key().call, v[0], v[1], v[2], v[3], v[4]); unique_group_calls.erase(E); } ugc_locked = false; } void SceneTree::_update_group_order(Group &g, bool p_use_priority) { if (!g.changed) return; if (g.nodes.empty()) return; Node **nodes = g.nodes.ptrw(); int node_count = g.nodes.size(); if (p_use_priority) { SortArray<Node *, Node::ComparatorWithPriority> node_sort; node_sort.sort(nodes, node_count); } else { SortArray<Node *, Node::Comparator> node_sort; node_sort.sort(nodes, node_count); } g.changed = false; } void SceneTree::call_group_flags(uint32_t p_call_flags, const StringName &p_group, const StringName &p_function, VARIANT_ARG_DECLARE) { Map<StringName, Group>::Element *E = group_map.find(p_group); if (!E) return; Group &g = E->get(); if (g.nodes.empty()) return; if (p_call_flags & GROUP_CALL_UNIQUE && !(p_call_flags & GROUP_CALL_REALTIME)) { ERR_FAIL_COND(ugc_locked); UGCall ug; ug.call = p_function; ug.group = p_group; if (unique_group_calls.has(ug)) return; VARIANT_ARGPTRS; Vector<Variant> args; for (int i = 0; i < VARIANT_ARG_MAX; i++) { if (argptr[i]->get_type() == Variant::NIL) break; args.push_back(*argptr[i]); } unique_group_calls[ug] = args; return; } _update_group_order(g); Vector<Node *> nodes_copy = g.nodes; Node **nodes = nodes_copy.ptrw(); int node_count = nodes_copy.size(); call_lock++; if (p_call_flags & GROUP_CALL_REVERSE) { for (int i = node_count - 1; i >= 0; i--) { if (call_lock && call_skip.has(nodes[i])) continue; if (p_call_flags & GROUP_CALL_REALTIME) { if (p_call_flags & GROUP_CALL_MULTILEVEL) nodes[i]->call_multilevel(p_function, VARIANT_ARG_PASS); else nodes[i]->call(p_function, VARIANT_ARG_PASS); } else MessageQueue::get_singleton()->push_call(nodes[i], p_function, VARIANT_ARG_PASS); } } else { for (int i = 0; i < node_count; i++) { if (call_lock && call_skip.has(nodes[i])) continue; if (p_call_flags & GROUP_CALL_REALTIME) { if (p_call_flags & GROUP_CALL_MULTILEVEL) nodes[i]->call_multilevel(p_function, VARIANT_ARG_PASS); else nodes[i]->call(p_function, VARIANT_ARG_PASS); } else MessageQueue::get_singleton()->push_call(nodes[i], p_function, VARIANT_ARG_PASS); } } call_lock--; if (call_lock == 0) call_skip.clear(); } void SceneTree::notify_group_flags(uint32_t p_call_flags, const StringName &p_group, int p_notification) { Map<StringName, Group>::Element *E = group_map.find(p_group); if (!E) return; Group &g = E->get(); if (g.nodes.empty()) return; _update_group_order(g); Vector<Node *> nodes_copy = g.nodes; Node **nodes = nodes_copy.ptrw(); int node_count = nodes_copy.size(); call_lock++; if (p_call_flags & GROUP_CALL_REVERSE) { for (int i = node_count - 1; i >= 0; i--) { if (call_lock && call_skip.has(nodes[i])) continue; if (p_call_flags & GROUP_CALL_REALTIME) nodes[i]->notification(p_notification); else MessageQueue::get_singleton()->push_notification(nodes[i], p_notification); } } else { for (int i = 0; i < node_count; i++) { if (call_lock && call_skip.has(nodes[i])) continue; if (p_call_flags & GROUP_CALL_REALTIME) nodes[i]->notification(p_notification); else MessageQueue::get_singleton()->push_notification(nodes[i], p_notification); } } call_lock--; if (call_lock == 0) call_skip.clear(); } void SceneTree::set_group_flags(uint32_t p_call_flags, const StringName &p_group, const String &p_name, const Variant &p_value) { Map<StringName, Group>::Element *E = group_map.find(p_group); if (!E) return; Group &g = E->get(); if (g.nodes.empty()) return; _update_group_order(g); Vector<Node *> nodes_copy = g.nodes; Node **nodes = nodes_copy.ptrw(); int node_count = nodes_copy.size(); call_lock++; if (p_call_flags & GROUP_CALL_REVERSE) { for (int i = node_count - 1; i >= 0; i--) { if (call_lock && call_skip.has(nodes[i])) continue; if (p_call_flags & GROUP_CALL_REALTIME) nodes[i]->set(p_name, p_value); else MessageQueue::get_singleton()->push_set(nodes[i], p_name, p_value); } } else { for (int i = 0; i < node_count; i++) { if (call_lock && call_skip.has(nodes[i])) continue; if (p_call_flags & GROUP_CALL_REALTIME) nodes[i]->set(p_name, p_value); else MessageQueue::get_singleton()->push_set(nodes[i], p_name, p_value); } } call_lock--; if (call_lock == 0) call_skip.clear(); } void SceneTree::call_group(const StringName &p_group, const StringName &p_function, VARIANT_ARG_DECLARE) { call_group_flags(0, p_group, VARIANT_ARG_PASS); } void SceneTree::notify_group(const StringName &p_group, int p_notification) { notify_group_flags(0, p_group, p_notification); } void SceneTree::set_group(const StringName &p_group, const String &p_name, const Variant &p_value) { set_group_flags(0, p_group, p_name, p_value); } void SceneTree::set_input_as_handled() { input_handled = true; } void SceneTree::input_text(const String &p_text) { root_lock++; call_group_flags(GROUP_CALL_REALTIME, "_viewports", "_vp_input_text", p_text); //special one for GUI, as controls use their own process check root_lock--; } bool SceneTree::is_input_handled() { return input_handled; } void SceneTree::input_event(const Ref<InputEvent> &p_event) { if (Engine::get_singleton()->is_editor_hint() && (Object::cast_to<InputEventJoypadButton>(p_event.ptr()) || Object::cast_to<InputEventJoypadMotion>(*p_event))) return; //avoid joy input on editor current_event++; root_lock++; input_handled = false; Ref<InputEvent> ev = p_event; MainLoop::input_event(ev); call_group_flags(GROUP_CALL_REALTIME, "_viewports", "_vp_input", ev); //special one for GUI, as controls use their own process check if (ScriptDebugger::get_singleton() && ScriptDebugger::get_singleton()->is_remote()) { //quit from game window using F8 Ref<InputEventKey> k = ev; if (k.is_valid() && k->is_pressed() && !k->is_echo() && k->get_scancode() == KEY_F8) { ScriptDebugger::get_singleton()->request_quit(); } } _flush_ugc(); root_lock--; //MessageQueue::get_singleton()->flush(); //flushing here causes UI and other places slowness root_lock++; if (!input_handled) { call_group_flags(GROUP_CALL_REALTIME, "_viewports", "_vp_unhandled_input", ev); //special one for GUI, as controls use their own process check _flush_ugc(); // input_handled = true; - no reason to set this as handled root_lock--; //MessageQueue::get_singleton()->flush(); //flushing here causes UI and other places slowness } else { // input_handled = true; - no reason to set this as handled root_lock--; } _call_idle_callbacks(); } void SceneTree::init() { //_quit=false; initialized = true; input_handled = false; pause = false; root->_set_tree(this); MainLoop::init(); } bool SceneTree::iteration(float p_time) { root_lock++; current_frame++; flush_transform_notifications(); MainLoop::iteration(p_time); physics_process_time = p_time; emit_signal("physics_frame"); _notify_group_pause("physics_process_internal", Node::NOTIFICATION_INTERNAL_PHYSICS_PROCESS); _notify_group_pause("physics_process", Node::NOTIFICATION_PHYSICS_PROCESS); _flush_ugc(); MessageQueue::get_singleton()->flush(); //small little hack flush_transform_notifications(); call_group_flags(GROUP_CALL_REALTIME, "_viewports", "update_worlds"); root_lock--; _flush_delete_queue(); _call_idle_callbacks(); return _quit; } void SceneTree::_update_font_oversampling(float p_ratio) { if (use_font_oversampling) { DynamicFontAtSize::font_oversampling = p_ratio; DynamicFont::update_oversampling(); } } bool SceneTree::idle(float p_time) { //print_line("ram: "+itos(OS::get_singleton()->get_static_memory_usage())+" sram: "+itos(OS::get_singleton()->get_dynamic_memory_usage())); //print_line("node count: "+itos(get_node_count())); //print_line("TEXTURE RAM: "+itos(VS::get_singleton()->get_render_info(VS::INFO_TEXTURE_MEM_USED))); root_lock++; MainLoop::idle(p_time); idle_process_time = p_time; if (multiplayer_poll) { multiplayer->poll(); } emit_signal("idle_frame"); MessageQueue::get_singleton()->flush(); //small little hack flush_transform_notifications(); _notify_group_pause("idle_process_internal", Node::NOTIFICATION_INTERNAL_PROCESS); _notify_group_pause("idle_process", Node::NOTIFICATION_PROCESS); Size2 win_size = Size2(OS::get_singleton()->get_window_size().width, OS::get_singleton()->get_window_size().height); if (win_size != last_screen_size) { last_screen_size = win_size; _update_root_rect(); emit_signal("screen_resized"); } _flush_ugc(); MessageQueue::get_singleton()->flush(); //small little hack flush_transform_notifications(); //transforms after world update, to avoid unnecessary enter/exit notifications call_group_flags(GROUP_CALL_REALTIME, "_viewports", "update_worlds"); root_lock--; _flush_delete_queue(); //go through timers List<Ref<SceneTreeTimer> >::Element *L = timers.back(); //last element for (List<Ref<SceneTreeTimer> >::Element *E = timers.front(); E;) { List<Ref<SceneTreeTimer> >::Element *N = E->next(); if (pause && !E->get()->is_pause_mode_process()) { if (E == L) { break; //break on last, so if new timers were added during list traversal, ignore them. } E = N; continue; } float time_left = E->get()->get_time_left(); time_left -= p_time; E->get()->set_time_left(time_left); if (time_left < 0) { E->get()->emit_signal("timeout"); timers.erase(E); } if (E == L) { break; //break on last, so if new timers were added during list traversal, ignore them. } E = N; } _call_idle_callbacks(); #ifdef TOOLS_ENABLED if (Engine::get_singleton()->is_editor_hint()) { //simple hack to reload fallback environment if it changed from editor String env_path = ProjectSettings::get_singleton()->get("rendering/environment/default_environment"); env_path = env_path.strip_edges(); //user may have added a space or two String cpath; Ref<Environment> fallback = get_root()->get_world()->get_fallback_environment(); if (fallback.is_valid()) { cpath = fallback->get_path(); } if (cpath != env_path) { if (env_path != String()) { fallback = ResourceLoader::load(env_path); if (fallback.is_null()) { //could not load fallback, set as empty ProjectSettings::get_singleton()->set("rendering/environment/default_environment", ""); } } else { fallback.unref(); } get_root()->get_world()->set_fallback_environment(fallback); } } #endif return _quit; } void SceneTree::finish() { _flush_delete_queue(); _flush_ugc(); initialized = false; MainLoop::finish(); if (root) { root->_set_tree(NULL); root->_propagate_after_exit_tree(); memdelete(root); //delete root } } void SceneTree::quit() { _quit = true; } void SceneTree::_notification(int p_notification) { switch (p_notification) { case NOTIFICATION_WM_QUIT_REQUEST: { get_root()->propagate_notification(p_notification); if (accept_quit) { _quit = true; break; } } break; case NOTIFICATION_WM_GO_BACK_REQUEST: { get_root()->propagate_notification(p_notification); if (quit_on_go_back) { _quit = true; break; } } break; case NOTIFICATION_OS_MEMORY_WARNING: case NOTIFICATION_OS_IME_UPDATE: case NOTIFICATION_WM_MOUSE_ENTER: case NOTIFICATION_WM_MOUSE_EXIT: case NOTIFICATION_WM_FOCUS_IN: case NOTIFICATION_WM_FOCUS_OUT: { if (p_notification == NOTIFICATION_WM_FOCUS_IN) { InputDefault *id = Object::cast_to<InputDefault>(Input::get_singleton()); if (id) { id->ensure_touch_mouse_raised(); } } get_root()->propagate_notification(p_notification); } break; case NOTIFICATION_TRANSLATION_CHANGED: { if (!Engine::get_singleton()->is_editor_hint()) { get_root()->propagate_notification(Node::NOTIFICATION_TRANSLATION_CHANGED); } } break; case NOTIFICATION_WM_UNFOCUS_REQUEST: { notify_group_flags(GROUP_CALL_REALTIME | GROUP_CALL_MULTILEVEL, "input", NOTIFICATION_WM_UNFOCUS_REQUEST); } break; case NOTIFICATION_WM_ABOUT: { #ifdef TOOLS_ENABLED if (EditorNode::get_singleton()) { EditorNode::get_singleton()->show_about(); } else { #endif get_root()->propagate_notification(p_notification); #ifdef TOOLS_ENABLED } #endif } break; case NOTIFICATION_CRASH: { get_root()->propagate_notification(p_notification); } break; default: break; }; }; void SceneTree::set_auto_accept_quit(bool p_enable) { accept_quit = p_enable; } void SceneTree::set_quit_on_go_back(bool p_enable) { quit_on_go_back = p_enable; } #ifdef TOOLS_ENABLED bool SceneTree::is_node_being_edited(const Node *p_node) const { return Engine::get_singleton()->is_editor_hint() && edited_scene_root && (edited_scene_root->is_a_parent_of(p_node) || edited_scene_root == p_node); } #endif #ifdef DEBUG_ENABLED void SceneTree::set_debug_collisions_hint(bool p_enabled) { debug_collisions_hint = p_enabled; } bool SceneTree::is_debugging_collisions_hint() const { return debug_collisions_hint; } void SceneTree::set_debug_navigation_hint(bool p_enabled) { debug_navigation_hint = p_enabled; } bool SceneTree::is_debugging_navigation_hint() const { return debug_navigation_hint; } #endif void SceneTree::set_debug_collisions_color(const Color &p_color) { debug_collisions_color = p_color; } Color SceneTree::get_debug_collisions_color() const { return debug_collisions_color; } void SceneTree::set_debug_collision_contact_color(const Color &p_color) { debug_collision_contact_color = p_color; } Color SceneTree::get_debug_collision_contact_color() const { return debug_collision_contact_color; } void SceneTree::set_debug_navigation_color(const Color &p_color) { debug_navigation_color = p_color; } Color SceneTree::get_debug_navigation_color() const { return debug_navigation_color; } void SceneTree::set_debug_navigation_disabled_color(const Color &p_color) { debug_navigation_disabled_color = p_color; } Color SceneTree::get_debug_navigation_disabled_color() const { return debug_navigation_disabled_color; } Ref<Material> SceneTree::get_debug_navigation_material() { if (navigation_material.is_valid()) return navigation_material; Ref<SpatialMaterial> line_material = Ref<SpatialMaterial>(memnew(SpatialMaterial)); line_material->set_flag(SpatialMaterial::FLAG_UNSHADED, true); line_material->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true); line_material->set_flag(SpatialMaterial::FLAG_SRGB_VERTEX_COLOR, true); line_material->set_flag(SpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR, true); line_material->set_albedo(get_debug_navigation_color()); navigation_material = line_material; return navigation_material; } Ref<Material> SceneTree::get_debug_navigation_disabled_material() { if (navigation_disabled_material.is_valid()) return navigation_disabled_material; Ref<SpatialMaterial> line_material = Ref<SpatialMaterial>(memnew(SpatialMaterial)); line_material->set_flag(SpatialMaterial::FLAG_UNSHADED, true); line_material->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true); line_material->set_flag(SpatialMaterial::FLAG_SRGB_VERTEX_COLOR, true); line_material->set_flag(SpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR, true); line_material->set_albedo(get_debug_navigation_disabled_color()); navigation_disabled_material = line_material; return navigation_disabled_material; } Ref<Material> SceneTree::get_debug_collision_material() { if (collision_material.is_valid()) return collision_material; Ref<SpatialMaterial> line_material = Ref<SpatialMaterial>(memnew(SpatialMaterial)); line_material->set_flag(SpatialMaterial::FLAG_UNSHADED, true); line_material->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true); line_material->set_flag(SpatialMaterial::FLAG_SRGB_VERTEX_COLOR, true); line_material->set_flag(SpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR, true); line_material->set_albedo(get_debug_collisions_color()); collision_material = line_material; return collision_material; } Ref<ArrayMesh> SceneTree::get_debug_contact_mesh() { if (debug_contact_mesh.is_valid()) return debug_contact_mesh; debug_contact_mesh = Ref<ArrayMesh>(memnew(ArrayMesh)); Ref<SpatialMaterial> mat = Ref<SpatialMaterial>(memnew(SpatialMaterial)); mat->set_flag(SpatialMaterial::FLAG_UNSHADED, true); mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true); mat->set_flag(SpatialMaterial::FLAG_SRGB_VERTEX_COLOR, true); mat->set_flag(SpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR, true); mat->set_albedo(get_debug_collision_contact_color()); Vector3 diamond[6] = { Vector3(-1, 0, 0), Vector3(1, 0, 0), Vector3(0, -1, 0), Vector3(0, 1, 0), Vector3(0, 0, -1), Vector3(0, 0, 1) }; /* clang-format off */ int diamond_faces[8 * 3] = { 0, 2, 4, 0, 3, 4, 1, 2, 4, 1, 3, 4, 0, 2, 5, 0, 3, 5, 1, 2, 5, 1, 3, 5, }; /* clang-format on */ PoolVector<int> indices; for (int i = 0; i < 8 * 3; i++) indices.push_back(diamond_faces[i]); PoolVector<Vector3> vertices; for (int i = 0; i < 6; i++) vertices.push_back(diamond[i] * 0.1); Array arr; arr.resize(Mesh::ARRAY_MAX); arr[Mesh::ARRAY_VERTEX] = vertices; arr[Mesh::ARRAY_INDEX] = indices; debug_contact_mesh->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES, arr); debug_contact_mesh->surface_set_material(0, mat); return debug_contact_mesh; } void SceneTree::set_pause(bool p_enabled) { if (p_enabled == pause) return; pause = p_enabled; PhysicsServer::get_singleton()->set_active(!p_enabled); Physics2DServer::get_singleton()->set_active(!p_enabled); if (get_root()) get_root()->propagate_notification(p_enabled ? Node::NOTIFICATION_PAUSED : Node::NOTIFICATION_UNPAUSED); } bool SceneTree::is_paused() const { return pause; } void SceneTree::_call_input_pause(const StringName &p_group, const StringName &p_method, const Ref<InputEvent> &p_input) { Map<StringName, Group>::Element *E = group_map.find(p_group); if (!E) return; Group &g = E->get(); if (g.nodes.empty()) return; _update_group_order(g); //copy, so copy on write happens in case something is removed from process while being called //performance is not lost because only if something is added/removed the vector is copied. Vector<Node *> nodes_copy = g.nodes; int node_count = nodes_copy.size(); Node **nodes = nodes_copy.ptrw(); Variant arg = p_input; const Variant *v[1] = { &arg }; call_lock++; for (int i = node_count - 1; i >= 0; i--) { if (input_handled) break; Node *n = nodes[i]; if (call_lock && call_skip.has(n)) continue; if (!n->can_process()) continue; n->call_multilevel(p_method, (const Variant **)v, 1); //ERR_FAIL_COND(node_count != g.nodes.size()); } call_lock--; if (call_lock == 0) call_skip.clear(); } void SceneTree::_notify_group_pause(const StringName &p_group, int p_notification) { Map<StringName, Group>::Element *E = group_map.find(p_group); if (!E) return; Group &g = E->get(); if (g.nodes.empty()) return; _update_group_order(g, p_notification == Node::NOTIFICATION_PROCESS || p_notification == Node::NOTIFICATION_INTERNAL_PROCESS || p_notification == Node::NOTIFICATION_PHYSICS_PROCESS || p_notification == Node::NOTIFICATION_INTERNAL_PHYSICS_PROCESS); //copy, so copy on write happens in case something is removed from process while being called //performance is not lost because only if something is added/removed the vector is copied. Vector<Node *> nodes_copy = g.nodes; int node_count = nodes_copy.size(); Node **nodes = nodes_copy.ptrw(); call_lock++; for (int i = 0; i < node_count; i++) { Node *n = nodes[i]; if (call_lock && call_skip.has(n)) continue; if (!n->can_process()) continue; if (!n->can_process_notification(p_notification)) continue; n->notification(p_notification); //ERR_FAIL_COND(node_count != g.nodes.size()); } call_lock--; if (call_lock == 0) call_skip.clear(); } /* void SceneMainLoop::_update_listener_2d() { if (listener_2d.is_valid()) { SpatialSound2DServer::get_singleton()->listener_set_space( listener_2d, world_2d->get_sound_space() ); } } */ Variant SceneTree::_call_group_flags(const Variant **p_args, int p_argcount, Variant::CallError &r_error) { r_error.error = Variant::CallError::CALL_OK; ERR_FAIL_COND_V(p_argcount < 3, Variant()); ERR_FAIL_COND_V(!p_args[0]->is_num(), Variant()); ERR_FAIL_COND_V(p_args[1]->get_type() != Variant::STRING, Variant()); ERR_FAIL_COND_V(p_args[2]->get_type() != Variant::STRING, Variant()); int flags = *p_args[0]; StringName group = *p_args[1]; StringName method = *p_args[2]; Variant v[VARIANT_ARG_MAX]; for (int i = 0; i < MIN(p_argcount - 3, 5); i++) { v[i] = *p_args[i + 3]; } call_group_flags(flags, group, method, v[0], v[1], v[2], v[3], v[4]); return Variant(); } Variant SceneTree::_call_group(const Variant **p_args, int p_argcount, Variant::CallError &r_error) { r_error.error = Variant::CallError::CALL_OK; ERR_FAIL_COND_V(p_argcount < 2, Variant()); ERR_FAIL_COND_V(p_args[0]->get_type() != Variant::STRING, Variant()); ERR_FAIL_COND_V(p_args[1]->get_type() != Variant::STRING, Variant()); StringName group = *p_args[0]; StringName method = *p_args[1]; Variant v[VARIANT_ARG_MAX]; for (int i = 0; i < MIN(p_argcount - 2, 5); i++) { v[i] = *p_args[i + 2]; } call_group_flags(0, group, method, v[0], v[1], v[2], v[3], v[4]); return Variant(); } int64_t SceneTree::get_frame() const { return current_frame; } int64_t SceneTree::get_event_count() const { return current_event; } Array SceneTree::_get_nodes_in_group(const StringName &p_group) { Array ret; Map<StringName, Group>::Element *E = group_map.find(p_group); if (!E) return ret; _update_group_order(E->get()); //update order just in case int nc = E->get().nodes.size(); if (nc == 0) return ret; ret.resize(nc); Node **ptr = E->get().nodes.ptrw(); for (int i = 0; i < nc; i++) { ret[i] = ptr[i]; } return ret; } bool SceneTree::has_group(const StringName &p_identifier) const { return group_map.has(p_identifier); } void SceneTree::get_nodes_in_group(const StringName &p_group, List<Node *> *p_list) { Map<StringName, Group>::Element *E = group_map.find(p_group); if (!E) return; _update_group_order(E->get()); //update order just in case int nc = E->get().nodes.size(); if (nc == 0) return; Node **ptr = E->get().nodes.ptrw(); for (int i = 0; i < nc; i++) { p_list->push_back(ptr[i]); } } static void _fill_array(Node *p_node, Array &array, int p_level) { array.push_back(p_level); array.push_back(p_node->get_name()); array.push_back(p_node->get_class()); array.push_back(p_node->get_instance_id()); for (int i = 0; i < p_node->get_child_count(); i++) { _fill_array(p_node->get_child(i), array, p_level + 1); } } void SceneTree::_debugger_request_tree(void *self) { SceneTree *sml = (SceneTree *)self; Array arr; _fill_array(sml->root, arr, 0); ScriptDebugger::get_singleton()->send_message("scene_tree", arr); } void SceneTree::_flush_delete_queue() { _THREAD_SAFE_METHOD_ while (delete_queue.size()) { Object *obj = ObjectDB::get_instance(delete_queue.front()->get()); if (obj) { memdelete(obj); } delete_queue.pop_front(); } } void SceneTree::queue_delete(Object *p_object) { _THREAD_SAFE_METHOD_ ERR_FAIL_NULL(p_object); p_object->_is_queued_for_deletion = true; delete_queue.push_back(p_object->get_instance_id()); } int SceneTree::get_node_count() const { return node_count; } void SceneTree::_update_root_rect() { if (stretch_mode == STRETCH_MODE_DISABLED) { _update_font_oversampling(1.0); root->set_size((last_screen_size / stretch_shrink).floor()); root->set_attach_to_screen_rect(Rect2(Point2(), last_screen_size)); root->set_size_override_stretch(false); root->set_size_override(false, Size2()); root->update_canvas_items(); return; //user will take care } //actual screen video mode Size2 video_mode = Size2(OS::get_singleton()->get_window_size().width, OS::get_singleton()->get_window_size().height); Size2 desired_res = stretch_min; Size2 viewport_size; Size2 screen_size; float viewport_aspect = desired_res.aspect(); float video_mode_aspect = video_mode.aspect(); if (stretch_aspect == STRETCH_ASPECT_IGNORE || ABS(viewport_aspect - video_mode_aspect) < CMP_EPSILON) { //same aspect or ignore aspect viewport_size = desired_res; screen_size = video_mode; if (use_font_oversampling) { WARN_PRINT("Font oversampling only works with the following resize modes 'Keep Width', 'Keep Height', and 'Expand'.") } } else if (viewport_aspect < video_mode_aspect) { // screen ratio is smaller vertically if (stretch_aspect == STRETCH_ASPECT_KEEP_HEIGHT || stretch_aspect == STRETCH_ASPECT_EXPAND) { //will stretch horizontally viewport_size.x = desired_res.y * video_mode_aspect; viewport_size.y = desired_res.y; screen_size = video_mode; } else { //will need black bars viewport_size = desired_res; screen_size.x = video_mode.y * viewport_aspect; screen_size.y = video_mode.y; } } else { //screen ratio is smaller horizontally if (stretch_aspect == STRETCH_ASPECT_KEEP_WIDTH || stretch_aspect == STRETCH_ASPECT_EXPAND) { //will stretch horizontally viewport_size.x = desired_res.x; viewport_size.y = desired_res.x / video_mode_aspect; screen_size = video_mode; } else { //will need black bars viewport_size = desired_res; screen_size.x = video_mode.x; screen_size.y = video_mode.x / viewport_aspect; } } screen_size = screen_size.floor(); viewport_size = viewport_size.floor(); Size2 margin; Size2 offset; //black bars and margin if (stretch_aspect != STRETCH_ASPECT_EXPAND && screen_size.x < video_mode.x) { margin.x = Math::round((video_mode.x - screen_size.x) / 2.0); VisualServer::get_singleton()->black_bars_set_margins(margin.x, 0, margin.x, 0); offset.x = Math::round(margin.x * viewport_size.y / screen_size.y); } else if (stretch_aspect != STRETCH_ASPECT_EXPAND && screen_size.y < video_mode.y) { margin.y = Math::round((video_mode.y - screen_size.y) / 2.0); VisualServer::get_singleton()->black_bars_set_margins(0, margin.y, 0, margin.y); offset.y = Math::round(margin.y * viewport_size.x / screen_size.x); } else { VisualServer::get_singleton()->black_bars_set_margins(0, 0, 0, 0); } switch (stretch_mode) { case STRETCH_MODE_DISABLED: { // Already handled above _update_font_oversampling(1.0); } break; case STRETCH_MODE_2D: { _update_font_oversampling(screen_size.x / viewport_size.x); //screen / viewport radio drives oversampling root->set_size((screen_size / stretch_shrink).floor()); root->set_attach_to_screen_rect(Rect2(margin, screen_size)); root->set_size_override_stretch(true); root->set_size_override(true, (viewport_size / stretch_shrink).floor()); root->update_canvas_items(); //force them to update just in case } break; case STRETCH_MODE_VIEWPORT: { _update_font_oversampling(1.0); root->set_size((viewport_size / stretch_shrink).floor()); root->set_attach_to_screen_rect(Rect2(margin, screen_size)); root->set_size_override_stretch(false); root->set_size_override(false, Size2()); root->update_canvas_items(); //force them to update just in case if (use_font_oversampling) { WARN_PRINT("Font oversampling does not work in 'Viewport' stretch mode, only '2D'.") } } break; } } void SceneTree::set_screen_stretch(StretchMode p_mode, StretchAspect p_aspect, const Size2 p_minsize, real_t p_shrink) { stretch_mode = p_mode; stretch_aspect = p_aspect; stretch_min = p_minsize; stretch_shrink = p_shrink; _update_root_rect(); } void SceneTree::set_edited_scene_root(Node *p_node) { #ifdef TOOLS_ENABLED edited_scene_root = p_node; #endif } Node *SceneTree::get_edited_scene_root() const { #ifdef TOOLS_ENABLED return edited_scene_root; #else return NULL; #endif } void SceneTree::set_current_scene(Node *p_scene) { ERR_FAIL_COND(p_scene && p_scene->get_parent() != root); current_scene = p_scene; } Node *SceneTree::get_current_scene() const { return current_scene; } void SceneTree::_change_scene(Node *p_to) { if (current_scene) { memdelete(current_scene); current_scene = NULL; } if (p_to) { current_scene = p_to; root->add_child(p_to); } } Error SceneTree::change_scene(const String &p_path) { Ref<PackedScene> new_scene = ResourceLoader::load(p_path); if (new_scene.is_null()) return ERR_CANT_OPEN; return change_scene_to(new_scene); } Error SceneTree::change_scene_to(const Ref<PackedScene> &p_scene) { Node *new_scene = NULL; if (p_scene.is_valid()) { new_scene = p_scene->instance(); ERR_FAIL_COND_V(!new_scene, ERR_CANT_CREATE); } call_deferred("_change_scene", new_scene); return OK; } Error SceneTree::reload_current_scene() { ERR_FAIL_COND_V(!current_scene, ERR_UNCONFIGURED); String fname = current_scene->get_filename(); return change_scene(fname); } void SceneTree::add_current_scene(Node *p_current) { current_scene = p_current; root->add_child(p_current); } #ifdef DEBUG_ENABLED void SceneTree::_live_edit_node_path_func(const NodePath &p_path, int p_id) { live_edit_node_path_cache[p_id] = p_path; } void SceneTree::_live_edit_res_path_func(const String &p_path, int p_id) { live_edit_resource_cache[p_id] = p_path; } void SceneTree::_live_edit_node_set_func(int p_id, const StringName &p_prop, const Variant &p_value) { if (!live_edit_node_path_cache.has(p_id)) return; NodePath np = live_edit_node_path_cache[p_id]; Node *base = NULL; if (root->has_node(live_edit_root)) base = root->get_node(live_edit_root); Map<String, Set<Node *> >::Element *E = live_scene_edit_cache.find(live_edit_scene); if (!E) return; //scene not editable for (Set<Node *>::Element *F = E->get().front(); F; F = F->next()) { Node *n = F->get(); if (base && !base->is_a_parent_of(n)) continue; if (!n->has_node(np)) continue; Node *n2 = n->get_node(np); n2->set(p_prop, p_value); } } void SceneTree::_live_edit_node_set_res_func(int p_id, const StringName &p_prop, const String &p_value) { RES r = ResourceLoader::load(p_value); if (!r.is_valid()) return; _live_edit_node_set_func(p_id, p_prop, r); } void SceneTree::_live_edit_node_call_func(int p_id, const StringName &p_method, VARIANT_ARG_DECLARE) { if (!live_edit_node_path_cache.has(p_id)) return; NodePath np = live_edit_node_path_cache[p_id]; Node *base = NULL; if (root->has_node(live_edit_root)) base = root->get_node(live_edit_root); Map<String, Set<Node *> >::Element *E = live_scene_edit_cache.find(live_edit_scene); if (!E) return; //scene not editable for (Set<Node *>::Element *F = E->get().front(); F; F = F->next()) { Node *n = F->get(); if (base && !base->is_a_parent_of(n)) continue; if (!n->has_node(np)) continue; Node *n2 = n->get_node(np); n2->call(p_method, VARIANT_ARG_PASS); } } void SceneTree::_live_edit_res_set_func(int p_id, const StringName &p_prop, const Variant &p_value) { if (!live_edit_resource_cache.has(p_id)) return; String resp = live_edit_resource_cache[p_id]; if (!ResourceCache::has(resp)) return; RES r = ResourceCache::get(resp); if (!r.is_valid()) return; r->set(p_prop, p_value); } void SceneTree::_live_edit_res_set_res_func(int p_id, const StringName &p_prop, const String &p_value) { RES r = ResourceLoader::load(p_value); if (!r.is_valid()) return; _live_edit_res_set_func(p_id, p_prop, r); } void SceneTree::_live_edit_res_call_func(int p_id, const StringName &p_method, VARIANT_ARG_DECLARE) { if (!live_edit_resource_cache.has(p_id)) return; String resp = live_edit_resource_cache[p_id]; if (!ResourceCache::has(resp)) return; RES r = ResourceCache::get(resp); if (!r.is_valid()) return; r->call(p_method, VARIANT_ARG_PASS); } void SceneTree::_live_edit_root_func(const NodePath &p_scene_path, const String &p_scene_from) { live_edit_root = p_scene_path; live_edit_scene = p_scene_from; } void SceneTree::_live_edit_create_node_func(const NodePath &p_parent, const String &p_type, const String &p_name) { Node *base = NULL; if (root->has_node(live_edit_root)) base = root->get_node(live_edit_root); Map<String, Set<Node *> >::Element *E = live_scene_edit_cache.find(live_edit_scene); if (!E) return; //scene not editable for (Set<Node *>::Element *F = E->get().front(); F; F = F->next()) { Node *n = F->get(); if (base && !base->is_a_parent_of(n)) continue; if (!n->has_node(p_parent)) continue; Node *n2 = n->get_node(p_parent); Node *no = Object::cast_to<Node>(ClassDB::instance(p_type)); if (!no) { continue; } no->set_name(p_name); n2->add_child(no); } } void SceneTree::_live_edit_instance_node_func(const NodePath &p_parent, const String &p_path, const String &p_name) { Ref<PackedScene> ps = ResourceLoader::load(p_path); if (!ps.is_valid()) return; Node *base = NULL; if (root->has_node(live_edit_root)) base = root->get_node(live_edit_root); Map<String, Set<Node *> >::Element *E = live_scene_edit_cache.find(live_edit_scene); if (!E) return; //scene not editable for (Set<Node *>::Element *F = E->get().front(); F; F = F->next()) { Node *n = F->get(); if (base && !base->is_a_parent_of(n)) continue; if (!n->has_node(p_parent)) continue; Node *n2 = n->get_node(p_parent); Node *no = ps->instance(); no->set_name(p_name); n2->add_child(no); } } void SceneTree::_live_edit_remove_node_func(const NodePath &p_at) { Node *base = NULL; if (root->has_node(live_edit_root)) base = root->get_node(live_edit_root); Map<String, Set<Node *> >::Element *E = live_scene_edit_cache.find(live_edit_scene); if (!E) return; //scene not editable for (Set<Node *>::Element *F = E->get().front(); F;) { Set<Node *>::Element *N = F->next(); Node *n = F->get(); if (base && !base->is_a_parent_of(n)) continue; if (!n->has_node(p_at)) continue; Node *n2 = n->get_node(p_at); memdelete(n2); F = N; } } void SceneTree::_live_edit_remove_and_keep_node_func(const NodePath &p_at, ObjectID p_keep_id) { Node *base = NULL; if (root->has_node(live_edit_root)) base = root->get_node(live_edit_root); Map<String, Set<Node *> >::Element *E = live_scene_edit_cache.find(live_edit_scene); if (!E) return; //scene not editable for (Set<Node *>::Element *F = E->get().front(); F;) { Set<Node *>::Element *N = F->next(); Node *n = F->get(); if (base && !base->is_a_parent_of(n)) continue; if (!n->has_node(p_at)) continue; Node *n2 = n->get_node(p_at); n2->get_parent()->remove_child(n2); live_edit_remove_list[n][p_keep_id] = n2; F = N; } } void SceneTree::_live_edit_restore_node_func(ObjectID p_id, const NodePath &p_at, int p_at_pos) { Node *base = NULL; if (root->has_node(live_edit_root)) base = root->get_node(live_edit_root); Map<String, Set<Node *> >::Element *E = live_scene_edit_cache.find(live_edit_scene); if (!E) return; //scene not editable for (Set<Node *>::Element *F = E->get().front(); F;) { Set<Node *>::Element *N = F->next(); Node *n = F->get(); if (base && !base->is_a_parent_of(n)) continue; if (!n->has_node(p_at)) continue; Node *n2 = n->get_node(p_at); Map<Node *, Map<ObjectID, Node *> >::Element *EN = live_edit_remove_list.find(n); if (!EN) continue; Map<ObjectID, Node *>::Element *FN = EN->get().find(p_id); if (!FN) continue; n2->add_child(FN->get()); EN->get().erase(FN); if (EN->get().size() == 0) { live_edit_remove_list.erase(EN); } F = N; } } void SceneTree::_live_edit_duplicate_node_func(const NodePath &p_at, const String &p_new_name) { Node *base = NULL; if (root->has_node(live_edit_root)) base = root->get_node(live_edit_root); Map<String, Set<Node *> >::Element *E = live_scene_edit_cache.find(live_edit_scene); if (!E) return; //scene not editable for (Set<Node *>::Element *F = E->get().front(); F; F = F->next()) { Node *n = F->get(); if (base && !base->is_a_parent_of(n)) continue; if (!n->has_node(p_at)) continue; Node *n2 = n->get_node(p_at); Node *dup = n2->duplicate(Node::DUPLICATE_SIGNALS | Node::DUPLICATE_GROUPS | Node::DUPLICATE_SCRIPTS); if (!dup) continue; dup->set_name(p_new_name); n2->get_parent()->add_child(dup); } } void SceneTree::_live_edit_reparent_node_func(const NodePath &p_at, const NodePath &p_new_place, const String &p_new_name, int p_at_pos) { Node *base = NULL; if (root->has_node(live_edit_root)) base = root->get_node(live_edit_root); Map<String, Set<Node *> >::Element *E = live_scene_edit_cache.find(live_edit_scene); if (!E) return; //scene not editable for (Set<Node *>::Element *F = E->get().front(); F; F = F->next()) { Node *n = F->get(); if (base && !base->is_a_parent_of(n)) continue; if (!n->has_node(p_at)) continue; Node *nfrom = n->get_node(p_at); if (!n->has_node(p_new_place)) continue; Node *nto = n->get_node(p_new_place); nfrom->get_parent()->remove_child(nfrom); nfrom->set_name(p_new_name); nto->add_child(nfrom); if (p_at_pos >= 0) nto->move_child(nfrom, p_at_pos); } } #endif void SceneTree::drop_files(const Vector<String> &p_files, int p_from_screen) { emit_signal("files_dropped", p_files, p_from_screen); MainLoop::drop_files(p_files, p_from_screen); } Ref<SceneTreeTimer> SceneTree::create_timer(float p_delay_sec, bool p_process_pause) { Ref<SceneTreeTimer> stt; stt.instance(); stt->set_pause_mode_process(p_process_pause); stt->set_time_left(p_delay_sec); timers.push_back(stt); return stt; } void SceneTree::_network_peer_connected(int p_id) { emit_signal("network_peer_connected", p_id); } void SceneTree::_network_peer_disconnected(int p_id) { emit_signal("network_peer_disconnected", p_id); } void SceneTree::_connected_to_server() { emit_signal("connected_to_server"); } void SceneTree::_connection_failed() { emit_signal("connection_failed"); } void SceneTree::_server_disconnected() { emit_signal("server_disconnected"); } Ref<MultiplayerAPI> SceneTree::get_multiplayer() const { return multiplayer; } void SceneTree::set_multiplayer_poll_enabled(bool p_enabled) { multiplayer_poll = p_enabled; } bool SceneTree::is_multiplayer_poll_enabled() const { return multiplayer_poll; } void SceneTree::set_multiplayer(Ref<MultiplayerAPI> p_multiplayer) { ERR_FAIL_COND(!p_multiplayer.is_valid()); if (multiplayer.is_valid()) { multiplayer->disconnect("network_peer_connected", this, "_network_peer_connected"); multiplayer->disconnect("network_peer_disconnected", this, "_network_peer_disconnected"); multiplayer->disconnect("connected_to_server", this, "_connected_to_server"); multiplayer->disconnect("connection_failed", this, "_connection_failed"); multiplayer->disconnect("server_disconnected", this, "_server_disconnected"); } multiplayer = p_multiplayer; multiplayer->set_root_node(root); multiplayer->connect("network_peer_connected", this, "_network_peer_connected"); multiplayer->connect("network_peer_disconnected", this, "_network_peer_disconnected"); multiplayer->connect("connected_to_server", this, "_connected_to_server"); multiplayer->connect("connection_failed", this, "_connection_failed"); multiplayer->connect("server_disconnected", this, "_server_disconnected"); } void SceneTree::set_network_peer(const Ref<NetworkedMultiplayerPeer> &p_network_peer) { multiplayer->set_network_peer(p_network_peer); } Ref<NetworkedMultiplayerPeer> SceneTree::get_network_peer() const { return multiplayer->get_network_peer(); } bool SceneTree::is_network_server() const { return multiplayer->is_network_server(); } bool SceneTree::has_network_peer() const { return multiplayer->has_network_peer(); } int SceneTree::get_network_unique_id() const { return multiplayer->get_network_unique_id(); } Vector<int> SceneTree::get_network_connected_peers() const { return multiplayer->get_network_connected_peers(); } int SceneTree::get_rpc_sender_id() const { return multiplayer->get_rpc_sender_id(); } void SceneTree::set_refuse_new_network_connections(bool p_refuse) { multiplayer->set_refuse_new_network_connections(p_refuse); } bool SceneTree::is_refusing_new_network_connections() const { return multiplayer->is_refusing_new_network_connections(); } void SceneTree::_bind_methods() { //ClassDB::bind_method(D_METHOD("call_group","call_flags","group","method","arg1","arg2"),&SceneMainLoop::_call_group,DEFVAL(Variant()),DEFVAL(Variant())); ClassDB::bind_method(D_METHOD("get_root"), &SceneTree::get_root); ClassDB::bind_method(D_METHOD("has_group", "name"), &SceneTree::has_group); ClassDB::bind_method(D_METHOD("set_auto_accept_quit", "enabled"), &SceneTree::set_auto_accept_quit); ClassDB::bind_method(D_METHOD("set_quit_on_go_back", "enabled"), &SceneTree::set_quit_on_go_back); ClassDB::bind_method(D_METHOD("set_debug_collisions_hint", "enable"), &SceneTree::set_debug_collisions_hint); ClassDB::bind_method(D_METHOD("is_debugging_collisions_hint"), &SceneTree::is_debugging_collisions_hint); ClassDB::bind_method(D_METHOD("set_debug_navigation_hint", "enable"), &SceneTree::set_debug_navigation_hint); ClassDB::bind_method(D_METHOD("is_debugging_navigation_hint"), &SceneTree::is_debugging_navigation_hint); ClassDB::bind_method(D_METHOD("set_edited_scene_root", "scene"), &SceneTree::set_edited_scene_root); ClassDB::bind_method(D_METHOD("get_edited_scene_root"), &SceneTree::get_edited_scene_root); ClassDB::bind_method(D_METHOD("set_pause", "enable"), &SceneTree::set_pause); ClassDB::bind_method(D_METHOD("is_paused"), &SceneTree::is_paused); ClassDB::bind_method(D_METHOD("set_input_as_handled"), &SceneTree::set_input_as_handled); ClassDB::bind_method(D_METHOD("is_input_handled"), &SceneTree::is_input_handled); ClassDB::bind_method(D_METHOD("create_timer", "time_sec", "pause_mode_process"), &SceneTree::create_timer, DEFVAL(true)); ClassDB::bind_method(D_METHOD("get_node_count"), &SceneTree::get_node_count); ClassDB::bind_method(D_METHOD("get_frame"), &SceneTree::get_frame); ClassDB::bind_method(D_METHOD("quit"), &SceneTree::quit); ClassDB::bind_method(D_METHOD("set_screen_stretch", "mode", "aspect", "minsize", "shrink"), &SceneTree::set_screen_stretch, DEFVAL(1)); ClassDB::bind_method(D_METHOD("queue_delete", "obj"), &SceneTree::queue_delete); MethodInfo mi; mi.name = "call_group_flags"; mi.arguments.push_back(PropertyInfo(Variant::INT, "flags")); mi.arguments.push_back(PropertyInfo(Variant::STRING, "group")); mi.arguments.push_back(PropertyInfo(Variant::STRING, "method")); ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "call_group_flags", &SceneTree::_call_group_flags, mi); ClassDB::bind_method(D_METHOD("notify_group_flags", "call_flags", "group", "notification"), &SceneTree::notify_group_flags); ClassDB::bind_method(D_METHOD("set_group_flags", "call_flags", "group", "property", "value"), &SceneTree::set_group_flags); MethodInfo mi2; mi2.name = "call_group"; mi2.arguments.push_back(PropertyInfo(Variant::STRING, "group")); mi2.arguments.push_back(PropertyInfo(Variant::STRING, "method")); ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "call_group", &SceneTree::_call_group, mi2); ClassDB::bind_method(D_METHOD("notify_group", "group", "notification"), &SceneTree::notify_group); ClassDB::bind_method(D_METHOD("set_group", "group", "property", "value"), &SceneTree::set_group); ClassDB::bind_method(D_METHOD("get_nodes_in_group", "group"), &SceneTree::_get_nodes_in_group); ClassDB::bind_method(D_METHOD("set_current_scene", "child_node"), &SceneTree::set_current_scene); ClassDB::bind_method(D_METHOD("get_current_scene"), &SceneTree::get_current_scene); ClassDB::bind_method(D_METHOD("change_scene", "path"), &SceneTree::change_scene); ClassDB::bind_method(D_METHOD("change_scene_to", "packed_scene"), &SceneTree::change_scene_to); ClassDB::bind_method(D_METHOD("reload_current_scene"), &SceneTree::reload_current_scene); ClassDB::bind_method(D_METHOD("_change_scene"), &SceneTree::_change_scene); ClassDB::bind_method(D_METHOD("set_multiplayer", "multiplayer"), &SceneTree::set_multiplayer); ClassDB::bind_method(D_METHOD("get_multiplayer"), &SceneTree::get_multiplayer); ClassDB::bind_method(D_METHOD("set_multiplayer_poll_enabled", "enabled"), &SceneTree::set_multiplayer_poll_enabled); ClassDB::bind_method(D_METHOD("is_multiplayer_poll_enabled"), &SceneTree::is_multiplayer_poll_enabled); ClassDB::bind_method(D_METHOD("set_network_peer", "peer"), &SceneTree::set_network_peer); ClassDB::bind_method(D_METHOD("get_network_peer"), &SceneTree::get_network_peer); ClassDB::bind_method(D_METHOD("is_network_server"), &SceneTree::is_network_server); ClassDB::bind_method(D_METHOD("has_network_peer"), &SceneTree::has_network_peer); ClassDB::bind_method(D_METHOD("get_network_connected_peers"), &SceneTree::get_network_connected_peers); ClassDB::bind_method(D_METHOD("get_network_unique_id"), &SceneTree::get_network_unique_id); ClassDB::bind_method(D_METHOD("get_rpc_sender_id"), &SceneTree::get_rpc_sender_id); ClassDB::bind_method(D_METHOD("set_refuse_new_network_connections", "refuse"), &SceneTree::set_refuse_new_network_connections); ClassDB::bind_method(D_METHOD("is_refusing_new_network_connections"), &SceneTree::is_refusing_new_network_connections); ClassDB::bind_method(D_METHOD("_network_peer_connected"), &SceneTree::_network_peer_connected); ClassDB::bind_method(D_METHOD("_network_peer_disconnected"), &SceneTree::_network_peer_disconnected); ClassDB::bind_method(D_METHOD("_connected_to_server"), &SceneTree::_connected_to_server); ClassDB::bind_method(D_METHOD("_connection_failed"), &SceneTree::_connection_failed); ClassDB::bind_method(D_METHOD("_server_disconnected"), &SceneTree::_server_disconnected); ClassDB::bind_method(D_METHOD("set_use_font_oversampling", "enable"), &SceneTree::set_use_font_oversampling); ClassDB::bind_method(D_METHOD("is_using_font_oversampling"), &SceneTree::is_using_font_oversampling); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "debug_collisions_hint"), "set_debug_collisions_hint", "is_debugging_collisions_hint"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "debug_navigation_hint"), "set_debug_navigation_hint", "is_debugging_navigation_hint"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "paused"), "set_pause", "is_paused"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "refuse_new_network_connections"), "set_refuse_new_network_connections", "is_refusing_new_network_connections"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "use_font_oversampling"), "set_use_font_oversampling", "is_using_font_oversampling"); ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "edited_scene_root", PROPERTY_HINT_RESOURCE_TYPE, "Node", 0), "set_edited_scene_root", "get_edited_scene_root"); ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "current_scene", PROPERTY_HINT_RESOURCE_TYPE, "Node", 0), "set_current_scene", "get_current_scene"); ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "network_peer", PROPERTY_HINT_RESOURCE_TYPE, "NetworkedMultiplayerPeer", 0), "set_network_peer", "get_network_peer"); ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "root", PROPERTY_HINT_RESOURCE_TYPE, "Node", 0), "", "get_root"); ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "multiplayer", PROPERTY_HINT_RESOURCE_TYPE, "MultiplayerAPI", 0), "set_multiplayer", "get_multiplayer"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "multiplayer_poll"), "set_multiplayer_poll_enabled", "is_multiplayer_poll_enabled"); ADD_SIGNAL(MethodInfo("tree_changed")); ADD_SIGNAL(MethodInfo("node_added", PropertyInfo(Variant::OBJECT, "node", PROPERTY_HINT_RESOURCE_TYPE, "Node"))); ADD_SIGNAL(MethodInfo("node_removed", PropertyInfo(Variant::OBJECT, "node", PROPERTY_HINT_RESOURCE_TYPE, "Node"))); ADD_SIGNAL(MethodInfo("screen_resized")); ADD_SIGNAL(MethodInfo("node_configuration_warning_changed", PropertyInfo(Variant::OBJECT, "node", PROPERTY_HINT_RESOURCE_TYPE, "Node"))); ADD_SIGNAL(MethodInfo("idle_frame")); ADD_SIGNAL(MethodInfo("physics_frame")); ADD_SIGNAL(MethodInfo("files_dropped", PropertyInfo(Variant::POOL_STRING_ARRAY, "files"), PropertyInfo(Variant::INT, "screen"))); ADD_SIGNAL(MethodInfo("network_peer_connected", PropertyInfo(Variant::INT, "id"))); ADD_SIGNAL(MethodInfo("network_peer_disconnected", PropertyInfo(Variant::INT, "id"))); ADD_SIGNAL(MethodInfo("connected_to_server")); ADD_SIGNAL(MethodInfo("connection_failed")); ADD_SIGNAL(MethodInfo("server_disconnected")); BIND_ENUM_CONSTANT(GROUP_CALL_DEFAULT); BIND_ENUM_CONSTANT(GROUP_CALL_REVERSE); BIND_ENUM_CONSTANT(GROUP_CALL_REALTIME); BIND_ENUM_CONSTANT(GROUP_CALL_UNIQUE); BIND_ENUM_CONSTANT(STRETCH_MODE_DISABLED); BIND_ENUM_CONSTANT(STRETCH_MODE_2D); BIND_ENUM_CONSTANT(STRETCH_MODE_VIEWPORT); BIND_ENUM_CONSTANT(STRETCH_ASPECT_IGNORE); BIND_ENUM_CONSTANT(STRETCH_ASPECT_KEEP); BIND_ENUM_CONSTANT(STRETCH_ASPECT_KEEP_WIDTH); BIND_ENUM_CONSTANT(STRETCH_ASPECT_KEEP_HEIGHT); BIND_ENUM_CONSTANT(STRETCH_ASPECT_EXPAND); } SceneTree *SceneTree::singleton = NULL; SceneTree::IdleCallback SceneTree::idle_callbacks[SceneTree::MAX_IDLE_CALLBACKS]; int SceneTree::idle_callback_count = 0; void SceneTree::_call_idle_callbacks() { for (int i = 0; i < idle_callback_count; i++) { idle_callbacks[i](); } } void SceneTree::add_idle_callback(IdleCallback p_callback) { ERR_FAIL_COND(idle_callback_count >= MAX_IDLE_CALLBACKS); idle_callbacks[idle_callback_count++] = p_callback; } void SceneTree::set_use_font_oversampling(bool p_oversampling) { if (use_font_oversampling == p_oversampling) return; use_font_oversampling = p_oversampling; _update_root_rect(); } bool SceneTree::is_using_font_oversampling() const { return use_font_oversampling; } SceneTree::SceneTree() { singleton = this; _quit = false; accept_quit = true; quit_on_go_back = true; initialized = false; use_font_oversampling = false; #ifdef DEBUG_ENABLED debug_collisions_hint = false; debug_navigation_hint = false; #endif debug_collisions_color = GLOBAL_DEF("debug/shapes/collision/shape_color", Color(0.0, 0.6, 0.7, 0.5)); debug_collision_contact_color = GLOBAL_DEF("debug/shapes/collision/contact_color", Color(1.0, 0.2, 0.1, 0.8)); debug_navigation_color = GLOBAL_DEF("debug/shapes/navigation/geometry_color", Color(0.1, 1.0, 0.7, 0.4)); debug_navigation_disabled_color = GLOBAL_DEF("debug/shapes/navigation/disabled_geometry_color", Color(1.0, 0.7, 0.1, 0.4)); collision_debug_contacts = GLOBAL_DEF("debug/shapes/collision/max_contacts_displayed", 10000); ProjectSettings::get_singleton()->set_custom_property_info("debug/shapes/collision/max_contacts_displayed", PropertyInfo(Variant::INT, "debug/shapes/collision/max_contacts_displayed", PROPERTY_HINT_RANGE, "0,20000,1")); // No negative tree_version = 1; physics_process_time = 1; idle_process_time = 1; root = NULL; current_frame = 0; current_event = 0; tree_changed_name = "tree_changed"; node_added_name = "node_added"; node_removed_name = "node_removed"; ugc_locked = false; call_lock = 0; root_lock = 0; node_count = 0; //create with mainloop root = memnew(Viewport); root->set_name("root"); root->set_handle_input_locally(false); if (!root->get_world().is_valid()) root->set_world(Ref<World>(memnew(World))); // Initialize network state multiplayer_poll = true; set_multiplayer(Ref<MultiplayerAPI>(memnew(MultiplayerAPI))); //root->set_world_2d( Ref<World2D>( memnew( World2D ))); root->set_as_audio_listener(true); root->set_as_audio_listener_2d(true); current_scene = NULL; int ref_atlas_size = GLOBAL_DEF("rendering/quality/reflections/atlas_size", 2048); ProjectSettings::get_singleton()->set_custom_property_info("rendering/quality/reflections/atlas_size", PropertyInfo(Variant::INT, "rendering/quality/reflections/atlas_size", PROPERTY_HINT_RANGE, "0,8192,or_greater")); //next_power_of_2 will return a 0 as min value int ref_atlas_subdiv = GLOBAL_DEF("rendering/quality/reflections/atlas_subdiv", 8); ProjectSettings::get_singleton()->set_custom_property_info("rendering/quality/reflections/atlas_subdiv", PropertyInfo(Variant::INT, "rendering/quality/reflections/atlas_subdiv", PROPERTY_HINT_RANGE, "0,32,or_greater")); //next_power_of_2 will return a 0 as min value int msaa_mode = GLOBAL_DEF("rendering/quality/filters/msaa", 0); ProjectSettings::get_singleton()->set_custom_property_info("rendering/quality/filters/msaa", PropertyInfo(Variant::INT, "rendering/quality/filters/msaa", PROPERTY_HINT_ENUM, "Disabled,2x,4x,8x,16x")); root->set_msaa(Viewport::MSAA(msaa_mode)); GLOBAL_DEF("rendering/quality/depth/hdr", true); GLOBAL_DEF("rendering/quality/depth/hdr.mobile", false); bool hdr = GLOBAL_GET("rendering/quality/depth/hdr"); root->set_hdr(hdr); VS::get_singleton()->scenario_set_reflection_atlas_size(root->get_world()->get_scenario(), ref_atlas_size, ref_atlas_subdiv); { //load default fallback environment //get possible extensions List<String> exts; ResourceLoader::get_recognized_extensions_for_type("Environment", &exts); String ext_hint; for (List<String>::Element *E = exts.front(); E; E = E->next()) { if (ext_hint != String()) ext_hint += ","; ext_hint += "*." + E->get(); } //get path String env_path = GLOBAL_DEF("rendering/environment/default_environment", ""); //setup property ProjectSettings::get_singleton()->set_custom_property_info("rendering/environment/default_environment", PropertyInfo(Variant::STRING, "rendering/viewport/default_environment", PROPERTY_HINT_FILE, ext_hint)); env_path = env_path.strip_edges(); if (env_path != String()) { Ref<Environment> env = ResourceLoader::load(env_path); if (env.is_valid()) { root->get_world()->set_fallback_environment(env); } else { if (Engine::get_singleton()->is_editor_hint()) { //file was erased, clear the field. ProjectSettings::get_singleton()->set("rendering/environment/default_environment", ""); } else { //file was erased, notify user. ERR_PRINTS(RTR("Default Environment as specified in Project Settings (Rendering -> Environment -> Default Environment) could not be loaded.")); } } } } stretch_mode = STRETCH_MODE_DISABLED; stretch_aspect = STRETCH_ASPECT_IGNORE; stretch_shrink = 1; last_screen_size = Size2(OS::get_singleton()->get_window_size().width, OS::get_singleton()->get_window_size().height); _update_root_rect(); if (ScriptDebugger::get_singleton()) { ScriptDebugger::get_singleton()->set_request_scene_tree_message_func(_debugger_request_tree, this); } root->set_physics_object_picking(GLOBAL_DEF("physics/common/enable_object_picking", true)); #ifdef TOOLS_ENABLED edited_scene_root = NULL; #endif #ifdef DEBUG_ENABLED live_edit_funcs.udata = this; live_edit_funcs.node_path_func = _live_edit_node_path_funcs; live_edit_funcs.res_path_func = _live_edit_res_path_funcs; live_edit_funcs.node_set_func = _live_edit_node_set_funcs; live_edit_funcs.node_set_res_func = _live_edit_node_set_res_funcs; live_edit_funcs.node_call_func = _live_edit_node_call_funcs; live_edit_funcs.res_set_func = _live_edit_res_set_funcs; live_edit_funcs.res_set_res_func = _live_edit_res_set_res_funcs; live_edit_funcs.res_call_func = _live_edit_res_call_funcs; live_edit_funcs.root_func = _live_edit_root_funcs; live_edit_funcs.tree_create_node_func = _live_edit_create_node_funcs; live_edit_funcs.tree_instance_node_func = _live_edit_instance_node_funcs; live_edit_funcs.tree_remove_node_func = _live_edit_remove_node_funcs; live_edit_funcs.tree_remove_and_keep_node_func = _live_edit_remove_and_keep_node_funcs; live_edit_funcs.tree_restore_node_func = _live_edit_restore_node_funcs; live_edit_funcs.tree_duplicate_node_func = _live_edit_duplicate_node_funcs; live_edit_funcs.tree_reparent_node_func = _live_edit_reparent_node_funcs; if (ScriptDebugger::get_singleton()) { ScriptDebugger::get_singleton()->set_live_edit_funcs(&live_edit_funcs); } live_edit_root = NodePath("/root"); #endif } SceneTree::~SceneTree() { }
// Copyright (c) 2016/17/18/19/20/21/22 Leandro T. C. Melo <ltcmelo@gmail.com> // Copyright (c) 2008 Roberto Raggi <roberto.raggi@gmail.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #include "SyntaxKind.h" #include "SyntaxNodes.h" #include "SyntaxVisitor.h" #include <algorithm> #include <cstddef> using namespace psy; using namespace C; SyntaxNode::SyntaxNode(SyntaxTree* tree, SyntaxKind kind) : tree_(tree) , kind_(kind) {} SyntaxNode::~SyntaxNode() {} const SyntaxTree* SyntaxNode::syntaxTree() const { return tree_; } SyntaxKind SyntaxNode::kind() const { return kind_; } SyntaxToken SyntaxNode::firstToken() const { return findValidToken(childNodesAndTokens()); } SyntaxToken SyntaxNode::lastToken() const { auto reversed = childNodesAndTokens(); std::reverse(reversed.begin(), reversed.end()); return findValidToken(reversed); } SyntaxToken SyntaxNode::findValidToken(const std::vector<SyntaxHolder>& syntaxHolders) const { for (const auto& synH : syntaxHolders) { switch (synH.variant()) { case SyntaxHolder::Variant::Token: if (synH.tokenIndex() != LexedTokens::invalidIndex()) return tokenAtIndex(synH.tokenIndex()); break; case SyntaxHolder::Variant::Node: if (synH.node()) { auto tk = synH.node()->firstToken(); if (tk != SyntaxToken::invalid()) return tk; } break; case SyntaxHolder::Variant::NodeList: if (synH.nodeList()) { auto tk = synH.nodeList()->firstToken(); if (tk != SyntaxToken::invalid()) return tk; } break; } } return 0; } SyntaxToken SyntaxNode::tokenAtIndex(LexedTokens::IndexType tkIdx) const { if (tkIdx == 0) return SyntaxToken::invalid(); return tree_->tokenAt(tkIdx); } void SyntaxNode::visitChildren(SyntaxVisitor* visitor) const { for (auto synH : childNodesAndTokens()) { switch (synH.variant()) { case SyntaxHolder::Variant::Node: { if (!synH.node()) continue; auto node = const_cast<SyntaxNode*>(synH.node()); node->acceptVisitor(visitor); break; } case SyntaxHolder::Variant::NodeList: { if (!synH.nodeList()) continue; auto nodeL = const_cast<SyntaxNodeList*>(synH.nodeList()); nodeL->acceptVisitor(visitor); break; } default: break; } } } void SyntaxNode::acceptVisitor(SyntaxVisitor* visitor) const { if (visitor->preVisit(this)) { auto action = dispatchVisit(visitor); if (action == SyntaxVisitor::Action::Visit) visitChildren(visitor); } visitor->postVisit(this); } namespace psy { namespace C { extern const char* tokenNames[]; std::string PSY_C_API to_string(SyntaxKind kind) { switch (kind) { //--------------// // Declarations // //--------------// case TranslationUnit: return "TranslationUnit"; case IncompleteDeclaration: return "IncompleteDeclaration"; case StructDeclaration: return "StructDeclaration"; case UnionDeclaration: return "UnionDeclaration"; case EnumDeclaration: return "EnumDeclaration"; case EnumMemberDeclaration: return "EnumMemberDeclaration"; case VariableAndOrFunctionDeclaration: return "VariableAndOrFunctionDeclaration"; case ParameterDeclaration: return "ParameterDeclaration"; case FieldDeclaration: return "FieldDeclaration"; case StaticAssertDeclaration: return "StaticAssertDeclaration"; case FunctionDefinition: return "FunctionDefinition"; case ExtGNU_AsmStatementDeclaration: return "ExtGNU_AsmStatementDeclaration"; case ExtPSY_TemplateDeclaration: return "ExtPSY_TemplateDeclaration"; case ExtKR_ParameterDeclaration: return "ExtKR_ParameterDeclaration"; /* Specifiers */ case TypedefStorageClass: return "TypedefStorageClass"; case ExternStorageClass: return "ExternStorageClass"; case StaticStorageClass: return "StaticStorageClass"; case AutoStorageClass: return "AutoStorageClass"; case RegisterStorageClass: return "RegisterStorageClass"; case ThreadLocalStorageClass: return "ThreadLocalStorageClass"; case ConstQualifier: return "ConstQualifier"; case RestrictQualifier: return "RestrictQualifier"; case VolatileQualifier: return "VolatileQualifier"; case AtomicQualifier: return "AtomicQualifier"; case BuiltinTypeSpecifier: return "BuiltinTypeSpecifier"; case StructTypeSpecifier: return "StructTypeSpecifier"; case UnionTypeSpecifier: return "UnionTypeSpecifier"; case EnumTypeSpecifier: return "EnumTypeSpecifier"; case AtomicTypeSpecifier: return "AtomicTypeSpecifier"; case TypeDeclarationAsSpecifier: return "TypeDeclarationAsSpecifier"; case InlineSpecifier: return "InlineSpecifier"; case NoReturnSpecifier: return "NoReturnSpecifier"; case AlignmentSpecifier: return "AlignmentSpecifier"; case TypedefName: return "TypedefName"; case ExtGNU_AttributeSpecifier: return "ExtGNU_AttributeSpecifier"; case ExtGNU_Attribute: return "ExtGNU_Attribute"; case ExtGNU_AsmLabel: return "ExtGNU_AsmLabel"; case ExtGNU_Typeof: return "ExtGNU_Typeof"; /* Declarators */ case PointerDeclarator: return "PointerDeclarator"; case IdentifierDeclarator: return "IdentifierDeclarator"; case AbstractDeclarator: return "AbstractDeclarator"; case ParenthesizedDeclarator: return "ParenthesizedDeclarator"; case ArrayDeclarator: return "ArrayDeclarator"; case FunctionDeclarator: return "FunctionDeclarator"; case BitfieldDeclarator: return "BitfieldDeclarator"; case SubscriptSuffix: return "SubscriptSuffix"; case ParameterSuffix: return "ParameterSuffix"; case BitfieldDeclaratorSuffix: return "BitfieldDeclaratorSuffix"; /* Initializers */ case ExpressionInitializer: return "ExpressionInitializer"; case BraceEnclosedInitializer: return "BraceEnclosedInitializer"; case DesignatedInitializer: return "DesignatedInitializer"; case FieldDesignator: return "FieldDesignator"; case ArrayDesignator: return "ArrayDesignator"; case OffsetOfDesignator: return "OffsetOfDesignator"; //-------------// // Expressions // //-------------// case IntegerConstantExpression: return "IntegerConstantExpression"; case FloatingConstantExpression: return "FloatingConstantExpression"; case CharacterConstantExpression: return "CharacterConstantExpression"; case ImaginaryIntegerConstantExpression: return "ImaginaryIntegerConstantExpression"; case ImaginaryFloatingConstantExpression: return "ImaginaryFloatingConstantExpression"; case BooleanConstantExpression: return "BooleanLiteralExpression"; case NULL_ConstantExpression: return "NULL_ConstantExpression"; case StringLiteralExpression: return "StringLiteralExpression"; case ParenthesizedExpression: return "ParenthesizedExpression"; case GenericSelectionExpression: return "GenericSelectionExpression"; case TypedGenericAssociation: return "GenericTypenameAssociation"; case DefaultGenericAssociation: return "GenericDefaultAssociation"; case ExtGNU_EnclosedCompoundStatementExpression: return "ExtGNU_EnclosedCompoundStatementExpression"; case ExtGNU_ComplexValuedExpression: return "ExtGNU_ComplexValuedExpression"; case ExtGNU_RealExpression: return "ExtGNU_RealExpression"; case ExtGNU_ImagExpression: return "ExtGNU_ImagExpression"; /* Names */ case IdentifierName: return "IdentifierName"; case PredefinedName: return "PredefinedName"; /* Unary */ case PreIncrementExpression: return "PreIncrementExpression"; case PreDecrementExpression: return "PreDecrementExpression"; case PostIncrementExpression: return "PostIncrementExpression"; case PostDecrementExpression: return "PostDecrementExpression"; case UnaryPlusExpression: return "UnaryPlusExpression"; case UnaryMinusExpression: return "UnaryMinusExpression"; case BitwiseNotExpression: return "BitwiseNotExpression"; case LogicalNotExpression: return "LogicalNotExpression"; /* Type trait */ case SizeofExpression: return "SizeofExpression"; case AlignofExpression: return "AlignofExpression"; /* Pointers */ case AddressOfExpression: return "AddressOfExpression"; case PointerIndirectionExpression: return "PointerIndirectionExpression"; /* Access */ case DirectMemberAccessExpression: return "DirectMemberAccessExpression"; case IndirectMemberAccessExpression: return "IndirectMemberAccessExpression"; case ElementAccessExpression: return "ElementAccessExpression"; /* Invocation-like */ case CallExpression: return "CallExpression"; case CompoundLiteralExpression: return "CompoundLiteralExpression"; case CastExpression: return "CastExpression"; case VAArgumentExpression: return "VAArgumentExpression"; case OffsetOfExpression: return "OffsetOfExpression"; case ExtGNU_ChooseExpression: return "ExtGNU_ChooseExpression"; /* Binary */ case MultiplyExpression: return "MultipliyExpression"; case DivideExpression: return "DivideExpression"; case ModuleExpression: return "ModuleExpression"; case AddExpression: return "AddExpression"; case SubstractExpression: return "SubstractExpression"; case LeftShiftExpression: return "LeftShiftExpression"; case RightShiftExpression: return "RightShiftExpression"; case LessThanExpression: return "LessThanExpression"; case LessThanOrEqualExpression: return "LessThanOrEqualExpression"; case GreaterThanExpression: return "GreaterThanExpression"; case GreaterThanOrEqualExpression: return "GreaterThanOrEqualExpression"; case EqualsExpression: return "EqualsExpression"; case NotEqualsExpression: return "NotEqualsExpression"; case BitwiseANDExpression: return "BitwiseExpression"; case BitwiseXORExpression: return "ExclusiveOrExpression"; case BitwiseORExpression: return "BitwiseOrExpression"; case LogicalANDExpression: return "LogicalAndExpression"; case LogicalORExpression: return "LogicalOrExpression"; case ConditionalExpression: return "ConditionalExpression"; /* Assignment */ case BasicAssignmentExpression: return "BasicAssignmentExpression"; case MultiplyAssignmentExpression: return "MultiplyAssignmentExpression"; case DivideAssignmentExpression: return "DivideAssignmentExpression"; case ModuloAssignmentExpression: return "ModuloAssignmentExpression"; case AddAssignmentExpression: return "AddAssignmentExpression"; case SubtractAssignmentExpression: return "SubtractAssignmentExpression"; case LeftShiftAssignmentExpression: return "LeftShiftAssignmentExpression"; case RightShiftAssignmentExpression: return "RightShiftAssignmentExpression"; case AndAssignmentExpression: return "AndAssignmentExpression"; case ExclusiveOrAssignmentExpression: return "ExclusiveOrAssignmentExpression"; case OrAssignmentExpression: return "OrAssignmentExpression"; /* Sequencing */ case SequencingExpression: return "SequencingExpression"; //------------// // Statements // //------------// case CompoundStatement: return "CompoundStatement"; case DeclarationStatement: return "DeclarationStatement"; case ExpressionStatement: return "ExpressionStatement"; case IdentifierLabelStatement: return "IdentifierLabelStatement"; case DefaultLabelStatement: return "DefaultLabelStatement"; case CaseLabelStatement: return "CaseLabelStatement"; case DefaultStatement: return "DefaultStatement"; case IfStatement: return "IfStatement"; case SwitchStatement: return "SwitchStatement"; case WhileStatement: return "WhileStatement"; case DoStatement: return "DoStatement"; case ForStatement: return "ForStatement"; case GotoStatement: return "GotoStatement"; case ContinueStatement: return "ContinueStatement"; case BreakStatement: return "BreakStatement"; case ReturnStatement: return "ReturnStatement"; case ExtGNU_AsmStatement: return "ExtGNU_AsmStatement"; case ExtGNU_AsmVolatileQualifier: return "ExtGNU_AsmVolatileQualifier"; case ExtGNU_AsmInlineQualifier: return "ExtGNU_AsmInlineQualifier"; case ExtGNU_AsmGotoQualifier: return "ExtGNU_AsmGotoQualifier"; case ExtGNU_AsmInputOperand: return "ExtGNU_AsmInputOperand"; case ExtGNU_AsmOutputOperand: return "ExtGNU_AsmOutputOperand"; //--------// // Common // //--------// case TypeName: return "TypeName"; case ExpressionAsTypeReference: return "ExpressionAsTypeReference"; case TypeNameAsTypeReference: return "TypeNameAsTypeReference"; //-------------// // Ambiguities // //-------------// case AmbiguousTypeNameOrExpressionAsTypeReference: return "AmbiguousTypeNameOrExpressionAsTypeReference"; case AmbiguousCastOrBinaryExpression: return "AmbiguousCastOrBinaryExpression"; case AmbiguousCallOrVariableDeclaration: return "AmbiguousCallOrVariableDeclaration"; case AmbiguousMultiplicationOrPointerDeclaration: return "AmbiguousCallOrVariableDeclaration"; //=================================================================== Misc case UnknownSyntax: return "<UNKNOWN>"; default: return tokenNames[kind]; } } } // C } // psy
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/xla/pjrt/interpreter_device.h" #include "absl/strings/str_cat.h" #include "tensorflow/compiler/xla/client/client_library.h" #include "tensorflow/compiler/xla/service/platform_util.h" namespace xla { static const char kInterpreterPlatformName[] = "interpreter"; InterpreterDevice::InterpreterDevice( int id, std::unique_ptr<LocalDeviceState> local_device_state) : Device(id, std::move(local_device_state), kInterpreterPlatformName, /*device_kind=*/kInterpreterPlatformName) {} StatusOr<std::shared_ptr<PjRtClient>> GetInterpreterClient() { TF_ASSIGN_OR_RETURN(se::Platform * platform, PlatformUtil::GetPlatform("Interpreter")); if (platform->VisibleDeviceCount() != 1) { return FailedPrecondition( "Interpreter platform should have exactly one device."); } LocalClientOptions options; options.set_platform(platform); TF_ASSIGN_OR_RETURN(LocalClient * client, ClientLibrary::GetOrCreateLocalClient(options)); std::vector<std::unique_ptr<Device>> devices; se::StreamExecutor* executor = client->backend().stream_executor(0).ValueOrDie(); auto device_state = absl::make_unique<LocalDeviceState>( executor, client, LocalDeviceState::kSynchronous, /*asynchronous=*/false, /*allow_event_reuse=*/false); auto device = absl::make_unique<InterpreterDevice>(0, std::move(device_state)); devices.push_back(std::move(device)); return std::make_shared<PjRtClient>( kInterpreterPlatformName, client, std::move(devices), /*host_id=*/0, /*allocator=*/nullptr, /*host_memory_allocator=*/nullptr, /*should_stage_host_to_device_transfers=*/false, /*gpu_run_options=*/nullptr); } } // namespace xla
#define CATCH_CONFIG_MAIN #include <Array.h> #include <catch2/catch.hpp> using std::string; using std::vector; Array<int> one() { return std::move(Array<int>{1, 2, 3, 4, 5}); } TEST_CASE("Constructor::Fill") { REQUIRE(Array<int>(5, 1).data == vector<int>{1, 1, 1, 1, 1}); } TEST_CASE("Constructor::init list") { REQUIRE(one().data == vector<int>{1, 2, 3, 4, 5}); } TEST_CASE("Constructor::vector") { vector<int> a{1, 2, 3, 4, 5}; REQUIRE(Array<int>(a).data == a); } TEST_CASE("Constructor::vector iterator") { vector<int> a{1, 2, 3, 4, 5}; REQUIRE( Array<int>(a.begin() + 1, a.begin() + 4).data == vector<int>(a.begin() + 1, a.begin() + 4)); } TEST_CASE("Operator::[]") { auto a = one(); REQUIRE(a[0] == 1); REQUIRE(a[4] == 5); a[3] = 666; REQUIRE(a[3] == 666); } TEST_CASE("Method::pop/push/shift/unshift") { Array<int> a{0}; REQUIRE(a.size() == 1); REQUIRE(a.push(1).data == vector<int>{0, 1}); REQUIRE(a.unshift(2).data == vector<int>{2, 0, 1}); REQUIRE(a.pop() == 1); REQUIRE(a.shift() == 2); } TEST_CASE("Method::every/some/find/findIndex") { auto a = one(); auto cond = [](int el) { return !(el % 2); }; REQUIRE_FALSE(a.every(cond)); REQUIRE(*(a.find(cond)) == 2); REQUIRE(a.some(cond)); REQUIRE(a.findIndex(cond) == 1); } TEST_CASE("Method::includes") { auto a = one(); int e = 4; int ee = 6; REQUIRE(a.includes(e)); REQUIRE(a.includes(4)); REQUIRE_FALSE(a.includes(ee)); REQUIRE_FALSE(a.includes(6)); } TEST_CASE("Method::indexOf/lastIndexOf") { auto a = one(); // [1,2,3,4,5] int el = 6; REQUIRE(a.indexOf(3) == 2); REQUIRE(a.indexOf(3, 3) == -1); REQUIRE(a.indexOf(el) == -1); REQUIRE(a.indexOf(6) == -1); REQUIRE(a.lastIndexOf(3) == 2); REQUIRE(a.lastIndexOf(3, 3) == 2); REQUIRE(a.lastIndexOf(el) == -1); REQUIRE(a.lastIndexOf(6) == -1); } TEST_CASE("Method::copyWithin") { Array<char> a{'a', 'b', 'c', 'd', 'e'}; REQUIRE(a.copyWithin(0, 3, 4).data == vector<char>{'d', 'b', 'c', 'd', 'e'}); REQUIRE(a.copyWithin(1, 3).data == vector<char>{'d', 'd', 'e', 'd', 'e'}); } TEST_CASE("Method::fill") { auto a = one(); REQUIRE(a.fill(-1, 2, 4).data == vector<int>{1, 2, -1, -1, 5}); REQUIRE(a.fill(-2, 3).data == vector<int>{1, 2, -1, -2, -2}); REQUIRE(a.fill(-3).data == vector<int>{-3, -3, -3, -3, -3}); } TEST_CASE("Method::reverse") { REQUIRE(one().reverse().data == vector<int>{5, 4, 3, 2, 1}); } TEST_CASE("Method::sort") { Array<int> a{1, 1, 4, 5, 1, 4}; REQUIRE(a.sort().data == vector<int>{1, 1, 1, 4, 4, 5}); REQUIRE(a.sort([](int l, int r) { return 1.0 / l < 1.0 / r; }).data == vector<int>{5, 4, 4, 1, 1, 1}); } TEST_CASE("Method::splice") { Array<string> a{"angel", "clown", "mandarin", "sturgeon"}; REQUIRE( a.splice(2, 0, {"drum"}).data == vector<string>{"angel", "clown", "drum", "mandarin", "sturgeon"}); REQUIRE(a.splice(3, 1).data == vector<string>{"angel", "clown", "drum", "sturgeon"}); REQUIRE( a.splice(2, 1, {"trumpet"}).data == vector<string>{"angel", "clown", "trumpet", "sturgeon"}); REQUIRE( a.splice(0, 2, {"parrot", "anemone", "blue"}).data == vector<string>{"parrot", "anemone", "blue", "trumpet", "sturgeon"}); REQUIRE(a.splice(a.size() - 3, 2).data == vector<string>{"parrot", "anemone", "sturgeon"}); REQUIRE(a.splice(1).data == vector<string>{"parrot"}); } TEST_CASE("Method::from") { REQUIRE(one().from().data == one().data); } TEST_CASE("Method::concat") { Array<int> a{1, 2, 3}; Array<int> b{4, 5, 6}; Array<int> c{7, 8, 9}; REQUIRE(a.concat(b).concat(c).data == vector<int>{1, 2, 3, 4, 5, 6, 7, 8, 9}); } TEST_CASE("Method::filter") { Array<string> a{"spray", "limit", "elite", "exuberant", "destruction", "present"}; auto flt = [](const string s) { return s.length() > 6; }; auto res = a.filter(flt); REQUIRE(res.data == vector<string>{"exuberant", "destruction", "present"}); } TEST_CASE("Method::map") { auto mpr = [](int a) { return a * a; }; auto res = one().map<int>(mpr); REQUIRE(res.data == vector<int>{1, 4, 9, 16, 25}); } TEST_CASE("Method::slice") { Array<string> a{"ant", "bison", "camel", "duck", "elephant"}; REQUIRE(a.slice(2).data == vector<string>{"camel", "duck", "elephant"}); REQUIRE(a.slice(2, 4).data == vector<string>{"camel", "duck"}); REQUIRE(a.slice(1, 5).data == vector<string>{"bison", "camel", "duck", "elephant"}); } TEST_CASE("Method::reduce") { Array<int> a{1, 2, 3, 4}; auto reducer = [](int acc, int cur) -> int { return acc + cur; }; REQUIRE(a.reduce<int>(reducer, 0) == 10); REQUIRE(a.reduce<int>(reducer, 5) == 15); } TEST_CASE("Method::reduceRight") { Array<Array<int>> a{{0, 1}, {2, 3}, {4, 5}}; auto rightReducer = [](Array<int> acc, Array<int> cur) { return acc.concat(cur); }; auto res = a.reduceRight<Array<int>>(rightReducer, Array<int>{}); REQUIRE(res.data == vector<int>{4, 5, 2, 3, 0, 1}); } TEST_CASE("Method::forEach") { auto a = one(); vector<int> res; a.forEach([&res](int a) { res.push_back(a * 2); }); REQUIRE(res == vector<int>{2, 4, 6, 8, 10}); } TEST_CASE("Method::join") { REQUIRE(one().join() == "1, 2, 3, 4, 5"); REQUIRE(one().join("") == "12345"); REQUIRE(one().join("-") == "1-2-3-4-5"); }
/* Copyright 2015 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/framework/node_def_builder.h" #include <memory> #include <gtest/gtest.h> #include "tensorflow/core/framework/fake_input.h" #include "tensorflow/core/framework/node_def_util.h" #include "tensorflow/core/framework/op_def_builder.h" #include "tensorflow/core/framework/op_def_util.h" #include "tensorflow/core/lib/core/status_test_util.h" #include "tensorflow/core/platform/protobuf.h" namespace tensorflow { namespace { class NodeDefBuilderTest : public ::testing::Test { protected: // Specify an OpDef via an OpDefBuilder. void Op(const OpDefBuilder& op_def_builder) { EXPECT_OK(op_def_builder.Finalize(&op_def_)); } // Resets builder_ with a new NodeDefBuilder using the Op from the last call // to Op() above. NodeDefBuilder& Builder() { EXPECT_FALSE(op_def_.name().empty()) << "Must call Op() before Builder()"; builder_.reset(new NodeDefBuilder("n", &op_def_)); return *builder_; } // Calls Finalize() and verifies it returns success and the result matches // expectations. void ExpectSuccess(const NodeDefBuilder& builder, DataTypeSlice expected_in_types, DataTypeSlice expected_out_types, StringPiece proto) { NodeDef node_def; Status status = builder.Finalize(&node_def); EXPECT_OK(status); if (!status.ok()) return; NodeDef expected; protobuf::TextFormat::ParseFromString(strings::StrCat("name: 'n' ", proto), &expected); EXPECT_EQ(node_def.DebugString(), expected.DebugString()); DataTypeVector in_types, out_types; status = InOutTypesForNode(node_def, builder.op_def(), &in_types, &out_types); EXPECT_OK(status); if (!status.ok()) return; EXPECT_EQ(DataTypeSliceString(expected_in_types), DataTypeVectorString(in_types)); EXPECT_EQ(DataTypeSliceString(expected_out_types), DataTypeVectorString(out_types)); status = ValidateNodeDef(node_def, op_def_); EXPECT_OK(status); } // Calls Finalize() and verifies it returns an error. // Each message must appear as a substring of the error. void ExpectFailures(const NodeDefBuilder& builder, const std::vector<string>& messages) { NodeDef node_def; Status status = builder.Finalize(&node_def); EXPECT_FALSE(status.ok()) << SummarizeNodeDef(node_def); if (status.ok()) return; for (const string& message : messages) { EXPECT_TRUE(StringPiece(status.error_message()).contains(message)) << status << ", " << message; } } // Calls Finalize() and verifies it returns an error. // Message must appear as a substring of the error. void ExpectFailure(const NodeDefBuilder& builder, const string& message) { ExpectFailures(builder, {message}); } // Like ExpectFailure(), except that the error can come from // ValidateNodeDef(). void ExpectInvalid(const NodeDefBuilder& builder, const string& message) { NodeDef node_def; Status status = builder.Finalize(&node_def); if (status.ok()) { status = ValidateNodeDef(node_def, op_def_); } EXPECT_FALSE(status.ok()) << SummarizeNodeDef(node_def); if (status.ok()) return; EXPECT_TRUE(StringPiece(status.error_message()).contains(message)) << "Actual error: " << status.error_message() << "\nDoes not contain: " << message; } OpDef op_def_; std::unique_ptr<NodeDefBuilder> builder_; }; TEST_F(NodeDefBuilderTest, Simple) { Op(OpDefBuilder("Simple").Input("a: int32").Output("out: float")); ExpectSuccess(Builder().Input("x", 0, DT_INT32), {DT_INT32}, {DT_FLOAT}, R"proto( op: "Simple" input: "x" )proto"); // Port != 0 ExpectSuccess(Builder().Input("y", 2, DT_INT32), {DT_INT32}, {DT_FLOAT}, R"proto( op: "Simple" input: "y:2" )proto"); // FakeInput ExpectSuccess(Builder().Input(FakeInput()), {DT_INT32}, {DT_FLOAT}, R"proto( op: "Simple" input: "a" )proto"); ExpectSuccess(Builder().Input(FakeInput(DT_INT32)), {DT_INT32}, {DT_FLOAT}, R"proto( op: "Simple" input: "a" )proto"); // Ref input ExpectSuccess(Builder().Input(FakeInput(DT_INT32_REF)), {DT_INT32}, {DT_FLOAT}, R"proto( op: "Simple" input: "a" )proto"); // ControlInput ExpectSuccess( Builder().ControlInput("x").Input(FakeInput()).ControlInput("y"), {DT_INT32}, {DT_FLOAT}, R"proto( op: "Simple" input: ["a", "^x", "^y"] )proto"); // Device ExpectSuccess(Builder().Input(FakeInput()).Device("ddd"), {DT_INT32}, {DT_FLOAT}, R"proto( op: "Simple" input: "a" device: "ddd" )proto"); // Extra input ExpectFailure(Builder().Input("x", 0, DT_INT32).Input("y", 0, DT_INT32), "More Input() calls than the 1 input_args while building " "NodeDef 'n' using Op<name=Simple; signature=a:int32 -> " "out:float>"); // Missing input ExpectFailure(Builder(), "0 inputs specified of 1 inputs in Op while"); { // Finalize() twice. NodeDefBuilder& builder = Builder(); builder.Input(FakeInput()).Finalize(nullptr); // First call to Finalize() // ExpectSuccess() also calls Finalize(). ExpectSuccess(builder, {DT_INT32}, {DT_FLOAT}, R"proto( op: "Simple" input: "a" )proto"); } { // Input() after Finalize() NodeDefBuilder& builder = Builder(); // Calling Finalize() before enough inputs -> error. ExpectFailure(builder, "0 inputs specified of 1 inputs in Op while"); builder.Input(FakeInput()); // Calling Finalize() with enough inputs -> success ExpectSuccess(builder, {DT_INT32}, {DT_FLOAT}, R"proto( op: "Simple" input: "a" )proto"); // Calling Finalize() with too many inputs -> error. builder.Input(FakeInput(DT_INT32)); ExpectFailure(builder, "More Input() calls than the 1 input_args while"); } // Wrong input type ExpectFailure(Builder().Input("x", 0, DT_FLOAT), "Input 'a' passed float expected int32 "); ExpectFailure(Builder().Input("x", 0, DT_FLOAT_REF), "Input 'a' passed float_ref expected int32 "); // List input ExpectFailure(Builder().Input(FakeInput(3, DT_FLOAT)), "List provided to input 'a' when single Tensor expected while"); ExpectFailure(Builder().Input(FakeInput(3)), "List provided to input 'a' when single Tensor expected while"); // Bad ControlInput ExpectInvalid(Builder().Input(FakeInput()).ControlInput("z:2"), "Control input '^z:2' must not have ':' in NodeDef:"); // Bad input name ExpectFailure(Builder().Input("", 0, DT_INT32), "Empty input node name while"); ExpectFailure(Builder().Input("^x", 0, DT_INT32), "Non-control input starting with ^: ^x while"); } TEST_F(NodeDefBuilderTest, OpDoesNotExist) { NodeDefBuilder builder("n", "Op Does Not Exist"); builder.Input(FakeInput()) .Input(FakeInput(12)) .ControlInput("y") .Attr("foo", 12) .Device("device"); ExpectFailure( builder, "Op type not registered 'Op Does Not Exist' while building NodeDef 'n'"); } TEST_F(NodeDefBuilderTest, Polymorphic) { Op(OpDefBuilder("Polymorphic") .Input("v: T") .Output("out: T") .Attr("T: type")); ExpectSuccess(Builder().Input(FakeInput(DT_INT32)), {DT_INT32}, {DT_INT32}, R"proto( op: "Polymorphic" input: "a" attr { key: "T" value { type: DT_INT32 } } )proto"); ExpectSuccess(Builder().Input(FakeInput(DT_FLOAT)), {DT_FLOAT}, {DT_FLOAT}, R"proto( op: "Polymorphic" input: "a" attr { key: "T" value { type: DT_FLOAT } } )proto"); // Redundant Attr() ExpectSuccess(Builder().Input(FakeInput(DT_BOOL)).Attr("T", DT_BOOL), {DT_BOOL}, {DT_BOOL}, R"proto( op: "Polymorphic" input: "a" attr { key: "T" value { type: DT_BOOL } } )proto"); // Conficting Attr() ExpectFailure(Builder().Input(FakeInput(DT_BOOL)).Attr("T", DT_STRING), "Inconsistent values for attr 'T' DT_BOOL vs. DT_STRING while"); ExpectFailure(Builder().Attr("T", DT_STRING).Input(FakeInput(DT_BOOL)), "Inconsistent values for attr 'T' DT_STRING vs. DT_BOOL while"); ExpectFailure(Builder().Attr("T", 12).Input(FakeInput(DT_BOOL)), "Inconsistent values for attr 'T' 12 vs. DT_BOOL while"); } TEST_F(NodeDefBuilderTest, PolymorphicOut) { Op(OpDefBuilder("PolymorphicOut").Output("out: T").Attr("T: type")); ExpectSuccess(Builder().Attr("T", DT_INT32), {}, {DT_INT32}, R"proto( op: "PolymorphicOut" attr { key: "T" value { type: DT_INT32 } } )proto"); ExpectSuccess(Builder().Attr("T", DT_FLOAT), {}, {DT_FLOAT}, R"proto( op: "PolymorphicOut" attr { key: "T" value { type: DT_FLOAT } } )proto"); // Redundant attr ExpectSuccess(Builder().Attr("T", DT_FLOAT).Attr("T", DT_FLOAT), {}, {DT_FLOAT}, R"proto( op: "PolymorphicOut" attr { key: "T" value { type: DT_FLOAT } } )proto"); // Conflicting attr ExpectFailure(Builder().Attr("T", DT_BOOL).Attr("T", DT_FLOAT), "Inconsistent values for attr 'T' DT_BOOL vs. DT_FLOAT while"); // Missing attr ExpectInvalid(Builder(), "NodeDef missing attr 'T' from"); // Attr has the wrong type ExpectInvalid( Builder().Attr("T", {DT_INT32, DT_BOOL}), "AttrValue had value with type 'list(type)' when 'type' expected"); ExpectInvalid(Builder().Attr("T", 12), "AttrValue had value with type 'int' when 'type' expected"); } TEST_F(NodeDefBuilderTest, PolymorphicDefaultOut) { Op(OpDefBuilder("PolymorphicDefaultOut") .Output("out: T") .Attr("T: type = DT_STRING")); ExpectSuccess(Builder(), {}, {DT_STRING}, R"proto( op: "PolymorphicDefaultOut" attr { key: "T" value { type: DT_STRING } } )proto"); ExpectSuccess(Builder().Attr("T", DT_BOOL), {}, {DT_BOOL}, R"proto( op: "PolymorphicDefaultOut" attr { key: "T" value { type: DT_BOOL } } )proto"); } TEST_F(NodeDefBuilderTest, Binary) { Op(OpDefBuilder("Binary").Input("a: T").Input("b: T").Output("out: T").Attr( "T: type")); ExpectSuccess(Builder().Input(FakeInput(DT_INT32)).Input(FakeInput(DT_INT32)), {DT_INT32, DT_INT32}, {DT_INT32}, R"proto( op: "Binary" input: "a" input: "b" attr { key: "T" value { type: DT_INT32 } } )proto"); ExpectSuccess(Builder().Input(FakeInput(DT_STRING)).Input(FakeInput()), {DT_STRING, DT_STRING}, {DT_STRING}, R"proto( op: "Binary" input: "a" input: "b" attr { key: "T" value { type: DT_STRING } } )proto"); // Type mismatch ExpectFailure(Builder().Input(FakeInput(DT_BOOL)).Input(FakeInput(DT_STRING)), "Inconsistent values for attr 'T' DT_BOOL vs. DT_STRING while"); } TEST_F(NodeDefBuilderTest, Restrict) { Op(OpDefBuilder("Restrict") .Input("a: T") .Output("out: T") .Attr("T: {string, bool}")); ExpectSuccess(Builder().Input(FakeInput(DT_STRING)), {DT_STRING}, {DT_STRING}, R"proto( op: "Restrict" input: "a" attr { key: "T" value { type: DT_STRING } } )proto"); ExpectInvalid(Builder().Input(FakeInput(DT_INT32)), "Value for attr 'T' of int32 is not in the list of allowed " "values: string, bool"); } TEST_F(NodeDefBuilderTest, TypeList) { Op(OpDefBuilder("TypeList").Input("a: T").Attr("T: list(type)")); ExpectSuccess(Builder().Input(FakeInput({DT_STRING, DT_INT32})), {DT_STRING, DT_INT32}, {}, R"proto( op: "TypeList" input: ["a", "a:1"] attr { key: "T" value { list { type: [DT_STRING, DT_INT32] } } } )proto"); ExpectSuccess(Builder().Input(FakeInput(3, DT_BOOL)), {DT_BOOL, DT_BOOL, DT_BOOL}, {}, R"proto( op: "TypeList" input: ["a", "a:1", "a:2"] attr { key: "T" value { list { type: [DT_BOOL, DT_BOOL, DT_BOOL] } } } )proto"); ExpectInvalid(Builder().Input(FakeInput(0)), "Length for attr 'T' of 0 must be at least minimum 1"); ExpectInvalid(Builder().Input(FakeInput({})), "Length for attr 'T' of 0 must be at least minimum 1"); ExpectInvalid(Builder().Input(FakeInput(DT_BOOL)), "Single tensor passed to 'a', expected list while"); ExpectFailures(Builder().Input(FakeInput()), {"2 errors while building NodeDef", "Could not infer list of types for input 'a': " "No attr named 'T' in NodeDef:", "0 inputs specified of 1 inputs in Op"}); } TEST_F(NodeDefBuilderTest, TypeListNoMin) { Op(OpDefBuilder("TypeListNoMin").Input("a: T").Attr("T: list(type) >= 0")); ExpectSuccess(Builder().Input(FakeInput(0)), {}, {}, R"proto( op: "TypeListNoMin" attr { key: "T" value { list { } } } )proto"); ExpectSuccess(Builder().Input(FakeInput(DataTypeVector())), {}, {}, R"proto( op: "TypeListNoMin" attr { key: "T" value { list { } } } )proto"); ExpectSuccess(Builder().Input(FakeInput({})), {}, {}, R"proto( op: "TypeListNoMin" attr { key: "T" value { list { } } } )proto"); ExpectSuccess(Builder().Input(FakeInput({DT_BOOL})), {DT_BOOL}, {}, R"proto( op: "TypeListNoMin" input: "a" attr { key: "T" value { list { type: DT_BOOL } } } )proto"); } TEST_F(NodeDefBuilderTest, TypeListTwice) { Op(OpDefBuilder("TypeListTwice") .Input("a: T") .Input("b: T") .Attr("T: list(type) >= 0")); ExpectSuccess(Builder() .Input(FakeInput({DT_INT32, DT_BOOL})) .Input(FakeInput({DT_INT32, DT_BOOL})), {DT_INT32, DT_BOOL, DT_INT32, DT_BOOL}, {}, R"proto( op: "TypeListTwice" input: ["a", "a:1", "b", "b:1"] attr { key: "T" value { list { type: [DT_INT32, DT_BOOL] } } } )proto"); ExpectSuccess( Builder().Input(FakeInput({DT_INT32, DT_BOOL})).Input(FakeInput()), {DT_INT32, DT_BOOL, DT_INT32, DT_BOOL}, {}, R"proto( op: "TypeListTwice" input: ["a", "a:1", "b", "b:1"] attr { key: "T" value { list { type: [DT_INT32, DT_BOOL] } } } )proto"); ExpectSuccess(Builder().Input(FakeInput(0)).Input(FakeInput(0)), {}, {}, R"proto( op: "TypeListTwice" attr { key: "T" value { list { } } } )proto"); ExpectSuccess(Builder().Input(FakeInput(0)).Input(FakeInput()), {}, {}, R"proto( op: "TypeListTwice" attr { key: "T" value { list { } } } )proto"); ExpectFailure(Builder() .Input(FakeInput({DT_INT32, DT_BOOL})) .Input(FakeInput({DT_INT32, DT_STRING})), "Inconsistent values for attr 'T' [DT_INT32, DT_BOOL] vs. " "[DT_INT32, DT_STRING] while"); } TEST_F(NodeDefBuilderTest, OutTypeList) { Op(OpDefBuilder("OutTypeList").Output("out: T").Attr("T: list(type) >= 0")); ExpectSuccess(Builder().Attr("T", {DT_FLOAT}), {}, {DT_FLOAT}, R"proto( op: "OutTypeList" attr { key: "T" value { list { type: DT_FLOAT } } } )proto"); ExpectSuccess(Builder().Attr("T", {DT_STRING, DT_BOOL}), {}, {DT_STRING, DT_BOOL}, R"proto( op: "OutTypeList" attr { key: "T" value { list { type: [DT_STRING, DT_BOOL] } } } )proto"); ExpectSuccess(Builder().Attr("T", DataTypeVector()), {}, {}, R"proto( op: "OutTypeList" attr { key: "T" value { list { } } } )proto"); ExpectInvalid( Builder().Attr("T", DT_FLOAT), "AttrValue had value with type 'type' when 'list(type)' expected"); } TEST_F(NodeDefBuilderTest, TypeListRestrict) { Op(OpDefBuilder("TypeListRestrict") .Input("a: T") .Attr("T: list({string, bool}) >= 0")); ExpectSuccess(Builder().Input(FakeInput({DT_STRING, DT_BOOL})), {DT_STRING, DT_BOOL}, {}, R"proto( op: "TypeListRestrict" input: ["a", "a:1"] attr { key: "T" value { list { type: [DT_STRING, DT_BOOL] } } } )proto"); ExpectInvalid(Builder().Input(FakeInput({DT_STRING, DT_INT32})), "Value for attr 'T' of int32 is not in the list of allowed " "values: string, bool"); } TEST_F(NodeDefBuilderTest, OutTypeListRestrict) { Op(OpDefBuilder("OutTypeListRestrict") .Output("out: t") .Attr("t: list({string, bool}) >= 0")); ExpectSuccess(Builder().Attr("t", {DT_BOOL, DT_STRING}), {}, {DT_BOOL, DT_STRING}, R"proto( op: "OutTypeListRestrict" attr { key: "t" value { list { type: [DT_BOOL, DT_STRING] } } } )proto"); ExpectInvalid(Builder().Attr("t", {DT_STRING, DT_INT32}), "Value for attr 't' of int32 is not in the list of allowed " "values: string, bool"); } TEST_F(NodeDefBuilderTest, Attr) { Op(OpDefBuilder("Attr").Attr("a: int")); ExpectSuccess(Builder().Attr("a", 12), {}, {}, R"proto( op: "Attr" attr { key: "a" value { i: 12 } } )proto"); // Attr has wrong type ExpectInvalid(Builder().Attr("a", "bad"), "AttrValue had value with type 'string' when 'int' expected"); ExpectInvalid( Builder().Attr("a", {12}), "AttrValue had value with type 'list(int)' when 'int' expected"); // Missing attr ExpectInvalid(Builder(), "NodeDef missing attr 'a' from Op<"); // Wrong attr ExpectInvalid(Builder().Attr("b", 12), "NodeDef mentions attr 'b' not in Op<"); // Extra attr ExpectInvalid(Builder().Attr("a", 12).Attr("extra", 12), "NodeDef mentions attr 'extra' not in Op<"); } TEST_F(NodeDefBuilderTest, AttrFloat) { Op(OpDefBuilder("AttrFloat").Attr("a: float")); ExpectSuccess(Builder().Attr("a", 1.2f /* float */), {}, {}, R"proto( op: "AttrFloat" attr { key: "a" value { f: 1.2 } } )proto"); ExpectSuccess(Builder().Attr("a", 1.2 /* double */), {}, {}, R"proto( op: "AttrFloat" attr { key: "a" value { f: 1.2 } } )proto"); // Won't automatically cast int to float ExpectInvalid(Builder().Attr("a", 12), "AttrValue had value with type 'int' when 'float' expected"); } TEST_F(NodeDefBuilderTest, AttrBoolList) { Op(OpDefBuilder("AttrBoolList").Attr("a: list(bool)")); ExpectSuccess(Builder().Attr("a", {true, false, true}), {}, {}, R"proto( op: "AttrBoolList" attr { key: "a" value { list { b: [true, false, true] } } } )proto"); ExpectSuccess(Builder().Attr("a", std::vector<bool>()), {}, {}, R"proto( op: "AttrBoolList" attr { key: "a" value { list { } } } )proto"); // Won't cast int -> bool. ExpectInvalid(Builder().Attr("a", {0}), "AttrValue had value with type 'list(int)' when 'list(bool)' " "expected"); } TEST_F(NodeDefBuilderTest, AttrMin) { Op(OpDefBuilder("AttrMin").Attr("a: int >= 5")); ExpectSuccess(Builder().Attr("a", 12), {}, {}, R"proto( op: "AttrMin" attr { key: "a" value { i: 12 } } )proto"); ExpectInvalid(Builder().Attr("a", 2), "Value for attr 'a' of 2 must be at least minimum 5"); } TEST_F(NodeDefBuilderTest, AttrListMin) { Op(OpDefBuilder("AttrListMin").Attr("a: list(int) >= 2")); ExpectSuccess(Builder().Attr("a", {1, 2}), {}, {}, R"proto( op: "AttrListMin" attr { key: "a" value { list { i: [1, 2] } } } )proto"); ExpectInvalid(Builder().Attr("a", {17}), "Length for attr 'a' of 1 must be at least minimum 2"); } TEST_F(NodeDefBuilderTest, AttrEnum) { Op(OpDefBuilder("AttrEnum").Attr("a: {'apples', 'oranges'}")); ExpectSuccess(Builder().Attr("a", "oranges"), {}, {}, R"proto( op: "AttrEnum" attr { key: "a" value { s: "oranges" } } )proto"); ExpectInvalid( Builder().Attr("a", "invalid"), "Value for attr 'a' of \"invalid\" is not in the list of allowed values: " "\"apples\", \"oranges\""); } TEST_F(NodeDefBuilderTest, AttrEnumList) { Op(OpDefBuilder("AttrEnumList").Attr("a: list({'apples', 'oranges'})")); ExpectSuccess(Builder().Attr("a", {"oranges", "apples"}), {}, {}, R"proto( op: "AttrEnumList" attr { key: "a" value { list { s: ["oranges", "apples"] } } } )proto"); ExpectInvalid( Builder().Attr("a", {"apples", "invalid", "oranges"}), "Value for attr 'a' of \"invalid\" is not in the list of allowed values: " "\"apples\", \"oranges\""); } TEST_F(NodeDefBuilderTest, AttrShape) { Op(OpDefBuilder("AttrShape").Attr("a: shape")); ExpectSuccess(Builder().Attr("a", TensorShape({5})), {}, {}, R"proto( op: "AttrShape" attr { key: "a" value { shape { dim { size: 5 } } } } )proto"); ExpectSuccess(Builder().Attr("a", TensorShape({4, 3, 2})), {}, {}, R"proto( op: "AttrShape" attr { key: "a" value { shape { dim { size: 4 } dim { size: 3 } dim { size: 2 } } } } )proto"); ExpectSuccess(Builder().Attr("a", TensorShape({3, 2})), {}, {}, R"proto( op: "AttrShape" attr { key: "a" value { shape { dim { size: 3 } dim { size: 2 } } } } )proto"); ExpectSuccess(Builder().Attr("a", TensorShape()), {}, {}, R"proto( op: "AttrShape" attr { key: "a" value { shape { } } } )proto"); } TEST_F(NodeDefBuilderTest, AttrDefault) { Op(OpDefBuilder("AttrDefault").Attr("a: string = 'banana'")); ExpectSuccess(Builder(), {}, {}, R"proto( op: "AttrDefault" attr { key: "a" value { s: "banana" } } )proto"); ExpectSuccess(Builder().Attr("a", "kiwi"), {}, {}, R"proto( op: "AttrDefault" attr { key: "a" value { s: "kiwi" } } )proto"); } TEST_F(NodeDefBuilderTest, AttrManyDefault) { Op(OpDefBuilder("AttrManyDefault") .Attr("a: string = 'banana'") .Attr("b: string = 'kiwi'")); ExpectSuccess(Builder(), {}, {}, R"proto( op: "AttrManyDefault" attr { key: "a" value { s: "banana" } } attr { key: "b" value { s: "kiwi" } } )proto"); Op(OpDefBuilder("AttrManyDefaultWithMandatory") .Attr("a: string = 'banana'") .Attr("b: string = 'kiwi'") .Attr("c: string")); ExpectSuccess(Builder().Attr("c", "strawberry"), {}, {}, R"proto( op: "AttrManyDefaultWithMandatory" attr { key: "c" value { s: "strawberry" } } attr { key: "a" value { s: "banana" } } attr { key: "b" value { s: "kiwi" } } )proto"); Op(OpDefBuilder("AttrManyDefaultAndInferred") .Input("input: T") .Attr("T: {float, double}") .Attr("a: string") .Attr("b: list(string) >= 1") .Attr("c: bool = true") .Attr("d: float = 0.3") .Attr("e: string") .Attr("f: float = 0.25")); ExpectSuccess(Builder() .Input(FakeInput(DT_FLOAT)) .Attr("a", "foo") .Attr("e", "foo") .Attr("b", std::vector<string>({"bar", "baz"})) .Attr("f", 1.0f), {DT_FLOAT}, {}, R"proto( op: "AttrManyDefaultAndInferred" input: "a" attr { key: "T" value { type: DT_FLOAT } } attr { key: "a" value { s: "foo" } } attr { key: "e" value { s: "foo" } } attr { key: "b" value { list { s: "bar" s: "baz" } } } attr { key: "f" value { f: 1.0 } } attr { key: "c" value { b: true } } attr { key: "d" value { f: 0.3 } } )proto"); } TEST_F(NodeDefBuilderTest, AttrListDefault) { Op(OpDefBuilder("AttrListDefault").Attr("a: list(int) = [5, 15]")); ExpectSuccess(Builder(), {}, {}, R"proto( op: "AttrListDefault" attr { key: "a" value { list { i: [5, 15] } } } )proto"); ExpectSuccess(Builder().Attr("a", {3}), {}, {}, R"proto( op: "AttrListDefault" attr { key: "a" value { list { i: 3 } } } )proto"); ExpectSuccess(Builder().Attr("a", std::vector<int>()), {}, {}, R"proto( op: "AttrListDefault" attr { key: "a" value { list { } } } )proto"); } TEST_F(NodeDefBuilderTest, AttrEmptyListDefault) { Op(OpDefBuilder("AttrEmptyListDefault").Attr("a: list(int) = []")); ExpectSuccess(Builder(), {}, {}, R"proto( op: "AttrEmptyListDefault" attr { key: "a" value { list { } } } )proto"); ExpectSuccess(Builder().Attr("a", {3}), {}, {}, R"proto( op: "AttrEmptyListDefault" attr { key: "a" value { list { i: 3 } } } )proto"); ExpectSuccess(Builder().Attr("a", std::vector<int>()), {}, {}, R"proto( op: "AttrEmptyListDefault" attr { key: "a" value { list { } } } )proto"); } TEST_F(NodeDefBuilderTest, NIntsIn) { Op(OpDefBuilder("NIntsIn").Input("a: N*int32").Attr("N: int >= 2")); ExpectSuccess(Builder().Input(FakeInput(2)), {DT_INT32, DT_INT32}, {}, R"proto( op: "NIntsIn" input: ["a", "a:1"] attr { key: "N" value { i: 2 } } )proto"); ExpectSuccess(Builder().Input(FakeInput(5, DT_INT32)), {DT_INT32, DT_INT32, DT_INT32, DT_INT32, DT_INT32}, {}, R"proto( op: "NIntsIn" input: ["a", "a:1", "a:2", "a:3", "a:4"] attr { key: "N" value { i: 5 } } )proto"); ExpectFailures(Builder().Input(FakeInput(2, DT_STRING)), {"2 errors while building NodeDef", "Input 'a' passed string expected int32"}); ExpectInvalid(Builder().Input(FakeInput(1)), "Value for attr 'N' of 1 must be at least minimum 2"); ExpectFailures( Builder().Input(FakeInput(DT_INT32)), {"2 errors while building NodeDef", "Could not infer length of input 'a': No attr named 'N' in NodeDef:", "0 inputs specified of 1 inputs in Op"}); ExpectFailure(Builder().Input({{"in", 0, DT_INT32}, {"in", 1, DT_STRING}}), "Input 'a' passed string expected int32 while"); ExpectFailures( Builder().Input(FakeInput()), {"2 errors while building NodeDef", "Could not infer length of input 'a': No attr named 'N' in NodeDef:", "0 inputs specified of 1 inputs in Op"}); } TEST_F(NodeDefBuilderTest, NPolymorphicIn) { Op(OpDefBuilder("NPolymorphicIn") .Input("a: N*T") .Attr("T: type") .Attr("N: int >= 2")); ExpectSuccess(Builder().Input(FakeInput(2, DT_INT32)), {DT_INT32, DT_INT32}, {}, R"proto( op: "NPolymorphicIn" input: ["a", "a:1"] attr { key: "N" value { i: 2 } } attr { key: "T" value { type: DT_INT32 } } )proto"); ExpectSuccess(Builder().Input(FakeInput(3, DT_STRING)), {DT_STRING, DT_STRING, DT_STRING}, {}, R"proto( op: "NPolymorphicIn" input: ["a", "a:1", "a:2"] attr { key: "N" value { i: 3 } } attr { key: "T" value { type: DT_STRING } } )proto"); ExpectFailures( Builder().Input(FakeInput(2)), {"2 errors while building NodeDef", "Could not infer type for input 'a': No attr named 'T' in NodeDef:", "0 inputs specified of 1 inputs in Op"}); ExpectFailure(Builder().Input(FakeInput({DT_INT32, DT_STRING})), "Input 'a' passed string expected int32 while"); ExpectFailure(Builder().Input({{"in", 0, DT_INT32}, {"in", 1, DT_STRING}}), "Input 'a' passed string expected int32 while"); ExpectInvalid(Builder().Input(FakeInput(1, DT_INT32)), "Value for attr 'N' of 1 must be at least minimum 2"); ExpectFailure(Builder().Input("in", 0, DT_INT32), "Single tensor passed to 'a', expected list while"); } TEST_F(NodeDefBuilderTest, NPolymorphicRestrictIn) { Op(OpDefBuilder("NPolymorphicRestrictIn") .Input("a: N*T") .Attr("T: {string, bool}") .Attr("N: int >= 2")); ExpectSuccess(Builder().Input(FakeInput(2, DT_BOOL)), {DT_BOOL, DT_BOOL}, {}, R"proto( op: "NPolymorphicRestrictIn" input: ["a", "a:1"] attr { key: "N" value { i: 2 } } attr { key: "T" value { type: DT_BOOL } } )proto"); ExpectSuccess(Builder().Input(FakeInput(3, DT_STRING)), {DT_STRING, DT_STRING, DT_STRING}, {}, R"proto( op: "NPolymorphicRestrictIn" input: ["a", "a:1", "a:2"] attr { key: "N" value { i: 3 } } attr { key: "T" value { type: DT_STRING } } )proto"); ExpectInvalid(Builder().Input(FakeInput(2, DT_INT32)), "Value for attr 'T' of int32 is not in the list of allowed " "values: string, bool"); } TEST_F(NodeDefBuilderTest, NInTwice) { Op(OpDefBuilder("NInTwice") .Input("a: N*int32") .Input("b: N*string") .Attr("N: int >= 0")); ExpectSuccess(Builder().Input(FakeInput(2)).Input(FakeInput(2)), {DT_INT32, DT_INT32, DT_STRING, DT_STRING}, {}, R"proto( op: "NInTwice" input: ["a", "a:1", "b", "b:1"] attr { key: "N" value { i: 2 } } )proto"); ExpectSuccess(Builder().Input(FakeInput(0)).Input(FakeInput()), {}, {}, R"proto( op: "NInTwice" attr { key: "N" value { i: 0 } } )proto"); ExpectFailure(Builder().Input(FakeInput(3)).Input(FakeInput(1)), "Inconsistent values for attr 'N' 3 vs. 1 while"); } TEST_F(NodeDefBuilderTest, NInPolymorphicTwice) { Op(OpDefBuilder("NInPolymorphicTwice") .Input("a: N*T") .Input("b: N*T") .Attr("T: type") .Attr("N: int >= 0")); ExpectSuccess(Builder().Input(FakeInput(2, DT_INT32)).Input(FakeInput()), {DT_INT32, DT_INT32, DT_INT32, DT_INT32}, {}, R"proto( op: "NInPolymorphicTwice" input: ["a", "a:1", "b", "b:1"] attr { key: "N" value { i: 2 } } attr { key: "T" value { type: DT_INT32 } } )proto"); ExpectFailure( Builder().Input(FakeInput(3, DT_INT32)).Input(FakeInput(1, DT_INT32)), "Inconsistent values for attr 'N' 3 vs. 1 while"); ExpectFailure(Builder().Input(FakeInput(3, DT_INT32)).Input(FakeInput(1)), "Inconsistent values for attr 'N' 3 vs. 1 while"); ExpectFailure( Builder().Input(FakeInput(2, DT_INT32)).Input(FakeInput(2, DT_STRING)), "Inconsistent values for attr 'T' DT_INT32 vs. DT_STRING while"); ExpectFailure( Builder().Input(FakeInput(2, DT_INT32)).Input(FakeInput(DT_STRING)), "Inconsistent values for attr 'T' DT_INT32 vs. DT_STRING while"); } TEST_F(NodeDefBuilderTest, NInTwoTypeVariables) { Op(OpDefBuilder("NInTwoTypeVariables") .Input("a: N*S") .Input("b: N*T") .Attr("S: type") .Attr("T: type") .Attr("N: int >= 0")); ExpectSuccess( Builder().Input(FakeInput(2, DT_INT32)).Input(FakeInput(2, DT_BOOL)), {DT_INT32, DT_INT32, DT_BOOL, DT_BOOL}, {}, R"proto( op: "NInTwoTypeVariables" input: ["a", "a:1", "b", "b:1"] attr { key: "N" value { i: 2 } } attr { key: "S" value { type: DT_INT32 } } attr { key: "T" value { type: DT_BOOL } } )proto"); ExpectSuccess( Builder().Input(FakeInput(2, DT_INT32)).Input(FakeInput(DT_BOOL)), {DT_INT32, DT_INT32, DT_BOOL, DT_BOOL}, {}, R"proto( op: "NInTwoTypeVariables" input: ["a", "a:1", "b", "b:1"] attr { key: "N" value { i: 2 } } attr { key: "S" value { type: DT_INT32 } } attr { key: "T" value { type: DT_BOOL } } )proto"); ExpectFailure( Builder().Input(FakeInput(3, DT_INT32)).Input(FakeInput(1, DT_STRING)), "Inconsistent values for attr 'N' 3 vs. 1 while"); } TEST_F(NodeDefBuilderTest, InPolymorphicTwice) { Op(OpDefBuilder("InPolymorphicTwice") .Input("a: N*T") .Input("b: M*T") .Attr("T: type") .Attr("N: int >= 0") .Attr("M: int >= 0")); ExpectSuccess( Builder().Input(FakeInput(1, DT_INT32)).Input(FakeInput(3, DT_INT32)), {DT_INT32, DT_INT32, DT_INT32, DT_INT32}, {}, R"proto( op: "InPolymorphicTwice" input: ["a", "b", "b:1", "b:2"] attr { key: "N" value { i: 1 } } attr { key: "T" value { type: DT_INT32 } } attr { key: "M" value { i: 3 } } )proto"); ExpectSuccess(Builder().Input(FakeInput(1, DT_BOOL)).Input(FakeInput(0)), {DT_BOOL}, {}, R"proto( op: "InPolymorphicTwice" input: "a" attr { key: "N" value { i: 1 } } attr { key: "T" value { type: DT_BOOL } } attr { key: "M" value { i: 0 } } )proto"); ExpectSuccess(Builder().Input(FakeInput(0)).Input(FakeInput(1, DT_BOOL)), {DT_BOOL}, {}, R"proto( op: "InPolymorphicTwice" input: "b" attr { key: "N" value { i: 0 } } attr { key: "M" value { i: 1 } } attr { key: "T" value { type: DT_BOOL } } )proto"); ExpectFailure( Builder().Input(FakeInput(2, DT_INT32)).Input(FakeInput(2, DT_STRING)), "Inconsistent values for attr 'T' DT_INT32 vs. DT_STRING while"); } TEST_F(NodeDefBuilderTest, NIntsOut) { Op(OpDefBuilder("NIntsOut").Output("a: N*int32").Attr("N: int >= 2")); ExpectSuccess(Builder().Attr("N", 2), {}, {DT_INT32, DT_INT32}, R"proto( op: "NIntsOut" attr { key: "N" value { i: 2 } } )proto"); ExpectSuccess(Builder().Attr("N", 3), {}, {DT_INT32, DT_INT32, DT_INT32}, R"proto( op: "NIntsOut" attr { key: "N" value { i: 3 } } )proto"); ExpectInvalid(Builder().Attr("N", 1), "Value for attr 'N' of 1 must be at least minimum 2"); ExpectInvalid( Builder().Attr("N", {3}), "AttrValue had value with type 'list(int)' when 'int' expected"); ExpectInvalid(Builder(), "NodeDef missing attr 'N' from"); } TEST_F(NodeDefBuilderTest, NIntsOutDefault) { Op(OpDefBuilder("NIntsOutDefault") .Output("a: N*int32") .Attr("N: int >= 2 = 3")); ExpectSuccess(Builder(), {}, {DT_INT32, DT_INT32, DT_INT32}, R"proto( op: "NIntsOutDefault" attr { key: "N" value { i: 3 } } )proto"); ExpectSuccess(Builder().Attr("N", 2), {}, {DT_INT32, DT_INT32}, R"proto( op: "NIntsOutDefault" attr { key: "N" value { i: 2 } } )proto"); } TEST_F(NodeDefBuilderTest, NPolymorphicOut) { Op(OpDefBuilder("NPolymorphicOut") .Output("a: N*T") .Attr("T: type") .Attr("N: int >= 2")); ExpectSuccess(Builder().Attr("T", DT_INT32).Attr("N", 2), {}, {DT_INT32, DT_INT32}, R"proto( op: "NPolymorphicOut" attr { key: "T" value { type: DT_INT32 } } attr { key: "N" value { i: 2 } } )proto"); ExpectSuccess(Builder().Attr("N", 3).Attr("T", DT_STRING), {}, {DT_STRING, DT_STRING, DT_STRING}, R"proto( op: "NPolymorphicOut" attr { key: "N" value { i: 3 } } attr { key: "T" value { type: DT_STRING } } )proto"); ExpectInvalid(Builder().Attr("N", 1).Attr("T", DT_STRING), "Value for attr 'N' of 1 must be at least minimum 2"); ExpectInvalid( Builder().Attr("N", 3).Attr("T", {DT_STRING}), "AttrValue had value with type 'list(type)' when 'type' expected"); } TEST_F(NodeDefBuilderTest, NPolymorphicOutDefault) { Op(OpDefBuilder("NPolymorphicOutDefault") .Output("a: N*T") .Attr("T: type = DT_BOOL") .Attr("N: int >= 2 = 2")); ExpectSuccess(Builder(), {}, {DT_BOOL, DT_BOOL}, R"proto( op: "NPolymorphicOutDefault" attr { key: "T" value { type: DT_BOOL } } attr { key: "N" value { i: 2 } } )proto"); ExpectSuccess(Builder().Attr("N", 3), {}, {DT_BOOL, DT_BOOL, DT_BOOL}, R"proto( op: "NPolymorphicOutDefault" attr { key: "N" value { i: 3 } } attr { key: "T" value { type: DT_BOOL } } )proto"); ExpectSuccess(Builder().Attr("T", DT_INT32), {}, {DT_INT32, DT_INT32}, R"proto( op: "NPolymorphicOutDefault" attr { key: "T" value { type: DT_INT32 } } attr { key: "N" value { i: 2 } } )proto"); ExpectSuccess(Builder().Attr("N", 3).Attr("T", DT_INT32), {}, {DT_INT32, DT_INT32, DT_INT32}, R"proto( op: "NPolymorphicOutDefault" attr { key: "N" value { i: 3 } } attr { key: "T" value { type: DT_INT32 } } )proto"); } TEST_F(NodeDefBuilderTest, NPolymorphicRestrictOut) { Op(OpDefBuilder("NPolymorphicRestrictOut") .Output("a: N*T") .Attr("T: {string, bool}") .Attr("N: int >= 2")); ExpectSuccess(Builder().Attr("N", 3).Attr("T", DT_BOOL), {}, {DT_BOOL, DT_BOOL, DT_BOOL}, R"proto( op: "NPolymorphicRestrictOut" attr { key: "N" value { i: 3 } } attr { key: "T" value { type: DT_BOOL } } )proto"); ExpectInvalid(Builder().Attr("N", 3).Attr("T", DT_INT32), "Value for attr 'T' of int32 is not in the list of allowed " "values: string, bool"); } TEST_F(NodeDefBuilderTest, RefIn) { Op(OpDefBuilder("RefIn").Input("a: Ref(int32)")); ExpectSuccess(Builder().Input(FakeInput(DT_INT32_REF)), {DT_INT32_REF}, {}, R"proto( op: "RefIn" input: "a" )proto"); ExpectFailure(Builder().Input(FakeInput(DT_BOOL_REF)), "Input 'a' passed bool_ref expected int32_ref while"); ExpectFailure(Builder().Input(FakeInput(DT_INT32)), "Input 'a' passed int32 expected int32_ref while"); } TEST_F(NodeDefBuilderTest, PolymorphicRefIn) { Op(OpDefBuilder("PolymorphicRefIn").Input("a: Ref(T)").Attr("T: type")); ExpectSuccess(Builder().Input(FakeInput(DT_BOOL_REF)), {DT_BOOL_REF}, {}, R"proto( op: "PolymorphicRefIn" input: "a" attr { key: "T" value { type: DT_BOOL } } )proto"); ExpectFailure(Builder().Input(FakeInput(DT_BOOL)), "Input 'a' passed bool expected ref type while"); } TEST_F(NodeDefBuilderTest, RefOut) { Op(OpDefBuilder("RefOut").Output("a: Ref(string)")); ExpectSuccess(Builder(), {}, {DT_STRING_REF}, R"proto( op: "RefOut" )proto"); } TEST_F(NodeDefBuilderTest, PolymorphicRefOut) { Op(OpDefBuilder("PolymorphicRefOut").Output("a: Ref(t)").Attr("t: type")); ExpectSuccess(Builder().Attr("t", DT_BOOL), {}, {DT_BOOL_REF}, R"proto( op: "PolymorphicRefOut" attr { key: "t" value { type: DT_BOOL } } )proto"); } TEST_F(NodeDefBuilderTest, SpecifyDevice) { Op(OpDefBuilder("SpecifyDevice")); ExpectSuccess(Builder().Device("ADevice"), {}, {}, R"proto( op: "SpecifyDevice" device: "ADevice" )proto"); } } // namespace } // namespace tensorflow
/*-----------------------Patrick 12/11/96-------------------------- Source for AVP Pheromone system -----------------------------------------------------------------*/ #include "3dc.h" #include "inline.h" #include "module.h" #include "strategy_def.h" #include "gamedef.h" #include "bh_types.h" #define UseLocalAssert TRUE #include "ourasert.h" #include "pheromone.h" #include "pfarlocs.h" #include "pvisible.h" #include "bh_alien.h" #include "bh_far.h" #include "bh_generator.h" #include "showcmds.h" #include "pldghost.h" #if 1 static unsigned int *Pher_Player1; static unsigned int *Pher_Player2; static unsigned char *Pher_Ai1; #else #define MaxModules 300 static unsigned int Pher_Player1[MaxModules]; static unsigned int Pher_Player2[MaxModules]; static unsigned char Pher_Ai1[MaxModules]; #endif /* these pointers indicate the current read from and write to buffers for the player and ai pheromone systems */ unsigned int *PherPl_ReadBuf; unsigned int *PherPl_WriteBuf; unsigned char *PherAi_Buf; #if SUPER_PHEROMONE_SYSTEM static unsigned int *Pher_Aliens1; static unsigned int *Pher_Aliens2; unsigned int *PherAls_ReadBuf; unsigned int *PherAls_WriteBuf; unsigned int AlienPheromoneScale; /* Marine pheromones: a pathfinding system only. */ static unsigned int *Pher_Marines1; static unsigned int *Pher_Marines2; unsigned int *PherMars_ReadBuf = 0; unsigned int *PherMars_WriteBuf = 0; #endif /* This global is used to store the current player phermone intensity */ unsigned int PlayerSmell = 3; MODULE *playerPherModule = (MODULE *)0; /* external globals */ extern int AIModuleArraySize; /* this define enables diagnostic text 'dump' for pheromone system */ #define logPheromoneDiagnostics 0 #if logPheromoneDiagnostics static void LogPlayerPherValues(void); static void LogModuleAdjacencies(void); int printModAdj = 1; #endif /*----------------------Patrick 12/11/96--------------------------- Initialises pheromone systems -------------------------------------------------------------------*/ void InitPheromoneSystem(void) { int i; #if 1 /* allocate the pheromone buffers */ Pher_Player1 = (unsigned int *)AllocateMem((AIModuleArraySize+1)*sizeof(unsigned int)); if(!Pher_Player1) { memoryInitialisationFailure = 1; return; } Pher_Player2 = (unsigned int *)AllocateMem((AIModuleArraySize+1)*sizeof(unsigned int)); if(!Pher_Player2) { memoryInitialisationFailure = 1; return; } Pher_Ai1 = (unsigned char *)AllocateMem((AIModuleArraySize+1)*sizeof(unsigned char)); if(!Pher_Ai1) { memoryInitialisationFailure = 1; return; } #endif #if SUPER_PHEROMONE_SYSTEM Pher_Aliens1 = (unsigned int *)AllocateMem((AIModuleArraySize+1)*sizeof(unsigned int)); if(!Pher_Aliens1) { memoryInitialisationFailure = 1; return; } Pher_Aliens2 = (unsigned int *)AllocateMem((AIModuleArraySize+1)*sizeof(unsigned int)); if(!Pher_Aliens2) { memoryInitialisationFailure = 1; return; } Pher_Marines1 = (unsigned int *)AllocateMem((AIModuleArraySize+1)*sizeof(unsigned int)); if(!Pher_Marines1) { memoryInitialisationFailure = 1; return; } Pher_Marines2 = (unsigned int *)AllocateMem((AIModuleArraySize+1)*sizeof(unsigned int)); if(!Pher_Marines2) { memoryInitialisationFailure = 1; return; } #endif /* init the player phermone system */ for(i=0;i<AIModuleArraySize;i++) { Pher_Player1[i] = 1; Pher_Player2[i] = 1; } PherPl_ReadBuf = &Pher_Player1[0]; PherPl_WriteBuf = &Pher_Player2[0]; PlayerSmell = 3; playerPherModule = (MODULE *)0; /* init the ai pheromone system */ for(i=0;i<AIModuleArraySize;i++) { Pher_Ai1[i] = 0; } PherAi_Buf = &Pher_Ai1[0]; #if SUPER_PHEROMONE_SYSTEM for(i=0;i<AIModuleArraySize;i++) { Pher_Aliens1[i] = 0; Pher_Aliens2[i] = 0; } PherAls_ReadBuf = &Pher_Aliens1[0]; PherAls_WriteBuf = &Pher_Aliens2[0]; AlienPheromoneScale=1; for(i=0;i<AIModuleArraySize;i++) { Pher_Marines1[i] = 0; Pher_Marines2[i] = 0; } PherMars_ReadBuf = &Pher_Marines1[0]; PherMars_WriteBuf = &Pher_Marines2[0]; #endif #if logPheromoneDiagnostics printModAdj = 1; #endif } /*----------------------Patrick 14/3/96--------------------------- End of level clean up for pheromone system -------------------------------------------------------------------*/ void CleanUpPheromoneSystem(void) { #if 1 if (Pher_Player1) DeallocateMem(Pher_Player1); if (Pher_Player2) DeallocateMem(Pher_Player2); if (Pher_Ai1) DeallocateMem(Pher_Ai1); #endif #if SUPER_PHEROMONE_SYSTEM if (Pher_Aliens1) DeallocateMem(Pher_Aliens1); if (Pher_Aliens2) DeallocateMem(Pher_Aliens2); if (Pher_Marines1) DeallocateMem(Pher_Marines1); if (Pher_Marines2) DeallocateMem(Pher_Marines2); #endif } int AIModuleAdmitsPheromones(AIMODULE *targetModule) { /* Check state. */ MODULEDOORTYPE doorStatus; doorStatus = (AIModuleIsADoor(targetModule)); switch(doorStatus) { case(MDT_ProxDoor): { /* Go thru UNLOCKED proxdoors... */ MODULE *renderModule; PROXDOOR_BEHAV_BLOCK *pdbblk; renderModule=*(targetModule->m_module_ptrs); pdbblk=((PROXDOOR_BEHAV_BLOCK *)renderModule->m_sbptr->SBdataptr); if (pdbblk->door_locked) { return 0; } else { return 1; } /* if (pdbblk->lockable_door) { if (pdbblk->door_locked) { return(0); } else { return(1); } } else { if (pdbblk->door_locked) { return(0); } else { return(1); } } */ } case(MDT_LiftDoor): { GLOBALASSERT(targetModule->m_module_ptrs); GLOBALASSERT(*(targetModule->m_module_ptrs)); if(GetState((*(targetModule->m_module_ptrs))->m_sbptr)) { /* Open. */ return (1); } else { /* Closed. */ return (0); } break; } case(MDT_SecurityDoor): { GLOBALASSERT(targetModule->m_module_ptrs); GLOBALASSERT(*(targetModule->m_module_ptrs)); if(GetState((*(targetModule->m_module_ptrs))->m_sbptr)) { /* Open. */ return (1); } else { /* Closed. */ return (0); } break; } default: { LOCALASSERT(doorStatus==MDT_NotADoor); return(1); } } } #if SUPER_PHEROMONE_SYSTEM void AddMarinePheromones(AIMODULE *targetModule) { int ThisModuleIndex; ThisModuleIndex = targetModule->m_index; PherAls_WriteBuf[ThisModuleIndex] += 3; } void MaintainMarineTargetZone(AIMODULE *targetModule) { int ThisModuleIndex; ThisModuleIndex = targetModule->m_index; PherMars_WriteBuf[ThisModuleIndex] += 3; } #endif /*----------------------Patrick 12/11/96--------------------------- Updates the player pheromone system: this is used by the NPC far behaviour for hunting the player. -------------------------------------------------------------------*/ void PlayerPheromoneSystem(void) { int moduleCounter; AIMODULE *ModuleListPointer; AIMODULE *ThisModulePtr; int ThisModuleIndex; AIMODULE **AdjModuleRefPtr; int AdjModuleIndex; #if logPheromoneDiagnostics if(printModAdj) { printModAdj = 0; LogModuleAdjacencies(); } #endif /* get a pointer to the global array of pointers to the modules in the environment (interfaces'r'us). First check if Global_ModulePtr is set. If not we're buggered, so leave everything as it is and try again next frame*/ { extern AIMODULE *AIModuleArray; ModuleListPointer = AIModuleArray; } /* go through each module in the environment */ for(moduleCounter = 0; moduleCounter < AIModuleArraySize; moduleCounter++) { /* get a pointer to the next current module */ ThisModulePtr = &(ModuleListPointer[moduleCounter]); LOCALASSERT(ThisModulePtr); /* get it's index */ ThisModuleIndex = ThisModulePtr->m_index; LOCALASSERT(ThisModuleIndex >= 0); LOCALASSERT(ThisModuleIndex < AIModuleArraySize); /* !!!!!!!!!!!!!!!!!!!!! check for closed non-traversable door module here if detected, do not update its smell. Actually, no: allow smell to pass thro' non-openable doors. Otherwise AIs that can open doors will choose not to !!!!!!!!!!!!!!!!!!!!!!!!*/ /* CDF 4/12/97: Actually, yes. AIs CAN'T open security doors, fool! */ /* check for universal module: don't want to update this! */ if(AIModuleIsPhysical(ThisModulePtr)) { if (AIModuleAdmitsPheromones(ThisModulePtr)) { /* get a pointer to the list of physically adjacent modules and traverse them */ AdjModuleRefPtr = ThisModulePtr->m_link_ptrs; if(AdjModuleRefPtr) /* check that there is a list of adjacent modules */ { while(*AdjModuleRefPtr != 0) { /* get the index */ AdjModuleIndex = (*AdjModuleRefPtr)->m_index; /* if adjacent module's previous smell is greater than the current module's new smell (so far), then update the current module's newq smell */ if(PherPl_ReadBuf[AdjModuleIndex] > PherPl_WriteBuf[ThisModuleIndex]) PherPl_WriteBuf[ThisModuleIndex] = (PherPl_ReadBuf[AdjModuleIndex] - 1); #if SUPER_PHEROMONE_SYSTEM if(PherAls_ReadBuf[AdjModuleIndex] > PherAls_WriteBuf[ThisModuleIndex]) { PherAls_WriteBuf[ThisModuleIndex] = (PherAls_ReadBuf[AdjModuleIndex] - 1); } if (CheckAdjacencyValidity((*AdjModuleRefPtr),ThisModulePtr,0)) { if(PherMars_ReadBuf[AdjModuleIndex] > PherMars_WriteBuf[ThisModuleIndex]) { PherMars_WriteBuf[ThisModuleIndex] = (PherMars_ReadBuf[AdjModuleIndex] - 1); } } #endif /* next adjacent module reference pointer */ AdjModuleRefPtr++; } } } #if SUPER_PHEROMONE_SYSTEM /* Decay pheromones. */ if (PherAls_WriteBuf[ThisModuleIndex]>0) { PherAls_WriteBuf[ThisModuleIndex]--; } if (PherMars_WriteBuf[ThisModuleIndex]>0) { PherMars_WriteBuf[ThisModuleIndex]--; } #endif } } /*If in a network game add pheromon's for other players*/ if(AvP.Network!=I_No_Network && AvP.NetworkAIServer) { /* go through the strategy blocks looking for players*/ int sbIndex; for(sbIndex=0;sbIndex<NumActiveStBlocks;sbIndex++) { STRATEGYBLOCK *playerSbPtr = ActiveStBlockList[sbIndex]; NETGHOSTDATABLOCK *ghostData; if(playerSbPtr->I_SBtype!=I_BehaviourNetGhost) continue; ghostData = (NETGHOSTDATABLOCK *)playerSbPtr->SBdataptr; if(ghostData->type==I_BehaviourMarinePlayer || ghostData->type==I_BehaviourPredatorPlayer) { /*this is another player*/ if(playerSbPtr->containingModule) { PherPl_WriteBuf[playerSbPtr->containingModule->m_aimodule->m_index] = PlayerSmell; AddMarinePheromones(playerSbPtr->containingModule->m_aimodule); } } } } /* That completed, find which module the player is in, set it's smell to the current player smell value, and update the player smell for the next frame */ { extern DISPLAYBLOCK* Player; VECTORCH playerPosition = Player->ObWorld; PLAYER_STATUS *playerStatusPtr= (PLAYER_STATUS *) (Player->ObStrategyBlock->SBdataptr); playerPherModule = (ModuleFromPosition(&playerPosition, playerPherModule)); if(playerPherModule) { //the player must be alive to leave pheromones //(mainly relevant in coop games) if(playerStatusPtr->IsAlive) { PherPl_WriteBuf[playerPherModule->m_aimodule->m_index] = PlayerSmell; if(playerPherModule->name) { if (ShowDebuggingText.Module) { ReleasePrintDebuggingText("Player Module: %d '%s'\n", playerPherModule->m_index,playerPherModule->name); ReleasePrintDebuggingText("Player Module Coords: %d %d %d\n",playerPherModule->m_world.vx,playerPherModule->m_world.vy,playerPherModule->m_world.vz); } #if SUPER_PHEROMONE_SYSTEM AlienPheromoneScale+=3; if (AlienPheromoneScale==0) AlienPheromoneScale=1; { unsigned int prop=DIV_FIXED(PherAls_WriteBuf[playerPherModule->m_aimodule->m_index],AlienPheromoneScale); textprint("Alien readable pheromones in Player Module: %d\n",prop); } /* No scale for 'marine' pheromones, the player will never see it. */ #endif } } } } PlayerSmell++; #if SUPER_PHEROMONE_SYSTEM /* Note that marines should add pheromones at the AI level... */ { unsigned int *tempBufPointer = PherAls_ReadBuf; PherAls_ReadBuf = PherAls_WriteBuf; PherAls_WriteBuf= tempBufPointer; } /* As should the pathfinding system. */ { unsigned int *tempBufPointer = PherMars_ReadBuf; PherMars_ReadBuf = PherMars_WriteBuf; PherMars_WriteBuf= tempBufPointer; } #endif /* swap the read and write buffers: behaviours access most recent data thro' the read buffer */ { unsigned int *tempBufPointer = PherPl_ReadBuf; PherPl_ReadBuf = PherPl_WriteBuf; PherPl_WriteBuf = tempBufPointer; } #if logPheromoneDiagnostics LogPlayerPherValues(); #endif } /*----------------------Patrick 14/11/96--------------------------- Ai Pheromone system. This system just keeps track of how many aliens are in each module, and is calculated from scratch at the start of each frame. Also, the numactivealiens bit of the hive data block is calculated for this frame. -------------------------------------------------------------------*/ void AiPheromoneSystem(void) { int sbIndex = 0; STRATEGYBLOCK *sbPtr; int i; /* first, zero the buffer, and hive counter */ for(i=0;i<AIModuleArraySize;i++) PherAi_Buf[i] = 0; /* next, have a look at the sb list */ while(sbIndex < NumActiveStBlocks) { sbPtr = ActiveStBlockList[sbIndex++]; if((sbPtr->I_SBtype == I_BehaviourAlien)||(sbPtr->I_SBtype == I_BehaviourMarine)) { if(sbPtr->containingModule) { PherAi_Buf[(sbPtr->containingModule->m_aimodule->m_index)]++; } } } } #if logPheromoneDiagnostics /* write out a list of module ajacencies */ static void LogModuleAdjacencies(void) { extern SCENE Global_Scene; extern SCENEMODULE **Global_ModulePtr; GLOBALASSERT(0); /* This function does not use AI modules yet! */ FILE *logFile; int i; SCENEMODULE *ScenePtr; MODULE **ModuleListPointer; MODULE *ThisModulePtr; int ThisModuleIndex; MREF *AdjModuleRefPtr; int AdjModuleIndex; LOCALASSERT(Global_ModulePtr != 0); ScenePtr = Global_ModulePtr[Global_Scene]; ModuleListPointer = ScenePtr->sm_marray; logFile = fopen("D:/PATRICK/MODADJ.TXT","w"); if(logFile) { LOCALASSERT(ModuleArraySize); for(i = 0; i < ModuleArraySize; i++) { ThisModulePtr = ModuleListPointer[i]; LOCALASSERT(ThisModulePtr); /* get it's index */ ThisModuleIndex = ThisModulePtr->m_index; LOCALASSERT(ThisModuleIndex >= 0); LOCALASSERT(ThisModuleIndex < ModuleArraySize); fprintf(logFile, "Module %d Adjoing modules: ", ThisModuleIndex); /* get a pointer to the list of physically adjacent modules and traverse them */ AdjModuleRefPtr = ThisModulePtr->m_link_ptrs; if(AdjModuleRefPtr == 0) { fprintf(logFile, " None/n"); } else { while(AdjModuleRefPtr->mref_ptr != 0) { /* get the index */ AdjModuleIndex = (AdjModuleRefPtr->mref_ptr)->m_index; fprintf(logFile, " %d,", AdjModuleIndex); /* next adjacent module reference pointer */ AdjModuleRefPtr++; } fprintf(logFile, "\n"); } } fclose(logFile); } /* also, initialise pheromone value file */ logFile = fopen("D:/PATRICK/MODPPHER.TXT","w"); if(logFile) { fprintf(logFile, "PLAYER PHEROMONE VALUES \n"); fclose(logFile); } } /* Log the player pheromone values */ static void LogPlayerPherValues(void) { FILE *logFile; int i; logFile = fopen("D:/PATRICK/MODPPHER.TXT","a"); if (!logFile) return; fprintf(logFile, "\n ***************************** \n"); for(i=0;i<AIModuleArraySize;i++) { if(i%7 == 0) fprintf(logFile, "\n"); fprintf(logFile, "%5d", PherPl_ReadBuf[i]); } fclose(logFile); } #endif
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <aws/elasticmapreduce/model/InstanceGroupStatus.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace EMR { namespace Model { InstanceGroupStatus::InstanceGroupStatus() : m_state(InstanceGroupState::NOT_SET), m_stateHasBeenSet(false), m_stateChangeReasonHasBeenSet(false), m_timelineHasBeenSet(false) { } InstanceGroupStatus::InstanceGroupStatus(JsonView jsonValue) : m_state(InstanceGroupState::NOT_SET), m_stateHasBeenSet(false), m_stateChangeReasonHasBeenSet(false), m_timelineHasBeenSet(false) { *this = jsonValue; } InstanceGroupStatus& InstanceGroupStatus::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("State")) { m_state = InstanceGroupStateMapper::GetInstanceGroupStateForName(jsonValue.GetString("State")); m_stateHasBeenSet = true; } if(jsonValue.ValueExists("StateChangeReason")) { m_stateChangeReason = jsonValue.GetObject("StateChangeReason"); m_stateChangeReasonHasBeenSet = true; } if(jsonValue.ValueExists("Timeline")) { m_timeline = jsonValue.GetObject("Timeline"); m_timelineHasBeenSet = true; } return *this; } JsonValue InstanceGroupStatus::Jsonize() const { JsonValue payload; if(m_stateHasBeenSet) { payload.WithString("State", InstanceGroupStateMapper::GetNameForInstanceGroupState(m_state)); } if(m_stateChangeReasonHasBeenSet) { payload.WithObject("StateChangeReason", m_stateChangeReason.Jsonize()); } if(m_timelineHasBeenSet) { payload.WithObject("Timeline", m_timeline.Jsonize()); } return payload; } } // namespace Model } // namespace EMR } // namespace Aws
#define BOOST_TEST_MODULE StringConversion #include <boost/test/unit_test.hpp>
int current_lineno = 0;
/* * Copyright (C) 2013 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "modules/mediasource/SourceBuffer.h" #include "bindings/core/v8/ExceptionMessages.h" #include "bindings/core/v8/ExceptionState.h" #include "core/dom/DOMArrayBuffer.h" #include "core/dom/DOMArrayBufferView.h" #include "core/dom/ExceptionCode.h" #include "core/dom/ExecutionContext.h" #include "core/events/Event.h" #include "core/events/GenericEventQueue.h" #include "core/fileapi/FileReaderLoader.h" #include "core/html/TimeRanges.h" #include "core/streams/Stream.h" #include "modules/mediasource/MediaSource.h" #include "platform/Logging.h" #include "platform/TraceEvent.h" #include "public/platform/WebSourceBuffer.h" #include "wtf/MathExtras.h" #include <limits> using blink::WebSourceBuffer; namespace blink { namespace { static bool throwExceptionIfRemovedOrUpdating(bool isRemoved, bool isUpdating, ExceptionState& exceptionState) { if (isRemoved) { exceptionState.throwDOMException(InvalidStateError, "This SourceBuffer has been removed from the parent media source."); return true; } if (isUpdating) { exceptionState.throwDOMException(InvalidStateError, "This SourceBuffer is still processing an 'appendBuffer', 'appendStream', or 'remove' operation."); return true; } return false; } } // namespace SourceBuffer* SourceBuffer::create(PassOwnPtr<WebSourceBuffer> webSourceBuffer, MediaSource* source, GenericEventQueue* asyncEventQueue) { SourceBuffer* sourceBuffer = new SourceBuffer(webSourceBuffer, source, asyncEventQueue); sourceBuffer->suspendIfNeeded(); return sourceBuffer; } SourceBuffer::SourceBuffer(PassOwnPtr<WebSourceBuffer> webSourceBuffer, MediaSource* source, GenericEventQueue* asyncEventQueue) : ActiveDOMObject(source->executionContext()) , m_webSourceBuffer(webSourceBuffer) , m_source(source) , m_trackDefaults(TrackDefaultList::create()) , m_asyncEventQueue(asyncEventQueue) , m_mode(segmentsKeyword()) , m_updating(false) , m_timestampOffset(0) , m_appendWindowStart(0) , m_appendWindowEnd(std::numeric_limits<double>::infinity()) , m_firstInitializationSegmentReceived(false) , m_pendingAppendDataOffset(0) , m_appendBufferAsyncPartRunner(this, &SourceBuffer::appendBufferAsyncPart) , m_pendingRemoveStart(-1) , m_pendingRemoveEnd(-1) , m_removeAsyncPartRunner(this, &SourceBuffer::removeAsyncPart) , m_streamMaxSizeValid(false) , m_streamMaxSize(0) , m_appendStreamAsyncPartRunner(this, &SourceBuffer::appendStreamAsyncPart) { ASSERT(m_webSourceBuffer); ASSERT(m_source); m_webSourceBuffer->setClient(this); } SourceBuffer::~SourceBuffer() { // Oilpan: a SourceBuffer might be finalized without having been // explicitly removed first, hence the asserts below will not // hold. #if !ENABLE(OILPAN) ASSERT(isRemoved()); ASSERT(!m_loader); ASSERT(!m_stream); ASSERT(!m_webSourceBuffer); #endif } const AtomicString& SourceBuffer::segmentsKeyword() { DEFINE_STATIC_LOCAL(const AtomicString, segments, ("segments", AtomicString::ConstructFromLiteral)); return segments; } const AtomicString& SourceBuffer::sequenceKeyword() { DEFINE_STATIC_LOCAL(const AtomicString, sequence, ("sequence", AtomicString::ConstructFromLiteral)); return sequence; } void SourceBuffer::setMode(const AtomicString& newMode, ExceptionState& exceptionState) { // Section 3.1 On setting mode attribute steps. // 1. Let new mode equal the new value being assigned to this attribute. // 2. If this object has been removed from the sourceBuffers attribute of the parent media source, then throw // an INVALID_STATE_ERR exception and abort these steps. // 3. If the updating attribute equals true, then throw an INVALID_STATE_ERR exception and abort these steps. if (throwExceptionIfRemovedOrUpdating(isRemoved(), m_updating, exceptionState)) return; // 4. If the readyState attribute of the parent media source is in the "ended" state then run the following steps: // 4.1 Set the readyState attribute of the parent media source to "open" // 4.2 Queue a task to fire a simple event named sourceopen at the parent media source. m_source->openIfInEndedState(); // 5. If the append state equals PARSING_MEDIA_SEGMENT, then throw an INVALID_STATE_ERR and abort these steps. // 6. If the new mode equals "sequence", then set the group start timestamp to the highest presentation end timestamp. WebSourceBuffer::AppendMode appendMode = WebSourceBuffer::AppendModeSegments; if (newMode == sequenceKeyword()) appendMode = WebSourceBuffer::AppendModeSequence; if (!m_webSourceBuffer->setMode(appendMode)) { exceptionState.throwDOMException(InvalidStateError, "The mode may not be set while the SourceBuffer's append state is 'PARSING_MEDIA_SEGMENT'."); return; } // 7. Update the attribute to new mode. m_mode = newMode; } PassRefPtrWillBeRawPtr<TimeRanges> SourceBuffer::buffered(ExceptionState& exceptionState) const { // Section 3.1 buffered attribute steps. // 1. If this object has been removed from the sourceBuffers attribute of the parent media source then throw an // InvalidStateError exception and abort these steps. if (isRemoved()) { exceptionState.throwDOMException(InvalidStateError, "This SourceBuffer has been removed from the parent media source."); return nullptr; } // 2. Return a new static normalized TimeRanges object for the media segments buffered. return TimeRanges::create(m_webSourceBuffer->buffered()); } double SourceBuffer::timestampOffset() const { return m_timestampOffset; } void SourceBuffer::setTimestampOffset(double offset, ExceptionState& exceptionState) { // Section 3.1 timestampOffset attribute setter steps. // https://dvcs.w3.org/hg/html-media/raw-file/tip/media-source/media-source.html#widl-SourceBuffer-timestampOffset // 1. Let new timestamp offset equal the new value being assigned to this attribute. // 2. If this object has been removed from the sourceBuffers attribute of the parent media source, then throw an // InvalidStateError exception and abort these steps. // 3. If the updating attribute equals true, then throw an InvalidStateError exception and abort these steps. if (throwExceptionIfRemovedOrUpdating(isRemoved(), m_updating, exceptionState)) return; // 4. If the readyState attribute of the parent media source is in the "ended" state then run the following steps: // 4.1 Set the readyState attribute of the parent media source to "open" // 4.2 Queue a task to fire a simple event named sourceopen at the parent media source. m_source->openIfInEndedState(); // 5. If the append state equals PARSING_MEDIA_SEGMENT, then throw an INVALID_STATE_ERR and abort these steps. // 6. If the mode attribute equals "sequence", then set the group start timestamp to new timestamp offset. if (!m_webSourceBuffer->setTimestampOffset(offset)) { exceptionState.throwDOMException(InvalidStateError, "The timestamp offset may not be set while the SourceBuffer's append state is 'PARSING_MEDIA_SEGMENT'."); return; } // 7. Update the attribute to new timestamp offset. m_timestampOffset = offset; } double SourceBuffer::appendWindowStart() const { return m_appendWindowStart; } void SourceBuffer::setAppendWindowStart(double start, ExceptionState& exceptionState) { // Section 3.1 appendWindowStart attribute setter steps. // https://dvcs.w3.org/hg/html-media/raw-file/tip/media-source/media-source.html#widl-SourceBuffer-appendWindowStart // 1. If this object has been removed from the sourceBuffers attribute of the parent media source then throw an // InvalidStateError exception and abort these steps. // 2. If the updating attribute equals true, then throw an InvalidStateError exception and abort these steps. if (throwExceptionIfRemovedOrUpdating(isRemoved(), m_updating, exceptionState)) return; // 3. If the new value is less than 0 or greater than or equal to appendWindowEnd then throw an InvalidAccessError // exception and abort these steps. if (start < 0 || start >= m_appendWindowEnd) { exceptionState.throwDOMException(InvalidAccessError, ExceptionMessages::indexOutsideRange("value", start, 0.0, ExceptionMessages::ExclusiveBound, m_appendWindowEnd, ExceptionMessages::InclusiveBound)); return; } m_webSourceBuffer->setAppendWindowStart(start); // 4. Update the attribute to the new value. m_appendWindowStart = start; } double SourceBuffer::appendWindowEnd() const { return m_appendWindowEnd; } void SourceBuffer::setAppendWindowEnd(double end, ExceptionState& exceptionState) { // Section 3.1 appendWindowEnd attribute setter steps. // https://dvcs.w3.org/hg/html-media/raw-file/tip/media-source/media-source.html#widl-SourceBuffer-appendWindowEnd // 1. If this object has been removed from the sourceBuffers attribute of the parent media source then throw an // InvalidStateError exception and abort these steps. // 2. If the updating attribute equals true, then throw an InvalidStateError exception and abort these steps. if (throwExceptionIfRemovedOrUpdating(isRemoved(), m_updating, exceptionState)) return; // 3. If the new value equals NaN, then throw an InvalidAccessError and abort these steps. if (std::isnan(end)) { exceptionState.throwDOMException(InvalidAccessError, ExceptionMessages::notAFiniteNumber(end)); return; } // 4. If the new value is less than or equal to appendWindowStart then throw an InvalidAccessError // exception and abort these steps. if (end <= m_appendWindowStart) { exceptionState.throwDOMException(InvalidAccessError, ExceptionMessages::indexExceedsMinimumBound("value", end, m_appendWindowStart)); return; } m_webSourceBuffer->setAppendWindowEnd(end); // 5. Update the attribute to the new value. m_appendWindowEnd = end; } void SourceBuffer::appendBuffer(PassRefPtr<DOMArrayBuffer> data, ExceptionState& exceptionState) { // Section 3.2 appendBuffer() // https://dvcs.w3.org/hg/html-media/raw-file/default/media-source/media-source.html#widl-SourceBuffer-appendBuffer-void-ArrayBufferView-data appendBufferInternal(static_cast<const unsigned char*>(data->data()), data->byteLength(), exceptionState); } void SourceBuffer::appendBuffer(PassRefPtr<DOMArrayBufferView> data, ExceptionState& exceptionState) { // Section 3.2 appendBuffer() // https://dvcs.w3.org/hg/html-media/raw-file/default/media-source/media-source.html#widl-SourceBuffer-appendBuffer-void-ArrayBufferView-data appendBufferInternal(static_cast<const unsigned char*>(data->baseAddress()), data->byteLength(), exceptionState); } void SourceBuffer::appendStream(Stream* stream, ExceptionState& exceptionState) { m_streamMaxSizeValid = false; appendStreamInternal(stream, exceptionState); } void SourceBuffer::appendStream(Stream* stream, unsigned long long maxSize, ExceptionState& exceptionState) { m_streamMaxSizeValid = maxSize > 0; if (m_streamMaxSizeValid) m_streamMaxSize = maxSize; appendStreamInternal(stream, exceptionState); } void SourceBuffer::abort(ExceptionState& exceptionState) { // Section 3.2 abort() method steps. // https://dvcs.w3.org/hg/html-media/raw-file/default/media-source/media-source.html#widl-SourceBuffer-abort-void // 1. If this object has been removed from the sourceBuffers attribute of the parent media source // then throw an InvalidStateError exception and abort these steps. // 2. If the readyState attribute of the parent media source is not in the "open" state // then throw an InvalidStateError exception and abort these steps. if (isRemoved()) { exceptionState.throwDOMException(InvalidStateError, "This SourceBuffer has been removed from the parent media source."); return; } if (!m_source->isOpen()) { exceptionState.throwDOMException(InvalidStateError, "The parent media source's readyState is not 'open'."); return; } // 3. If the sourceBuffer.updating attribute equals true, then run the following steps: ... abortIfUpdating(); // 4. Run the reset parser state algorithm. m_webSourceBuffer->abort(); // 5. Set appendWindowStart to 0. setAppendWindowStart(0, exceptionState); // 6. Set appendWindowEnd to positive Infinity. setAppendWindowEnd(std::numeric_limits<double>::infinity(), exceptionState); } void SourceBuffer::remove(double start, double end, ExceptionState& exceptionState) { // Section 3.2 remove() method steps. // 1. If duration equals NaN, then throw an InvalidAccessError exception and abort these steps. // 2. If start is negative or greater than duration, then throw an InvalidAccessError exception and abort these steps. if (start < 0 || (m_source && (std::isnan(m_source->duration()) || start > m_source->duration()))) { exceptionState.throwDOMException(InvalidAccessError, ExceptionMessages::indexOutsideRange("start", start, 0.0, ExceptionMessages::ExclusiveBound, !m_source || std::isnan(m_source->duration()) ? 0 : m_source->duration(), ExceptionMessages::ExclusiveBound)); return; } // 3. If end is less than or equal to start or end equals NaN, then throw an InvalidAccessError exception and abort these steps. if (end <= start || std::isnan(end)) { exceptionState.throwDOMException(InvalidAccessError, "The end value provided (" + String::number(end) + ") must be greater than the start value provided (" + String::number(start) + ")."); return; } // 4. If this object has been removed from the sourceBuffers attribute of the parent media source then throw an // InvalidStateError exception and abort these steps. // 5. If the updating attribute equals true, then throw an InvalidStateError exception and abort these steps. if (throwExceptionIfRemovedOrUpdating(isRemoved(), m_updating, exceptionState)) return; TRACE_EVENT_ASYNC_BEGIN0("media", "SourceBuffer::remove", this); // 6. If the readyState attribute of the parent media source is in the "ended" state then run the following steps: // 6.1. Set the readyState attribute of the parent media source to "open" // 6.2. Queue a task to fire a simple event named sourceopen at the parent media source . m_source->openIfInEndedState(); // 7. Run the range removal algorithm with start and end as the start and end of the removal range. // 7.3. Set the updating attribute to true. m_updating = true; // 7.4. Queue a task to fire a simple event named updatestart at this SourceBuffer object. scheduleEvent(EventTypeNames::updatestart); // 7.5. Return control to the caller and run the rest of the steps asynchronously. m_pendingRemoveStart = start; m_pendingRemoveEnd = end; m_removeAsyncPartRunner.runAsync(); } void SourceBuffer::setTrackDefaults(TrackDefaultList* trackDefaults, ExceptionState& exceptionState) { // Per 02 Dec 2014 Editor's Draft // http://w3c.github.io/media-source/#widl-SourceBuffer-trackDefaults // 1. If this object has been removed from the sourceBuffers attribute of // the parent media source, then throw an InvalidStateError exception // and abort these steps. // 2. If the updating attribute equals true, then throw an InvalidStateError // exception and abort these steps. if (throwExceptionIfRemovedOrUpdating(isRemoved(), m_updating, exceptionState)) return; // 3. Update the attribute to the new value. m_trackDefaults = trackDefaults; } void SourceBuffer::abortIfUpdating() { // Section 3.2 abort() method step 3 substeps. // https://dvcs.w3.org/hg/html-media/raw-file/default/media-source/media-source.html#widl-SourceBuffer-abort-void if (!m_updating) return; const char* traceEventName = 0; if (!m_pendingAppendData.isEmpty()) { traceEventName = "SourceBuffer::appendBuffer"; } else if (m_stream) { traceEventName = "SourceBuffer::appendStream"; } else if (m_pendingRemoveStart != -1) { traceEventName = "SourceBuffer::remove"; } else { ASSERT_NOT_REACHED(); } // 3.1. Abort the buffer append and stream append loop algorithms if they are running. m_appendBufferAsyncPartRunner.stop(); m_pendingAppendData.clear(); m_pendingAppendDataOffset = 0; m_removeAsyncPartRunner.stop(); m_pendingRemoveStart = -1; m_pendingRemoveEnd = -1; m_appendStreamAsyncPartRunner.stop(); clearAppendStreamState(); // 3.2. Set the updating attribute to false. m_updating = false; // 3.3. Queue a task to fire a simple event named abort at this SourceBuffer object. scheduleEvent(EventTypeNames::abort); // 3.4. Queue a task to fire a simple event named updateend at this SourceBuffer object. scheduleEvent(EventTypeNames::updateend); TRACE_EVENT_ASYNC_END0("media", traceEventName, this); } void SourceBuffer::removedFromMediaSource() { if (isRemoved()) return; abortIfUpdating(); m_webSourceBuffer->removedFromMediaSource(); m_webSourceBuffer.clear(); m_source = nullptr; m_asyncEventQueue = nullptr; } void SourceBuffer::initializationSegmentReceived() { ASSERT(m_source); ASSERT(m_updating); // https://dvcs.w3.org/hg/html-media/raw-file/tip/media-source/media-source.html#sourcebuffer-init-segment-received // FIXME: Make steps 1-7 synchronous with this call. // FIXME: Augment the interface to this method to implement compliant steps 4-7 here. // Step 3 (if the first initialization segment received flag is true) is // implemented by caller. if (!m_firstInitializationSegmentReceived) { // 5. If active track flag equals true, then run the following steps: // 5.1. Add this SourceBuffer to activeSourceBuffers. // 5.2. Queue a task to fire a simple event named addsourcebuffer at // activesourcebuffers. m_source->setSourceBufferActive(this); // 6. Set first initialization segment received flag to true. m_firstInitializationSegmentReceived = true; } } bool SourceBuffer::hasPendingActivity() const { return m_source; } void SourceBuffer::suspend() { m_appendBufferAsyncPartRunner.suspend(); m_removeAsyncPartRunner.suspend(); m_appendStreamAsyncPartRunner.suspend(); } void SourceBuffer::resume() { m_appendBufferAsyncPartRunner.resume(); m_removeAsyncPartRunner.resume(); m_appendStreamAsyncPartRunner.resume(); } void SourceBuffer::stop() { m_appendBufferAsyncPartRunner.stop(); m_removeAsyncPartRunner.stop(); m_appendStreamAsyncPartRunner.stop(); } ExecutionContext* SourceBuffer::executionContext() const { return ActiveDOMObject::executionContext(); } const AtomicString& SourceBuffer::interfaceName() const { return EventTargetNames::SourceBuffer; } bool SourceBuffer::isRemoved() const { return !m_source; } void SourceBuffer::scheduleEvent(const AtomicString& eventName) { ASSERT(m_asyncEventQueue); RefPtrWillBeRawPtr<Event> event = Event::create(eventName); event->setTarget(this); m_asyncEventQueue->enqueueEvent(event.release()); } void SourceBuffer::appendBufferInternal(const unsigned char* data, unsigned size, ExceptionState& exceptionState) { // Section 3.2 appendBuffer() // https://dvcs.w3.org/hg/html-media/raw-file/default/media-source/media-source.html#widl-SourceBuffer-appendBuffer-void-ArrayBufferView-data // 1. Run the prepare append algorithm. // https://dvcs.w3.org/hg/html-media/raw-file/default/media-source/media-source.html#sourcebuffer-prepare-append // 1. If this object has been removed from the sourceBuffers attribute of the parent media source then throw an InvalidStateError exception and abort these steps. // 2. If the updating attribute equals true, then throw an InvalidStateError exception and abort these steps. if (throwExceptionIfRemovedOrUpdating(isRemoved(), m_updating, exceptionState)) return; TRACE_EVENT_ASYNC_BEGIN1("media", "SourceBuffer::appendBuffer", this, "size", size); // 3. If the readyState attribute of the parent media source is in the "ended" state then run the following steps: ... m_source->openIfInEndedState(); // Steps 4-5 - end "prepare append" algorithm. // 2. Add data to the end of the input buffer. ASSERT(data || size == 0); if (data) m_pendingAppendData.append(data, size); m_pendingAppendDataOffset = 0; // 3. Set the updating attribute to true. m_updating = true; // 4. Queue a task to fire a simple event named updatestart at this SourceBuffer object. scheduleEvent(EventTypeNames::updatestart); // 5. Asynchronously run the buffer append algorithm. m_appendBufferAsyncPartRunner.runAsync(); TRACE_EVENT_ASYNC_STEP_INTO0("media", "SourceBuffer::appendBuffer", this, "initialDelay"); } void SourceBuffer::appendBufferAsyncPart() { ASSERT(m_updating); // Section 3.5.4 Buffer Append Algorithm // https://dvcs.w3.org/hg/html-media/raw-file/default/media-source/media-source.html#sourcebuffer-buffer-append // 1. Run the segment parser loop algorithm. // Step 2 doesn't apply since we run Step 1 synchronously here. ASSERT(m_pendingAppendData.size() >= m_pendingAppendDataOffset); size_t appendSize = m_pendingAppendData.size() - m_pendingAppendDataOffset; // Impose an arbitrary max size for a single append() call so that an append // doesn't block the renderer event loop very long. This value was selected // by looking at YouTube SourceBuffer usage across a variety of bitrates. // This value allows relatively large appends while keeping append() call // duration in the ~5-15ms range. const size_t MaxAppendSize = 128 * 1024; if (appendSize > MaxAppendSize) appendSize = MaxAppendSize; TRACE_EVENT_ASYNC_STEP_INTO1("media", "SourceBuffer::appendBuffer", this, "appending", "appendSize", static_cast<unsigned>(appendSize)); // |zero| is used for 0 byte appends so we always have a valid pointer. // We need to convey all appends, even 0 byte ones to |m_webSourceBuffer| // so that it can clear its end of stream state if necessary. unsigned char zero = 0; unsigned char* appendData = &zero; if (appendSize) appendData = m_pendingAppendData.data() + m_pendingAppendDataOffset; m_webSourceBuffer->append(appendData, appendSize, &m_timestampOffset); m_pendingAppendDataOffset += appendSize; if (m_pendingAppendDataOffset < m_pendingAppendData.size()) { m_appendBufferAsyncPartRunner.runAsync(); TRACE_EVENT_ASYNC_STEP_INTO0("media", "SourceBuffer::appendBuffer", this, "nextPieceDelay"); return; } // 3. Set the updating attribute to false. m_updating = false; m_pendingAppendData.clear(); m_pendingAppendDataOffset = 0; // 4. Queue a task to fire a simple event named update at this SourceBuffer object. scheduleEvent(EventTypeNames::update); // 5. Queue a task to fire a simple event named updateend at this SourceBuffer object. scheduleEvent(EventTypeNames::updateend); TRACE_EVENT_ASYNC_END0("media", "SourceBuffer::appendBuffer", this); } void SourceBuffer::removeAsyncPart() { ASSERT(m_updating); ASSERT(m_pendingRemoveStart >= 0); ASSERT(m_pendingRemoveStart < m_pendingRemoveEnd); // Section 3.2 remove() method steps // https://dvcs.w3.org/hg/html-media/raw-file/default/media-source/media-source.html#widl-SourceBuffer-remove-void-double-start-double-end // 9. Run the coded frame removal algorithm with start and end as the start and end of the removal range. m_webSourceBuffer->remove(m_pendingRemoveStart, m_pendingRemoveEnd); // 10. Set the updating attribute to false. m_updating = false; m_pendingRemoveStart = -1; m_pendingRemoveEnd = -1; // 11. Queue a task to fire a simple event named update at this SourceBuffer object. scheduleEvent(EventTypeNames::update); // 12. Queue a task to fire a simple event named updateend at this SourceBuffer object. scheduleEvent(EventTypeNames::updateend); } void SourceBuffer::appendStreamInternal(Stream* stream, ExceptionState& exceptionState) { // Section 3.2 appendStream() // https://dvcs.w3.org/hg/html-media/raw-file/default/media-source/media-source.html#widl-SourceBuffer-appendStream-void-Stream-stream-unsigned-long-long-maxSize // (0. If the stream has been neutered, then throw an InvalidAccessError exception and abort these steps.) if (stream->isNeutered()) { exceptionState.throwDOMException(InvalidAccessError, "The stream provided has been neutered."); return; } // 1. Run the prepare append algorithm. // Section 3.5.4 Prepare Append Algorithm. // https://dvcs.w3.org/hg/html-media/raw-file/default/media-source/media-source.html#sourcebuffer-prepare-append // 1. If this object has been removed from the sourceBuffers attribute of the parent media source then throw an InvalidStateError exception and abort these steps. // 2. If the updating attribute equals true, then throw an InvalidStateError exception and abort these steps. if (throwExceptionIfRemovedOrUpdating(isRemoved(), m_updating, exceptionState)) return; TRACE_EVENT_ASYNC_BEGIN0("media", "SourceBuffer::appendStream", this); // 3. If the readyState attribute of the parent media source is in the "ended" state then run the following steps: ... m_source->openIfInEndedState(); // Steps 4-5 of the prepare append algorithm are handled by m_webSourceBuffer. // 2. Set the updating attribute to true. m_updating = true; // 3. Queue a task to fire a simple event named updatestart at this SourceBuffer object. scheduleEvent(EventTypeNames::updatestart); // 4. Asynchronously run the stream append loop algorithm with stream and maxSize. stream->neuter(); m_loader = FileReaderLoader::create(FileReaderLoader::ReadByClient, this); m_stream = stream; m_appendStreamAsyncPartRunner.runAsync(); } void SourceBuffer::appendStreamAsyncPart() { ASSERT(m_updating); ASSERT(m_loader); ASSERT(m_stream); // Section 3.5.6 Stream Append Loop // https://dvcs.w3.org/hg/html-media/raw-file/default/media-source/media-source.html#sourcebuffer-stream-append-loop // 1. If maxSize is set, then let bytesLeft equal maxSize. // 2. Loop Top: If maxSize is set and bytesLeft equals 0, then jump to the loop done step below. if (m_streamMaxSizeValid && !m_streamMaxSize) { appendStreamDone(true); return; } // Steps 3-11 are handled by m_loader. // Note: Passing 0 here signals that maxSize was not set. (i.e. Read all the data in the stream). m_loader->start(executionContext(), *m_stream, m_streamMaxSizeValid ? m_streamMaxSize : 0); } void SourceBuffer::appendStreamDone(bool success) { ASSERT(m_updating); ASSERT(m_loader); ASSERT(m_stream); clearAppendStreamState(); if (!success) { // Section 3.5.3 Append Error Algorithm // https://dvcs.w3.org/hg/html-media/raw-file/default/media-source/media-source.html#sourcebuffer-append-error // // 1. Run the reset parser state algorithm. (Handled by caller) // 2. Set the updating attribute to false. m_updating = false; // 3. Queue a task to fire a simple event named error at this SourceBuffer object. scheduleEvent(EventTypeNames::error); // 4. Queue a task to fire a simple event named updateend at this SourceBuffer object. scheduleEvent(EventTypeNames::updateend); TRACE_EVENT_ASYNC_END0("media", "SourceBuffer::appendStream", this); return; } // Section 3.5.6 Stream Append Loop // Steps 1-11 are handled by appendStreamAsyncPart(), |m_loader|, and |m_webSourceBuffer|. // 12. Loop Done: Set the updating attribute to false. m_updating = false; // 13. Queue a task to fire a simple event named update at this SourceBuffer object. scheduleEvent(EventTypeNames::update); // 14. Queue a task to fire a simple event named updateend at this SourceBuffer object. scheduleEvent(EventTypeNames::updateend); TRACE_EVENT_ASYNC_END0("media", "SourceBuffer::appendStream", this); } void SourceBuffer::clearAppendStreamState() { m_streamMaxSizeValid = false; m_streamMaxSize = 0; m_loader.clear(); m_stream = nullptr; } void SourceBuffer::didStartLoading() { WTF_LOG(Media, "SourceBuffer::didStartLoading() %p", this); } void SourceBuffer::didReceiveDataForClient(const char* data, unsigned dataLength) { WTF_LOG(Media, "SourceBuffer::didReceiveDataForClient(%d) %p", dataLength, this); ASSERT(m_updating); ASSERT(m_loader); m_webSourceBuffer->append(reinterpret_cast<const unsigned char*>(data), dataLength, &m_timestampOffset); } void SourceBuffer::didFinishLoading() { WTF_LOG(Media, "SourceBuffer::didFinishLoading() %p", this); appendStreamDone(true); } void SourceBuffer::didFail(FileError::ErrorCode errorCode) { WTF_LOG(Media, "SourceBuffer::didFail(%d) %p", errorCode, this); appendStreamDone(false); } DEFINE_TRACE(SourceBuffer) { visitor->trace(m_source); visitor->trace(m_stream); visitor->trace(m_trackDefaults); visitor->trace(m_asyncEventQueue); RefCountedGarbageCollectedEventTargetWithInlineData<SourceBuffer>::trace(visitor); ActiveDOMObject::trace(visitor); } } // namespace blink
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ // See docs in ../ops/nn_ops.cc. #ifdef INTEL_MKL #define EIGEN_USE_THREADS #include <algorithm> #include "mkldnn.hpp" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/register_types.h" #include "tensorflow/core/kernels/mkl/mkl_pooling_ops_common.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/util/mkl_util.h" #include "tensorflow/core/util/padding.h" using mkldnn::algorithm; using mkldnn::engine; using mkldnn::error; using mkldnn::memory; using mkldnn::pooling_backward; using mkldnn::pooling_forward; using mkldnn::prop_kind; namespace tensorflow { typedef Eigen::ThreadPoolDevice CPUDevice; // An implementation of MaxPooling (forward). template <typename Device, typename T, bool native_format = false> class MklMaxPoolingOp : public MklPoolingForwardOpBase<T> { public: explicit MklMaxPoolingOp(OpKernelConstruction* context) : MklPoolingForwardOpBase<T>(context) { // In Max Pooling, MKL-DNN does not allow passing workspace as nullptr. // So we set workspace_enabled_ to true. this->workspace_enabled_ = true; this->native_format_ = native_format; } void Compute(OpKernelContext* context) override { try { const Tensor& input_tensor = MklGetInput(context, this->kInputTensorIndexInput); MklDnnShape dnn_shape_input; GetMklShape(context, this->kInputTensorIndexInput, &dnn_shape_input, this->native_format_); this->SanityCheckInput(context, input_tensor, dnn_shape_input); if (!context->status().ok()) return; MklDnnData<T> dnn_data_input(&cpu_engine_); MklDnnData<T> dnn_data_output(&cpu_engine_); // Initialize variables for the pooling op. MklPoolParameters pool_params; // Check whether pooling is 2D or 3D. bool is_pool2d = (this->ksize_.size() == 4); // Get the input tensor and initialize the pooling parameters TensorShape input_tensor_shape = input_tensor.shape(); this->InitMklPoolParameters(context, &pool_params, dnn_shape_input, input_tensor_shape); OP_REQUIRES_OK(context, context->status()); // Declare output tensor Tensor* output_tensor = nullptr; // Declare output workspace tensor Tensor* output_ws_tensor = nullptr; memory::dims output_dims_mkl_order; this->GetOutputDims(pool_params, &output_dims_mkl_order); // If input is an empty tensor, allocate an empty output tensor and return if (input_tensor.NumElements() == 0) { const int kOutputIndex = 0; this->AllocateEmptyOutputTensor(context, kOutputIndex, &pool_params, output_dims_mkl_order, &output_tensor); bool int8_forward_inference = std::is_same<T, qint8>::value || std::is_same<T, quint8>::value; // Allocate an empty workspace tensor if not Quantized MaxPooling // Because Quantized MaxPooling does not have backward pass // Therefore no workspace, which is used to help backward pass in MKL if (!int8_forward_inference) { const int kOutputWorkspaceIndex = 1; // output_ws_tensor is not really used, so using output_dims_mkl_order this->AllocateEmptyOutputTensor(context, kOutputWorkspaceIndex, &pool_params, output_dims_mkl_order, &output_ws_tensor); } return; } // Get the input memory descriptor memory::desc input_md = dnn_shape_input.IsMklTensor() ? dnn_shape_input.GetMklLayout() : is_pool2d ? memory::desc( TFShapeToMklDnnDimsInNCHW( input_tensor_shape, this->data_format_tf_), MklDnnType<T>(), this->data_format_mkldnn_) : memory::desc( TFShapeToMklDnnDimsInNCDHW( input_tensor_shape, this->data_format_tf_), MklDnnType<T>(), this->data_format_mkldnn_); // Get src/filter/stride/padding information memory::dims src_dims = dnn_shape_input.IsMklTensor() ? dnn_shape_input.GetSizesAsMklDnnDims() : is_pool2d ? TFShapeToMklDnnDimsInNCHW(input_tensor.shape(), this->data_format_tf_) : TFShapeToMklDnnDimsInNCDHW(input_tensor.shape(), this->data_format_tf_); memory::dims filter_dims, strides, padding_left, padding_right; this->PoolParamsToDims(&pool_params, &filter_dims, &strides, &padding_left, &padding_right, is_pool2d); // Get a pooling op from the cached pool MklPoolingFwdPrimitive<T>* pooling_fwd = nullptr; prop_kind pooling_prop_kind; bool int8_forward_inference = std::is_same<T, qint8>::value || std::is_same<T, quint8>::value; if (int8_forward_inference) pooling_prop_kind = prop_kind::forward_inference; else pooling_prop_kind = prop_kind::forward_training; MklPoolingParams fwdParams( src_dims, output_dims_mkl_order, filter_dims, strides, padding_left, padding_right, mkldnn::algorithm::pooling_max, pooling_prop_kind, static_cast<memory::format_tag>(this->data_format_mkldnn_), input_md, this->native_format_); pooling_fwd = MklPoolingFwdPrimitiveFactory<T>::Get(fwdParams); // Allocate output tensor. this->AllocateOutputTensor(context, *(pooling_fwd->GetPoolingFwdPd()), output_dims_mkl_order, this->tensor_format_mkldnn_, &output_tensor); OP_REQUIRES_OK(context, context->status()); dnn_data_output.SetUsrMem(pooling_fwd->GetPoolingFwdPd()->dst_desc(), output_tensor); const T* src_data = input_tensor.flat<T>().data(); T* dst_data = output_tensor->flat<T>().data(); std::shared_ptr<stream> fwd_cpu_stream; MklDnnThreadPool eigen_tp(context); fwd_cpu_stream.reset(CreateStream(&eigen_tp, pooling_fwd->GetEngine())); if (int8_forward_inference) { // Execute pooling op pooling_fwd->Execute(src_data, dst_data, nullptr, fwd_cpu_stream); // Pass min, max from input to output. const Tensor& min_input_t = MklGetInput(context, 1); const Tensor& max_input_t = MklGetInput(context, 2); const float min_input = min_input_t.flat<float>()(0); const float max_input = max_input_t.flat<float>()(0); Tensor* output_min = nullptr; Tensor* output_max = nullptr; MklDnnShape output_min_mkl_shape, output_max_mkl_shape; output_min_mkl_shape.SetMklTensor(false); output_max_mkl_shape.SetMklTensor(false); AllocateOutputSetMklShape(context, 1, &output_min, {}, output_min_mkl_shape, this->native_format_); AllocateOutputSetMklShape(context, 2, &output_max, {}, output_max_mkl_shape, this->native_format_); output_min->flat<float>()(0) = min_input; output_max->flat<float>()(0) = max_input; } else { MklDnnData<uint8> dnn_data_wksp(&cpu_engine_); AllocateWorkspaceTensor(context, *(pooling_fwd->GetPoolingFwdPd()), &dnn_data_wksp); OP_REQUIRES_OK(context, context->status()); T* ws_data = static_cast<T*>(dnn_data_wksp.GetOpMem().get_data_handle()); // Execute pooling op. pooling_fwd->Execute(src_data, dst_data, ws_data, fwd_cpu_stream); } } catch (mkldnn::error& e) { string error_msg = "Status: " + std::to_string(e.status) + ", message: " + string(e.message) + ", in file " + string(__FILE__) + ":" + std::to_string(__LINE__); OP_REQUIRES_OK(context, errors::Aborted("Compute received an exception:", error_msg)); } } private: const int kOutputTensorIndexWorkspace = 1; engine cpu_engine_ = engine(engine::kind::cpu, 0); void AllocateWorkspaceTensor( OpKernelContext* context, const pooling_forward::primitive_desc& pool_fwd_prim_desc, MklDnnData<uint8>* dnn_data_wksp) { DCHECK(dnn_data_wksp); Tensor* workspace_tensor = nullptr; memory::desc workspace_pd = pool_fwd_prim_desc.workspace_desc(); size_t workspace_bytes = workspace_pd.get_size(); MklDnnShape workspace_mkl_shape; workspace_mkl_shape.SetMklTensor(false); TensorShape workspace_tf_shape; workspace_tf_shape.AddDim(workspace_bytes); AllocateOutputSetMklShape(context, kOutputTensorIndexWorkspace, &workspace_tensor, workspace_tf_shape, workspace_mkl_shape, this->native_format_); DCHECK(workspace_tensor); dnn_data_wksp->SetUsrMem(workspace_pd, workspace_tensor); } }; // The operation to compute MaxPool gradients. // It takes three inputs: // - The original input tensor // - The original output tensor // - Backprop tensor for output // It produces one output: backprop tensor for input. template <class Device, class T, bool native_format = false> class MklMaxPoolingGradOp : public MklPoolingBackwardOpBase<T> { public: explicit MklMaxPoolingGradOp(OpKernelConstruction* context) : MklPoolingBackwardOpBase<T>(context) { this->native_format_ = native_format; } void Compute(OpKernelContext* context) override { try { const Tensor& orig_input_tensor = MklGetInput(context, kInputTensorIndexOrigInput); const Tensor& grad_tensor = MklGetInput(context, kInputTensorIndexGradient); const Tensor& workspace_tensor = MklGetInput(context, kInputTensorIndexWorkspace); MklDnnShape orig_input_mkl_shape, grad_mkl_shape; GetMklShape(context, kInputTensorIndexOrigInput, &orig_input_mkl_shape, this->native_format_); GetMklShape(context, kInputTensorIndexGradient, &grad_mkl_shape, this->native_format_); if (!context->status().ok()) return; MklDnnData<T> grad_dnn_data(&cpu_engine_); MklDnnData<uint8> workspace_dnn_data(&cpu_engine_); MklPoolParameters pool_params; TensorShape orig_input_shape = orig_input_tensor.shape(); bool is_pool2d = (this->ksize_.size() == 4); this->InitMklPoolParameters(context, &pool_params, orig_input_mkl_shape, orig_input_shape); memory::dims filter_dims, strides, padding_left, padding_right; this->PoolParamsToDims(&pool_params, &filter_dims, &strides, &padding_left, &padding_right, is_pool2d); memory::dims orig_input_dims_mkl_order = orig_input_mkl_shape.IsMklTensor() ? orig_input_mkl_shape.GetSizesAsMklDnnDims() : is_pool2d ? TFShapeToMklDnnDimsInNCHW(orig_input_shape, this->data_format_tf_) : TFShapeToMklDnnDimsInNCDHW(orig_input_shape, this->data_format_tf_); memory::dims diff_dst_dims = grad_mkl_shape.IsMklTensor() ? grad_mkl_shape.GetSizesAsMklDnnDims() : is_pool2d ? TFShapeToMklDnnDimsInNCHW(grad_tensor.shape(), this->data_format_tf_) : TFShapeToMklDnnDimsInNCDHW(grad_tensor.shape(), this->data_format_tf_); memory::dims output_dims_mkl_order; this->GetOutputDims(pool_params, &output_dims_mkl_order); // get src mem desc memory::desc src_md = orig_input_mkl_shape.IsMklTensor() ? orig_input_mkl_shape.GetMklLayout() : memory::desc(orig_input_dims_mkl_order, MklDnnType<T>(), this->data_format_mkldnn_); // Get diff_dst memory descriptor. memory::desc diff_dst_md = grad_mkl_shape.IsMklTensor() ? grad_mkl_shape.GetMklLayout() : memory::desc(diff_dst_dims, MklDnnType<T>(), this->data_format_mkldnn_); MklPoolingParams bwdParams( orig_input_dims_mkl_order, output_dims_mkl_order, filter_dims, strides, padding_left, padding_right, mkldnn::algorithm::pooling_max, prop_kind::forward_training, static_cast<memory::format_tag>(this->data_format_mkldnn_), src_md, this->native_format_); MklPoolingBwdPrimitive<T>* pooling_bwd = MklPoolingBwdPrimitiveFactory<T>::Get(bwdParams); std::shared_ptr<stream> bwd_cpu_stream; MklDnnThreadPool eigen_tp(context); bwd_cpu_stream.reset(CreateStream(&eigen_tp, pooling_bwd->GetEngine())); // Allocate output tensor and memory primitive. Tensor* output_tensor = nullptr; this->AllocateOutputTensor(context, *(pooling_bwd->GetPoolingBwdPd()), orig_input_dims_mkl_order, this->tensor_format_mkldnn_, &output_tensor); // Check if diff_dst needs to be reordered. std::shared_ptr<PoolingBwdPd> pooling_bwd_pd = pooling_bwd->GetPoolingBwdPd(); T* diff_dst_data = nullptr; if (!this->native_format_ && (diff_dst_md != pooling_bwd_pd->diff_dst_desc())) { grad_dnn_data.SetUsrMem(diff_dst_md, &grad_tensor); grad_dnn_data.CheckReorderToOpMem(pooling_bwd_pd->diff_dst_desc(), cpu_engine_, context); diff_dst_data = static_cast<T*>(grad_dnn_data.GetOpMem().get_data_handle()); } else { diff_dst_data = static_cast<T*>(const_cast<T*>(grad_tensor.flat<T>().data())); } void* ws_data = static_cast<void*>( const_cast<uint8*>(workspace_tensor.flat<uint8>().data())); T* diff_src_data = output_tensor->flat<T>().data(); // Execute pooling op. pooling_bwd->Execute(diff_dst_data, diff_src_data, ws_data, bwd_cpu_stream); } catch (mkldnn::error& e) { string error_msg = "Status:" + std::to_string(e.status) + ", message: " + string(e.message) + ". in file " + string(__FILE__) + ":" + std::to_string(__LINE__); OP_REQUIRES_OK(context, errors::Aborted("Compute received an exception:", error_msg)); } } private: // .Input("orig_input: T") // .Input("orig_output: T") // .Input("grad: T") // .Input("workspace: T") const int kInputTensorIndexOrigInput = 0; const int kInputTensorIndexOrigOutput = 1; const int kInputTensorIndexGradient = 2; const int kInputTensorIndexWorkspace = 3; engine cpu_engine_ = engine(engine::kind::cpu, 0); }; // MklMaxPoolingGradOp #define REGISTER_MKL_MAXPOOL3D_KERNELS(T) \ REGISTER_KERNEL_BUILDER( \ Name("_MklMaxPool3D") \ .Device(DEVICE_CPU) \ .TypeConstraint<T>("T") \ .Label(mkl_op_registry::kMklLayoutDependentOpLabel), \ MklMaxPoolingOp<CPUDevice, T>); \ REGISTER_KERNEL_BUILDER( \ Name("_MklMaxPool3DGrad") \ .Device(DEVICE_CPU) \ .TypeConstraint<T>("T") \ .Label(mkl_op_registry::kMklLayoutDependentOpLabel), \ MklMaxPoolingGradOp<CPUDevice, T>); \ REGISTER_KERNEL_BUILDER(Name("_MklNativeMaxPool3D") \ .Device(DEVICE_CPU) \ .TypeConstraint<T>("T") \ .Label(mkl_op_registry::kMklNameChangeOpLabel), \ MklMaxPoolingOp<CPUDevice, T, true>); \ REGISTER_KERNEL_BUILDER(Name("_MklNativeMaxPool3DGrad") \ .Device(DEVICE_CPU) \ .TypeConstraint<T>("T") \ .Label(mkl_op_registry::kMklNameChangeOpLabel), \ MklMaxPoolingGradOp<CPUDevice, T, true>); TF_CALL_float(REGISTER_MKL_MAXPOOL3D_KERNELS); TF_CALL_bfloat16(REGISTER_MKL_MAXPOOL3D_KERNELS); #define REGISTER_MKL_MAXPOOL_KERNELS(T) \ REGISTER_KERNEL_BUILDER( \ Name("_MklMaxPool") \ .Device(DEVICE_CPU) \ .TypeConstraint<T>("T") \ .Label(mkl_op_registry::kMklLayoutDependentOpLabel), \ MklMaxPoolingOp<CPUDevice, T>); \ REGISTER_KERNEL_BUILDER( \ Name("_MklMaxPoolGrad") \ .Device(DEVICE_CPU) \ .TypeConstraint<T>("T") \ .Label(mkl_op_registry::kMklLayoutDependentOpLabel), \ MklMaxPoolingGradOp<CPUDevice, T>); \ REGISTER_KERNEL_BUILDER(Name("_MklNativeMaxPool") \ .Device(DEVICE_CPU) \ .TypeConstraint<T>("T") \ .Label(mkl_op_registry::kMklNameChangeOpLabel), \ MklMaxPoolingOp<CPUDevice, T, true>); \ REGISTER_KERNEL_BUILDER(Name("_MklNativeMaxPoolGrad") \ .Device(DEVICE_CPU) \ .TypeConstraint<T>("T") \ .Label(mkl_op_registry::kMklNameChangeOpLabel), \ MklMaxPoolingGradOp<CPUDevice, T, true>); TF_CALL_float(REGISTER_MKL_MAXPOOL_KERNELS); TF_CALL_bfloat16(REGISTER_MKL_MAXPOOL_KERNELS); REGISTER_KERNEL_BUILDER(Name("_MklQuantizedMaxPool") .Device(DEVICE_CPU) .TypeConstraint<quint8>("T") .Label(mkl_op_registry::kMklQuantizedOpLabel), MklMaxPoolingOp<CPUDevice, quint8, true>); REGISTER_KERNEL_BUILDER(Name("_MklQuantizedMaxPool") .Device(DEVICE_CPU) .TypeConstraint<qint8>("T") .Label(mkl_op_registry::kMklQuantizedOpLabel), MklMaxPoolingOp<CPUDevice, qint8, true>); } // namespace tensorflow #endif // INTEL_MKL
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) | | Copyright (c) 1997-2010 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include "hphp/runtime/ext/imagick/ext_imagick.h" #include "hphp/runtime/base/array-init.h" #include <utility> namespace HPHP { #define IMAGICKPIXEL_THROW imagickThrow<ImagickPixelException> using PixelGetFunction = double (*)(const PixelWand*); using PixelSetFunction = void (*)(PixelWand*, const double); Object createImagickPixel(PixelWand* wand, bool owner) { Object ret = ImagickPixel::allocObject(); setWandResource(s_ImagickPixel, ret, wand, owner); return ret; } Array createImagickPixelArray(size_t num, PixelWand* wands[], bool owner) { if (wands == nullptr) { return Array(); } else { VecInit ret(num); for (int i = 0; i < num; ++i) { ret.append(createImagickPixel(wands[i], owner)); } return ret.toArray(); } } ALWAYS_INLINE req::ptr<WandResource<PixelWand>> getPixelWand(const Variant& obj) { if (!obj.isObject()) { IMAGICKPIXEL_THROW("Invalid color parameter provided"); } else if (!obj.getObjectData()->instanceof(s_ImagickPixel)) { IMAGICKPIXEL_THROW( "The parameter must be an instance of ImagickPixel or a string"); } else { auto wand = getPixelWandResource(obj.asCObjRef()); return req::make<WandResource<PixelWand>>(wand->getWand(), false); } } req::ptr<WandResource<PixelWand>> newPixelWand() { auto ret = req::make<WandResource<PixelWand>>(NewPixelWand()); if (ret->getWand() == nullptr) { IMAGICKPIXEL_THROW("Failed to allocate PixelWand structure"); } return ret; } req::ptr<WandResource<PixelWand>> buildColorWand(const Variant& color) { if (!color.isString()) { return getPixelWand(color); } auto ret = newPixelWand(); auto status = PixelSetColor(ret->getWand(), color.asCStrRef().c_str()); if (status == MagickFalse) { IMAGICKPIXEL_THROW("Unrecognized color string"); } return ret; } req::ptr<WandResource<PixelWand>> buildOpacityWand(const Variant& opacity) { if (!opacity.isInteger() && !opacity.isDouble()) { return getPixelWand(opacity); } auto ret = newPixelWand(); PixelSetOpacity(ret->getWand(), opacity.toDouble()); return ret; } ////////////////////////////////////////////////////////////////////////////// // class ImagickPixel static bool HHVM_METHOD(ImagickPixel, clear) { auto wand = getPixelWandResource(Object{this_}); ClearPixelWand(wand->getWand()); return true; } static void HHVM_METHOD(ImagickPixel, __construct, const String& color) { auto wand = NewPixelWand(); if (wand == nullptr) { IMAGICKPIXEL_THROW("Failed to allocate PixelWand structure"); } else { setWandResource(s_ImagickPixel, Object{this_}, wand); } if (!color.isNull() && !color.empty()) { if (PixelSetColor(wand, color.c_str()) == MagickFalse) { IMAGICKPIXEL_THROW("Unable to construct ImagickPixel"); } } } static bool HHVM_METHOD(ImagickPixel, destroy) { return HHVM_MN(ImagickPixel, clear)(this_); } static Array HHVM_METHOD(ImagickPixel, getColor, bool normalized) { static const PixelGetFunction pixelGet[4] = { PixelGetRed, PixelGetGreen, PixelGetBlue, PixelGetAlpha }; static const StaticString key[4] = { s_r, s_g, s_b, s_a }; auto wand = getPixelWandResource(Object{this_}); DictInit ret(4); for (int i = 0; i < 4; ++i) { double color = pixelGet[i](wand->getWand()); if (i < 3 && !normalized) { color *= 255; ret.set(key[i], (int64_t)(color > 0.0 ? color + 0.5 : color - 0.5)); } else { ret.set(key[i], color); } } return ret.toArray(); } static String HHVM_METHOD(ImagickPixel, getColorAsString) { auto wand = getPixelWandResource(Object{this_}); return convertMagickString(PixelGetColorAsString(wand->getWand())); } static int64_t HHVM_METHOD(ImagickPixel, getColorCount) { auto wand = getPixelWandResource(Object{this_}); return PixelGetColorCount(wand->getWand()); } static double HHVM_METHOD(ImagickPixel, getColorValue, int64_t color) { static const PixelGetFunction pixelGet[] = { PixelGetBlack, PixelGetBlue, PixelGetCyan, PixelGetGreen, PixelGetRed, PixelGetYellow, PixelGetMagenta, PixelGetOpacity, PixelGetAlpha, PixelGetFuzz }; if (0 <= color && color < sizeof(pixelGet) / sizeof(pixelGet[0])) { auto wand = getPixelWandResource(Object{this_}); return pixelGet[color](wand->getWand()); } else { IMAGICKPIXEL_THROW("Unknown color type"); } } static Array HHVM_METHOD(ImagickPixel, getHSL) { auto wand = getPixelWandResource(Object{this_}); double hue, saturation, luminosity; PixelGetHSL(wand->getWand(), &hue, &saturation, &luminosity); return make_dict_array( s_hue, hue, s_saturation, saturation, s_luminosity, luminosity); } static bool isSimilar(ObjectData* this_, const Variant& color, double fuzz, bool useQuantum) { auto wand = getPixelWandResource(Object{this_}); auto pixel = buildColorWand(color); if (useQuantum) { fuzz *= QuantumRange; } return IsPixelWandSimilar(wand->getWand(), pixel->getWand(), fuzz) != MagickFalse; } static bool HHVM_METHOD(ImagickPixel, isPixelSimilar, const Variant& color, double fuzz) { return isSimilar(this_, color, fuzz, true); } static bool HHVM_METHOD(ImagickPixel, isSimilar, const Variant& color, double fuzz) { raiseDeprecated(s_ImagickPixel.c_str(), "isSimilar", s_ImagickPixel.c_str(), "isPixelSimilar"); return isSimilar(this_, color, fuzz, false); } static bool HHVM_METHOD(ImagickPixel, setColor, const String& color) { auto wand = getPixelWandResource(Object{this_}); if (PixelSetColor(wand->getWand(), color.c_str()) == MagickFalse) { IMAGICKPIXEL_THROW("Unable to set ImagickPixel color"); } return true; } static bool HHVM_METHOD(ImagickPixel, setColorValue, int64_t color, double value) { static const PixelSetFunction pixelSet[] = { PixelSetBlack, PixelSetBlue, PixelSetCyan, PixelSetGreen, PixelSetRed, PixelSetYellow, PixelSetMagenta, PixelSetOpacity, PixelSetAlpha, PixelSetFuzz }; if (0 <= color && color < sizeof(pixelSet) / sizeof(pixelSet[0])) { auto wand = getPixelWandResource(Object{this_}); pixelSet[color](wand->getWand(), value); return true; } else { IMAGICKPIXEL_THROW("Unknown color type"); } } static bool HHVM_METHOD(ImagickPixel, setHSL, double hue, double saturation, double luminosity) { auto wand = getPixelWandResource(Object{this_}); PixelSetHSL(wand->getWand(), hue, saturation, luminosity); return true; } #undef IMAGICKPIXEL_THROW void ImagickExtension::loadImagickPixelClass() { HHVM_ME(ImagickPixel, clear); HHVM_ME(ImagickPixel, __construct); HHVM_ME(ImagickPixel, destroy); HHVM_ME(ImagickPixel, getColor); HHVM_ME(ImagickPixel, getColorAsString); HHVM_ME(ImagickPixel, getColorCount); HHVM_ME(ImagickPixel, getColorValue); HHVM_ME(ImagickPixel, getHSL); HHVM_ME(ImagickPixel, isPixelSimilar); HHVM_ME(ImagickPixel, isSimilar); HHVM_ME(ImagickPixel, setColor); HHVM_ME(ImagickPixel, setColorValue); HHVM_ME(ImagickPixel, setHSL); } ////////////////////////////////////////////////////////////////////////////// } // namespace HPHP
#include "global.hpp" #include "SDL.h" namespace global { SDL_Window *window = nullptr; SDL_Renderer *renderer = nullptr; }
// Copyright 2014 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "trunks/password_authorization_delegate.h" #include <base/logging.h> #include "trunks/tpm_generated.h" namespace trunks { const uint8_t kContinueSession = 1; PasswordAuthorizationDelegate::PasswordAuthorizationDelegate( const std::string& password) { password_ = Make_TPM2B_DIGEST(password); } PasswordAuthorizationDelegate::~PasswordAuthorizationDelegate() {} bool PasswordAuthorizationDelegate::GetCommandAuthorization( const std::string& command_hash, bool is_command_parameter_encryption_possible, bool is_response_parameter_encryption_possible, std::string* authorization) { TPMS_AUTH_COMMAND auth; auth.session_handle = TPM_RS_PW; auth.nonce.size = 0; auth.session_attributes = kContinueSession; auth.hmac = password_; TPM_RC serialize_error = Serialize_TPMS_AUTH_COMMAND(auth, authorization); if (serialize_error != TPM_RC_SUCCESS) { LOG(ERROR) << __func__ << ": could not serialize command auth."; return false; } return true; } bool PasswordAuthorizationDelegate::CheckResponseAuthorization( const std::string& response_hash, const std::string& authorization) { TPMS_AUTH_RESPONSE auth_response; std::string mutable_auth_string(authorization); std::string auth_bytes; TPM_RC parse_error; parse_error = Parse_TPMS_AUTH_RESPONSE(&mutable_auth_string, &auth_response, &auth_bytes); if (authorization.size() != auth_bytes.size()) { LOG(ERROR) << __func__ << ": Authorization string was of wrong length."; return false; } if (parse_error != TPM_RC_SUCCESS) { LOG(ERROR) << __func__ << ": could not parse authorization response."; return false; } if (auth_response.nonce.size != 0) { LOG(ERROR) << __func__ << ": received a non zero length nonce."; return false; } if (auth_response.hmac.size != 0) { LOG(ERROR) << __func__ << ": received a non zero length hmac."; return false; } if (auth_response.session_attributes != kContinueSession) { LOG(ERROR) << __func__ << ": received wrong session attributes."; return false; } return true; } bool PasswordAuthorizationDelegate::EncryptCommandParameter( std::string* parameter) { return true; } bool PasswordAuthorizationDelegate::DecryptResponseParameter( std::string* parameter) { return true; } bool PasswordAuthorizationDelegate::GetTpmNonce(std::string* nonce) { return false; } } // namespace trunks
//============================================================================== // Copyright 2003 - 2012 LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 - 2012 LRI UMR 8623 CNRS/Univ Paris Sud XI // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #define NT2_UNIT_MODULE "nt2 operator toolbox - shift_right/scalar Mode" ////////////////////////////////////////////////////////////////////////////// // unit test behavior of operator components in scalar mode ////////////////////////////////////////////////////////////////////////////// /// created by jt the 18/02/2011 /// #include <nt2/toolbox/operator/include/functions/shift_right.hpp> #include <boost/type_traits/is_same.hpp> #include <nt2/sdk/functor/meta/call.hpp> #include <nt2/sdk/meta/as_integer.hpp> #include <nt2/sdk/meta/as_floating.hpp> #include <nt2/sdk/meta/as_signed.hpp> #include <nt2/sdk/meta/upgrade.hpp> #include <nt2/sdk/meta/downgrade.hpp> #include <nt2/sdk/meta/scalar_of.hpp> #include <boost/dispatch/meta/as_floating.hpp> #include <boost/type_traits/common_type.hpp> #include <nt2/sdk/unit/tests.hpp> #include <nt2/sdk/unit/module.hpp> #include <nt2/sdk/memory/buffer.hpp> #include <nt2/toolbox/constant/constant.hpp> NT2_TEST_CASE_TPL ( shift_right_signed_int__2_0, NT2_INTEGRAL_SIGNED_TYPES) { using nt2::shift_right; using nt2::tag::shift_right_; typedef typename nt2::meta::as_integer<T>::type iT; typedef typename nt2::meta::call<shift_right_(T,iT)>::type r_t; typedef typename nt2::meta::scalar_of<r_t>::type ssr_t; typedef typename nt2::meta::upgrade<T>::type u_t; typedef r_t wished_r_t; // return type conformity test NT2_TEST( (boost::is_same < r_t, wished_r_t >::value) ); std::cout << std::endl; double ulpd; ulpd=0.0; // specific values tests NT2_TEST_EQUAL(shift_right(nt2::Mone<T>(),nt2::One<iT>()), nt2::Mone<r_t>()); NT2_TEST_EQUAL(shift_right(nt2::One<T>(),nt2::One<iT>()), nt2::Zero<r_t>()); NT2_TEST_EQUAL(shift_right(nt2::One<T>(),nt2::Zero<iT>()), nt2::One<r_t>()); NT2_TEST_EQUAL(shift_right(nt2::Zero<T>(),nt2::One<iT>()), nt2::Zero<r_t>()); } // end of test for signed_int_ NT2_TEST_CASE_TPL ( shift_right_unsigned_int__2_0, NT2_UNSIGNED_TYPES) { using nt2::shift_right; using nt2::tag::shift_right_; typedef typename nt2::meta::as_integer<T>::type iT; typedef typename nt2::meta::call<shift_right_(T,iT)>::type r_t; typedef typename nt2::meta::scalar_of<r_t>::type ssr_t; typedef typename nt2::meta::upgrade<T>::type u_t; typedef r_t wished_r_t; // return type conformity test NT2_TEST( (boost::is_same < r_t, wished_r_t >::value) ); std::cout << std::endl; double ulpd; ulpd=0.0; // specific values tests NT2_TEST_EQUAL(shift_right(nt2::One<T>(),nt2::One<iT>()), nt2::Zero<r_t>()); NT2_TEST_EQUAL(shift_right(nt2::One<T>(),nt2::Zero<iT>()), nt2::One<r_t>()); NT2_TEST_EQUAL(shift_right(nt2::Zero<T>(),nt2::One<iT>()), nt2::Zero<r_t>()); } // end of test for unsigned_int_ NT2_TEST_CASE_TPL ( shift_right_real__2_0, NT2_REAL_TYPES) { using nt2::shift_right; using nt2::tag::shift_right_; typedef typename nt2::meta::as_integer<T>::type iT; typedef typename nt2::meta::call<shift_right_(T,iT)>::type r_t; typedef typename nt2::meta::scalar_of<r_t>::type ssr_t; typedef typename nt2::meta::upgrade<T>::type u_t; typedef r_t wished_r_t; // return type conformity test NT2_TEST( (boost::is_same < r_t, wished_r_t >::value) ); std::cout << std::endl; double ulpd; ulpd=0.0; // specific values tests NT2_TEST_EQUAL(shift_right(nt2::One<T>(),nt2::Zero<iT>()), nt2::One<r_t>()); NT2_TEST_EQUAL(shift_right(nt2::Zero<T>(),nt2::One<iT>()), nt2::Zero<r_t>()); } // end of test for floating_
// Copyright (c) 2017 The Bitcoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "guiutiltests.h" #include "chainparams.h" #include "config.h" #include "dstencode.h" #include "guiutil.h" #include "receiverequestdialog.h" namespace { class UtilCfgDummy : public DummyConfig { public: UtilCfgDummy() : useCashAddr(false) {} void SetCashAddrEncoding(bool b) override { useCashAddr = b; } bool UseCashAddrEncoding() const override { return useCashAddr; } const CChainParams &GetChainParams() const override { return Params(CBaseChainParams::MAIN); } private: bool useCashAddr; }; } // anon ns void GUIUtilTests::dummyAddressTest() { CChainParams &params = Params(CBaseChainParams::MAIN); UtilCfgDummy cfg; std::string dummyaddr; cfg.SetCashAddrEncoding(false); dummyaddr = GUIUtil::DummyAddress(params, cfg); QVERIFY(!IsValidDestinationString(dummyaddr, params)); QVERIFY(!dummyaddr.empty()); cfg.SetCashAddrEncoding(true); dummyaddr = GUIUtil::DummyAddress(params, cfg); QVERIFY(!IsValidDestinationString(dummyaddr, params)); QVERIFY(!dummyaddr.empty()); } void GUIUtilTests::toCurrentEncodingTest() { UtilCfgDummy config; // garbage in, garbage out QVERIFY(ToCurrentEncoding("garbage", config) == "garbage"); QString cashaddr_pubkey = "granadeiro:qpm2qsznhks23z7629mms6s4cwef74vcwvy22gdx6a"; QString base58_pubkey = "1BpEi6DfDAUFd7GtittLSdBeYJvcoaVggu"; config.SetCashAddrEncoding(true); QVERIFY(ToCurrentEncoding(cashaddr_pubkey, config) == cashaddr_pubkey); QVERIFY(ToCurrentEncoding(base58_pubkey, config) == cashaddr_pubkey); config.SetCashAddrEncoding(false); QVERIFY(ToCurrentEncoding(cashaddr_pubkey, config) == base58_pubkey); QVERIFY(ToCurrentEncoding(base58_pubkey, config) == base58_pubkey); }
#include <ros/ros.h> #include <tf/transform_broadcaster.h> int main(int argc, char** argv){ ros::init(argc, argv, "robot_tf_publisher"); ros::NodeHandle n; ros::Rate r(100); tf::TransformBroadcaster broadcaster; while(n.ok()){ broadcaster.sendTransform( tf::StampedTransform( tf::Transform(tf::Quaternion(0, 0, 0, 1), tf::Vector3(0.1, 0.0, 0.2)), ros::Time::now(),"base_link", "scanner")); r.sleep(); } }
#include "ObjectSystem/Camera/CameraComponent.hpp" #include "ObjectSystem/Actor.hpp" #include "Engine/Engine.hpp" #include "Graphics/Renderer.hpp" CameraComponent::CameraComponent(Actor* o) : Component(o) { } void CameraComponent::SetViewMatrix(const Matrix4& view) { owner->GetEngine()->GetRenderer()->SetViewMatrix(view); }
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2020 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Kaveh Vahedipour //////////////////////////////////////////////////////////////////////////////// #include "AgencyCache.h" #include "Agency/AsyncAgencyComm.h" #include "Agency/AgencyStrings.h" #include "Agency/Node.h" #include "ApplicationFeatures/ApplicationServer.h" #include "Basics/application-exit.h" #include "GeneralServer/RestHandler.h" #include "Scheduler/Scheduler.h" #include "Scheduler/SchedulerFeature.h" using namespace arangodb; using namespace arangodb::consensus; AgencyCache::AgencyCache( application_features::ApplicationServer& server, AgencyCallbackRegistry& callbackRegistry) : Thread(server, "AgencyCache"), _commitIndex(0), _readDB(server, nullptr, "readDB"), _callbackRegistry(callbackRegistry), _lastSnapshot(0) {} AgencyCache::~AgencyCache() { beginShutdown(); } bool AgencyCache::isSystem() const { return true; } /// Start all agent thread bool AgencyCache::start() { LOG_TOPIC("9a90f", DEBUG, Logger::AGENCY) << "Starting agency cache worker."; Thread::start(); return true; } // Fill existing Builder from readDB, mainly /Plan /Current index_t AgencyCache::get(VPackBuilder& result, std::string const& path) const { result.clear(); std::shared_lock g(_storeLock); if (_commitIndex > 0) { _readDB.get("arango/" + path, result, false); } return _commitIndex; } // Create Builder from readDB, mainly /Plan /Current std::tuple<query_t, index_t> AgencyCache::get(std::string const& path) const { auto ret = std::make_shared<VPackBuilder>(); index_t commitIndex = get(*ret, path); return std::tuple(std::move(ret), commitIndex); } // Get Builder from readDB mainly /Plan /Current query_t AgencyCache::dump() const { auto query = std::make_shared<arangodb::velocypack::Builder>(); { VPackArrayBuilder outer(query.get()); VPackArrayBuilder inner(query.get()); query->add(VPackValue("/")); } auto ret = std::make_shared<VPackBuilder>(); { VPackObjectBuilder o(ret.get()); std::shared_lock g(_storeLock); ret->add("index", VPackValue(_commitIndex)); ret->add(VPackValue("cache")); _readDB.read(query, ret); } return ret; } // Get Builder from readDB, mainly /Plan /Current std::tuple<query_t, index_t> AgencyCache::read(std::vector<std::string> const& paths) const { auto query = std::make_shared<arangodb::velocypack::Builder>(); { VPackArrayBuilder outer(query.get()); VPackArrayBuilder inner(query.get()); for (auto const& i : paths) { query->add(VPackValue(i)); } } auto result = std::make_shared<arangodb::velocypack::Builder>(); std::shared_lock g(_storeLock); if (_commitIndex > 0) { _readDB.read(query, result); } return std::tuple(std::move(result), _commitIndex); } futures::Future<arangodb::Result> AgencyCache::waitFor(index_t index) { std::shared_lock s(_storeLock); if (index <= _commitIndex) { return futures::makeFuture(arangodb::Result()); } // intentionally don't release _storeLock here until we have inserted the promise std::lock_guard w(_waitLock); return _waiting.emplace(index, futures::Promise<arangodb::Result>())->second.getFuture(); } index_t AgencyCache::index() const { std::shared_lock g(_storeLock); return _commitIndex; } // If a "arango/Plan/Databases" key is set, all databases in the Plan are completely // replaced. This means that loadPlan and the maintenance thread have to revisit everything. // In particular, we have to visit all databases in the new Plan as well as all currently // existing databases locally! Therefore we fake all of these databases as if they were // changed in this raft index. std::unordered_set<std::string> AgencyCache::reInitPlan() { std::unordered_set<std::string> planChanges = server().getFeature<ClusterFeature>().allDatabases(); // local databases // And everything under /arango/Plan/Databases: auto keys = _readDB.nodePtr(AgencyCommHelper::path(PLAN) + "/" + DATABASES)->keys(); for (auto const& dbname : keys) { planChanges.emplace(dbname); } planChanges.emplace(); // and the rest return planChanges; } void AgencyCache::handleCallbacksNoLock( VPackSlice slice, std::unordered_set<uint64_t>& uniq, std::vector<uint64_t>& toCall, std::unordered_set<std::string>& planChanges, std::unordered_set<std::string>& currentChanges) { if (!slice.isObject()) { LOG_TOPIC("31514", DEBUG, Logger::CLUSTER) << "Cannot handle callback on non-object " << slice.toJson(); return; } // Collect and normalize keys std::vector<std::string> keys; keys.reserve(slice.length()); for (auto const& i : VPackObjectIterator(slice)) { VPackValueLength l; char const* p = i.key.getString(l); keys.emplace_back(Store::normalize(p, l)); } std::sort(keys.begin(), keys.end()); // Find callbacks, which are a prefix of some key: for (auto const& cb : _callbacks) { auto const& cbkey = cb.first; auto it = std::lower_bound(keys.begin(), keys.end(), cbkey); if (it != keys.end() && it->compare(0, cbkey.size(), cbkey) == 0) { if (uniq.emplace(cb.second).second) { toCall.push_back(cb.second); } } } std::unordered_set<std::string> dbs; const char SLASH ('/'); // Find keys, which are a prefix of a callback: for (auto const& k : keys) { auto it = _callbacks.lower_bound(k); while (it != _callbacks.end() && it->first.compare(0, k.size(), k) == 0) { if (uniq.emplace(it->second).second) { toCall.push_back(it->second); } ++it; } if (k.size() > 8) { std::string_view r(k.c_str() + 8, k.size() - 8); auto rs = r.size(); if (rs > strlen(PLAN) && r.compare(0, strlen(PLAN), PLAN) == 0) { if (rs >= strlen(PLAN_VERSION) && // Plan/Version -> ignore r.compare(0, strlen(PLAN_VERSION), PLAN_VERSION) == 0) { continue; } else if (rs > strlen(PLAN_COLLECTIONS) && // Plan/Collections r.compare(0, strlen(PLAN_COLLECTIONS), PLAN_COLLECTIONS) == 0) { auto tmp = r.substr(strlen(PLAN_COLLECTIONS)); planChanges.emplace(tmp.substr(0,tmp.find(SLASH))); } else if (rs > strlen(PLAN_DATABASES) && // Plan/Databases r.compare(0, strlen(PLAN_DATABASES), PLAN_DATABASES) == 0) { auto tmp = r.substr(strlen(PLAN_DATABASES)); planChanges.emplace(tmp); } else if (rs > strlen(PLAN_VIEWS) && // Plan/Views r.compare(0, strlen(PLAN_VIEWS), (PLAN_VIEWS)) == 0) { auto tmp = r.substr(strlen(PLAN_VIEWS)); planChanges.emplace(tmp.substr(0,tmp.find(SLASH))); } else if (rs > strlen(PLAN_ANALYZERS) && // Plan/Analyzers r.compare(0, strlen(PLAN_ANALYZERS), PLAN_ANALYZERS)==0) { auto tmp = r.substr(strlen(PLAN_ANALYZERS)); planChanges.emplace(tmp.substr(0,tmp.find(SLASH))); } else if (r == "Plan/Databases" || r == "Plan/Collections" || r == "Plan/Views" || r == "Plan/Analyzers" || r == "Plan") { // !! Check documentation of the function before making changes here !! planChanges = reInitPlan(); } else { planChanges.emplace(); // "" to indicate non database } } else if (rs > strlen(CURRENT) && r.compare(0, strlen(CURRENT), CURRENT) == 0) { if (rs >= strlen(CURRENT_VERSION) && // Current/Version is ignored r.compare(0, strlen(CURRENT_VERSION), CURRENT_VERSION) == 0) { continue; } else if (rs > strlen(CURRENT_COLLECTIONS) && // Current/Collections r.compare(0, strlen(CURRENT_COLLECTIONS), CURRENT_COLLECTIONS) == 0) { auto tmp = r.substr(strlen(CURRENT_COLLECTIONS)); currentChanges.emplace(tmp.substr(0,tmp.find(SLASH))); } else if (rs > strlen(CURRENT_DATABASES) && // Current/Databases r.compare(0, strlen(CURRENT_DATABASES), CURRENT_DATABASES) == 0) { auto tmp = r.substr(strlen(CURRENT_DATABASES)); currentChanges.emplace(tmp.substr(0,tmp.find(SLASH))); } else { currentChanges.emplace(); // "" to indicate non database } } } } } void AgencyCache::run() { using namespace std::chrono; TRI_ASSERT(AsyncAgencyCommManager::INSTANCE != nullptr); _commitIndex = 0; _readDB.clear(); double wait = 0.0; auto increaseWaitTime = [&wait]() noexcept { if (wait <= 1.9) { wait += 0.1; } }; // Long poll to agency auto sendTransaction = [&]() { index_t commitIndex = 0; { std::shared_lock g(_storeLock); commitIndex = _commitIndex + 1; } LOG_TOPIC("afede", TRACE, Logger::CLUSTER) << "AgencyCache: poll polls: waiting for commitIndex " << commitIndex; return AsyncAgencyComm().poll(60s, commitIndex); }; // while not stopping // poll agency // if result // if firstIndex == 0 // overwrite readDB, update commitIndex // else // apply logs to local cache // else // wait ever longer until success std::vector<uint64_t> toCall; std::unordered_set<uint64_t> uniq; while (!this->isStopping()) { // we need to make sure that this thread keeps running, so whenever // an exception happens in here, we log it and go on try { uniq.clear(); toCall.clear(); std::this_thread::sleep_for(std::chrono::duration<double>(wait)); // rb holds receives either // * A complete overwrite (firstIndex == 0) // {..., result:{commitIndex:X, firstIndex:0, readDB:{...}}} // * Incremental change to cache (firstIndex != 0) // {..., result:{commitIndex:X, firstIndex:Y, log:[]}} if (server().getFeature<NetworkFeature>().prepared()) { auto ret = sendTransaction() .thenValue( [&](AsyncAgencyCommResult&& rb) { if (rb.ok() && rb.statusCode() == arangodb::fuerte::StatusOK) { index_t curIndex = 0; { std::lock_guard g(_storeLock); curIndex = _commitIndex; } auto slc = rb.slice(); wait = 0.; TRI_ASSERT(slc.hasKey("result")); VPackSlice rs = slc.get("result"); TRI_ASSERT(rs.hasKey("commitIndex")); TRI_ASSERT(rs.get("commitIndex").isNumber()); TRI_ASSERT(rs.hasKey("firstIndex")); TRI_ASSERT(rs.get("firstIndex").isNumber()); index_t commitIndex = rs.get("commitIndex").getNumber<uint64_t>(); index_t firstIndex = rs.get("firstIndex").getNumber<uint64_t>(); if (firstIndex > 0) { // Do incoming logs match our cache's index? if (firstIndex != curIndex + 1) { LOG_TOPIC("a9a09", WARN, Logger::CLUSTER) << "Logs from poll start with index " << firstIndex << " we requested logs from and including " << curIndex << " retrying."; LOG_TOPIC("457e9", TRACE, Logger::CLUSTER) << "Incoming: " << rs.toJson(); increaseWaitTime(); } else { TRI_ASSERT(rs.hasKey("log")); TRI_ASSERT(rs.get("log").isArray()); LOG_TOPIC("4579e", TRACE, Logger::CLUSTER) << "Applying to cache " << rs.get("log").toJson(); for (auto const& i : VPackArrayIterator(rs.get("log"))) { { std::lock_guard g(_storeLock); _readDB.applyTransaction(i); // apply logs _commitIndex = i.get("index").getNumber<uint64_t>(); std::unordered_set<std::string> pc, cc; { std::lock_guard g(_callbacksLock); handleCallbacksNoLock(i.get("query"), uniq, toCall, pc, cc); } for (auto const& i : pc) { _planChanges.emplace(_commitIndex, i); } for (auto const& i : cc) { _currentChanges.emplace(_commitIndex, i); } } } } } else { TRI_ASSERT(rs.hasKey("readDB")); std::lock_guard g(_storeLock); LOG_TOPIC("4579f", TRACE, Logger::CLUSTER) << "Fresh start: overwriting agency cache with " << rs.toJson(); _readDB = rs; // overwrite std::unordered_set<std::string> pc = reInitPlan(); for (auto const& i : pc) { _planChanges.emplace(_commitIndex, i); } // !! Check documentation of the function before making changes here !! _commitIndex = commitIndex; _lastSnapshot = commitIndex; } triggerWaiting(commitIndex); if (firstIndex > 0) { if (!toCall.empty()) { invokeCallbacks(toCall); } } else { invokeAllCallbacks(); } } else { increaseWaitTime(); LOG_TOPIC("9a93e", DEBUG, Logger::CLUSTER) << "Failed to get poll result from agency."; } return futures::makeFuture(); }) .thenError<VPackException>( [&increaseWaitTime](VPackException const& e) { LOG_TOPIC("9a9f3", ERR, Logger::CLUSTER) << "Failed to parse poll result from agency: " << e.what(); increaseWaitTime(); }) .thenError<std::exception>( [&increaseWaitTime](std::exception const& e) { LOG_TOPIC("9a9e3", ERR, Logger::CLUSTER) << "Failed to get poll result from agency: " << e.what(); increaseWaitTime(); }); ret.wait(); } else { increaseWaitTime(); LOG_TOPIC("9393e", DEBUG, Logger::CLUSTER) << "Waiting for network feature to get ready"; } } catch (std::exception const& e) { LOG_TOPIC("544da", ERR, Logger::CLUSTER) << "Caught an error while polling agency updates: " << e.what(); increaseWaitTime(); } catch (...) { LOG_TOPIC("78916", ERR, Logger::CLUSTER) << "Caught an error while polling agency updates"; increaseWaitTime(); } // off to next round we go... } } void AgencyCache::triggerWaiting(index_t commitIndex) { auto* scheduler = SchedulerFeature::SCHEDULER; std::lock_guard w(_waitLock); auto pit = _waiting.begin(); while (pit != _waiting.end()) { if (pit->first > commitIndex) { break; } auto pp = std::make_shared<futures::Promise<Result>>(std::move(pit->second)); if (scheduler && !this->isStopping()) { bool queued = scheduler->queue( RequestLane::CLUSTER_INTERNAL, [pp] { pp->setValue(Result()); }); if (!queued) { LOG_TOPIC("c6473", WARN, Logger::AGENCY) << "Failed to schedule logsForTrigger running in main thread"; pp->setValue(Result()); } } else { pp->setValue(Result(TRI_ERROR_SHUTTING_DOWN)); } pit = _waiting.erase(pit); } } /// Register local callback bool AgencyCache::registerCallback(std::string const& key, uint64_t const& id) { std::string const ckey = Store::normalize(AgencyCommHelper::path(key)); LOG_TOPIC("67bb8", DEBUG, Logger::CLUSTER) << "Registering callback for " << ckey; size_t size = 0; { std::lock_guard g(_callbacksLock); _callbacks.emplace(ckey, id); size = _callbacks.size(); } LOG_TOPIC("31415", TRACE, Logger::CLUSTER) << "Registered callback for " << ckey << " " << size; // this method always returns ok. return true; } /// Unregister local callback void AgencyCache::unregisterCallback(std::string const& key, uint64_t const& id) { std::string const ckey = Store::normalize(AgencyCommHelper::path(key)); LOG_TOPIC("cc768", DEBUG, Logger::CLUSTER) << "Unregistering callback for " << ckey; size_t size = 0; { std::lock_guard g(_callbacksLock); auto range = _callbacks.equal_range(ckey); for (auto it = range.first; it != range.second;) { if (it->second == id) { it = _callbacks.erase(it); break; } else { ++it; } } size = _callbacks.size(); } LOG_TOPIC("034cc", TRACE, Logger::CLUSTER) << "Unregistered callback for " << ckey << " " << size; } /// Orderly shutdown void AgencyCache::beginShutdown() { LOG_TOPIC("a63ae", TRACE, Logger::CLUSTER) << "Clearing books in agency cache"; // trigger all waiting for an index { std::lock_guard g(_waitLock); auto pit = _waiting.begin(); while (pit != _waiting.end()) { pit->second.setValue(Result(TRI_ERROR_SHUTTING_DOWN)); ++pit; } _waiting.clear(); } // trigger all callbacks { std::lock_guard g(_callbacksLock); for (auto const& i : _callbacks) { auto cb = _callbackRegistry.getCallback(i.second); if (cb != nullptr) { LOG_TOPIC("76bb8", DEBUG, Logger::CLUSTER) << "Agency callback " << i << " has been triggered. refetching!"; try { cb->refetchAndUpdate(true, false); } catch (arangodb::basics::Exception const& e) { LOG_TOPIC("c3111", WARN, Logger::AGENCYCOMM) << "Error executing callback: " << e.message(); } } } _callbacks.clear(); } Thread::beginShutdown(); } bool AgencyCache::has(std::string const& path) const { std::shared_lock g(_storeLock); return _readDB.has(AgencyCommHelper::path(path)); } std::vector<bool> AgencyCache::has(std::vector<std::string> const& paths) const { std::vector<bool> ret; ret.reserve(paths.size()); std::shared_lock g(_storeLock); for (auto const& i : paths) { ret.push_back(_readDB.has(i)); } return ret; } void AgencyCache::invokeCallbackNoLock(uint64_t id, std::string const& key) const { auto cb = _callbackRegistry.getCallback(id); if (cb != nullptr) { try { cb->refetchAndUpdate(true, false); LOG_TOPIC("76aa8", DEBUG, Logger::CLUSTER) << "Agency callback " << id << " has been triggered. refetching " << key; } catch (arangodb::basics::Exception const& e) { LOG_TOPIC("c3091", WARN, Logger::AGENCYCOMM) << "Error executing callback: " << e.message(); } } } void AgencyCache::invokeCallbacks(std::vector<uint64_t> const& toCall) const { for (auto i : toCall) { invokeCallbackNoLock(i); } } void AgencyCache::invokeAllCallbacks() const { std::vector<uint64_t> toCall; { std::lock_guard g(_callbacksLock); for (auto i : _callbacks) { toCall.push_back(i.second); } } invokeCallbacks(toCall); } AgencyCache::change_set_t AgencyCache::changedSince( std::string const& what, consensus::index_t const& last) const { static std::vector<std::string> const planGoodies ({ AgencyCommHelper::path(PLAN_ANALYZERS) + "/", AgencyCommHelper::path(PLAN_COLLECTIONS) + "/", AgencyCommHelper::path(PLAN_DATABASES) + "/", AgencyCommHelper::path(PLAN_VIEWS) + "/"}); static std::vector<std::string> const currentGoodies ({ AgencyCommHelper::path(CURRENT_COLLECTIONS) + "/", AgencyCommHelper::path(CURRENT_DATABASES) + "/"}); bool get_rest = false; std::unordered_map<std::string, query_t> db_res; query_t rest_res = nullptr; decltype(_planChanges) const& changes = (what == PLAN) ? _planChanges : _currentChanges; std::vector<std::string> const& goodies = (what == PLAN) ? planGoodies : currentGoodies; std::unordered_set<std::string> databases; std::shared_lock g(_storeLock); auto tmp = _readDB.nodePtr()->hasAsUInt(AgencyCommHelper::path(what) + "/" + VERSION); uint64_t version = tmp.second ? tmp.first : 0; if (last < _lastSnapshot) { get_rest = true; auto keys = _readDB.nodePtr(AgencyCommHelper::path(what) + "/" + DATABASES)->keys(); for (auto& i : keys) { databases.emplace(std::move(i)); } } else { auto it = changes.lower_bound(last+1); if (it != changes.end()) { for (; it != changes.end(); ++it) { if (it->second.empty()) { // Need to get rest get_rest = true; } databases.emplace(it->second); } LOG_TOPIC("d5743", TRACE, Logger::CLUSTER) << "collecting " << databases << " from agency cache"; } else { LOG_TOPIC("d5734", DEBUG, Logger::CLUSTER) << "no changed databases since " << last; return change_set_t(_commitIndex, version, std::move(db_res), std::move(rest_res)); } } if (databases.empty()) { return change_set_t(_commitIndex, version, std::move(db_res), std::move(rest_res)); } { for (auto const& i : databases) { if (!i.empty()) { // actual database auto query = std::make_shared<arangodb::velocypack::Builder>(); { VPackArrayBuilder outer(query.get()); { VPackArrayBuilder inner(query.get()); for (auto const& g : goodies) { // Get goodies for database query->add(VPackValue(g + i)); } }} auto [entry,created] = db_res.try_emplace(i, std::make_shared<VPackBuilder>()); if (created) { _readDB.read(query, entry->second); } else { LOG_TOPIC("31ae3", ERR, Logger::CLUSTER) << "Failed to communicate updated database " << i << " in AgencyCache with maintenance."; FATAL_ERROR_EXIT(); } } } } if (get_rest) { // All the rest, i.e. All keys excluding the usual suspects static std::vector<std::string> const exc { "Analyzers", "Collections", "Databases", "Views"}; auto keys = _readDB.nodePtr(AgencyCommHelper::path(what))->keys(); keys.erase( std::remove_if( std::begin(keys), std::end(keys), [&] (auto x) { return std::binary_search(std::begin(exc), std::end(exc),x);}), std::end(keys)); auto query = std::make_shared<arangodb::velocypack::Builder>(); { VPackArrayBuilder outer(query.get()); for (auto const& i : keys) { VPackArrayBuilder inner(query.get()); query->add(VPackValue(AgencyCommHelper::path(what) + "/" + i)); } } if (_commitIndex > 0) { // Databases rest_res = std::make_shared<VPackBuilder>(); _readDB.read(query, rest_res); } } return change_set_t(_commitIndex, version, std::move(db_res), std::move(rest_res)); } namespace std { ostream& operator<<(ostream& o, AgencyCache::change_set_t const& c) { o << c.ind; return o; } ostream& operator<<(ostream& o, AgencyCache::databases_t const& dbs) { o << "{"; bool first = true; for (auto const& db : dbs) { if (!first) { o << ", "; } else { first = false; } o << '"' << db.first << "\": " << db.second->toJson(); } o << "}"; return o; } }
// b757 : 頸美椰子樹 #include <cstdio> #include <iostream> using namespace std; int main() { double r; while( scanf("%lf", &r )!=EOF ) { cout<< r*9/5 + 32 << endl ; } return 0; }
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "system_test_ability_util.h" #include "status_receiver_host.h" #include "iservice_registry.h" namespace OHOS { namespace STABUtil { using namespace OHOS; using namespace OHOS::AAFwk; using namespace OHOS::AppExecFwk; using namespace OHOS::MTUtil; using namespace OHOS::STtools; using namespace OHOS::EventFwk; std::mutex STAbilityUtil::mutex_; std::shared_ptr<STAbilityUtil> STAbilityUtil::instance_ = nullptr; bool STAbilityUtil::PublishEvent(const std::string &eventName, const int &code, const std::string &data) { Want want; want.SetAction(eventName); CommonEventData commonData; commonData.SetWant(want); commonData.SetCode(code); commonData.SetData(data); return CommonEventManager::PublishCommonEvent(commonData); } void STAbilityUtil::InstallHaps(vector_str &hapNames) { for (auto hapName : hapNames) { Install(hapName); } } void STAbilityUtil::UninstallBundle(vector_str &bundleNames) { for (auto bundleName : bundleNames) { Uninstall(bundleName); } } void STAbilityUtil::KillService(const std::string &serviceName) { system(("kill -9 $(pidof " + serviceName + ") > /dev/null 2>&1").c_str()); } void STAbilityUtil::StartService(const std::string &serviceName, const time_t &delay) { system(("/system/bin/" + serviceName + "& > /dev/null 2>&1").c_str()); std::this_thread::sleep_for(std::chrono::milliseconds(delay)); } void STAbilityUtil::KillBundleProcess(vector_str &bundleNames) { for (std::string bundleName : bundleNames) { KillService(bundleName); } } sptr<IAbilityManager> STAbilityUtil::GetAbilityManagerService() { sptr<ISystemAbilityManager> systemAbilityManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); if (!systemAbilityManager) { HILOG_ERROR("failed to get ability manager service"); return nullptr; } sptr<IRemoteObject> remoteObject = systemAbilityManager->GetSystemAbility(ABILITY_MGR_SERVICE_ID); if (!remoteObject) { HILOG_ERROR("fail to get ability manager proxy."); return nullptr; } HILOG_ERROR("get ability manager proxy success."); return iface_cast<IAbilityManager>(remoteObject); } sptr<IAppMgr> STAbilityUtil::GetAppMgrService() { sptr<ISystemAbilityManager> systemAbilityManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); if (!systemAbilityManager) { HILOG_ERROR("failed to get app manager service"); return nullptr; } sptr<IRemoteObject> remoteObject = systemAbilityManager->GetSystemAbility(APP_MGR_SERVICE_ID); if (!remoteObject) { HILOG_ERROR("fail to get app manager proxy."); return nullptr; } HILOG_ERROR("get app manager proxy success."); return iface_cast<IAppMgr>(remoteObject); } ErrCode STAbilityUtil::StartAbility(const Want &want, sptr<IAbilityManager> &abilityMs, const time_t &delay) { ErrCode result = OHOS::ERR_OK; abilityMs = GetAbilityManagerService(); if (abilityMs == nullptr) { result = OHOS::ERR_INVALID_VALUE; HILOG_ERROR("failed to get ability manager service"); return result; } result = abilityMs->StartAbility(want); std::this_thread::sleep_for(std::chrono::milliseconds(delay)); if (result == OHOS::ERR_OK) { HILOG_INFO("start ability successfully."); } else { HILOG_INFO("failed to start ability."); } return result; } bool STAbilityUtil::StopAbility(const std::string &eventName, const int &code, const std::string &data) { return PublishEvent(eventName, code, data); } ErrCode STAbilityUtil::StopServiceAbility(const Want &want, unsigned int usec) { ErrCode result = OHOS::ERR_OK; sptr<IAbilityManager> abilityMs = GetAbilityManagerService(); if (abilityMs == nullptr) { result = OHOS::ERR_INVALID_VALUE; HILOG_ERROR("failed to get ability manager service"); return result; } result = abilityMs->StopServiceAbility(want); if (result == OHOS::ERR_OK) { HILOG_INFO("stop service ability successfully."); } else { HILOG_INFO("failed to stop service ability."); } return result; } ErrCode STAbilityUtil::ConnectAbility(const Want &want, const sptr<IAbilityConnection> &connect, const sptr<IRemoteObject> &callerToken, unsigned int usec) { ErrCode result = OHOS::ERR_OK; sptr<IAbilityManager> abilityMs = GetAbilityManagerService(); if (abilityMs == nullptr) { result = OHOS::ERR_INVALID_VALUE; HILOG_ERROR("failed to get ability manager service"); return result; } result = abilityMs->ConnectAbility(want, connect, callerToken); if (result == OHOS::ERR_OK) { HILOG_INFO("connect ability successfully."); } else { HILOG_INFO("failed to connect ability."); } return result; } ErrCode STAbilityUtil::DisconnectAbility(const sptr<IAbilityConnection> &connect, unsigned int usec) { ErrCode result = OHOS::ERR_OK; sptr<IAbilityManager> abilityMs = GetAbilityManagerService(); if (abilityMs == nullptr) { result = OHOS::ERR_INVALID_VALUE; HILOG_ERROR("failed to get ability manager service"); return result; } result = abilityMs->DisconnectAbility(connect); if (result == OHOS::ERR_OK) { HILOG_INFO("StopServiceAbility successfully."); } else { HILOG_INFO("failed to StopServiceAbility."); } return result; } Want STAbilityUtil::MakeWant(std::string deviceId, std::string abilityName, std::string bundleName, MAP_STR_STR params) { ElementName element(deviceId, bundleName, abilityName); Want want; want.SetElement(element); for (const auto &param : params) { want.SetParam(param.first, param.second); } return want; } Want STAbilityUtil::MakeWant(std::string deviceId, std::string abilityName, std::string bundleName, vector_str params) { ElementName element(deviceId, bundleName, abilityName); Want want; want.SetElement(element); want.SetParam("operator", params); return want; } ErrCode STAbilityUtil::GetTopAbilityRecordId(int64_t &id, sptr<IAbilityManager> &abilityMs) { ErrCode result = OHOS::ERR_OK; id = -1; abilityMs = GetAbilityManagerService(); if (abilityMs == nullptr) { result = OHOS::ERR_INVALID_VALUE; HILOG_ERROR("failed to get ability manager service"); return result; } StackInfo stackInfo; abilityMs->GetAllStackInfo(stackInfo); MissionStackInfo defaultMissionStack; for (const auto &stackInfo : stackInfo.missionStackInfos) { if (stackInfo.id == 1) { // DEFAULT_MISSION_STACK_ID = 1 defaultMissionStack = stackInfo; break; } } if (!defaultMissionStack.missionRecords.empty() && !defaultMissionStack.missionRecords.begin()->abilityRecordInfos.empty()) { id = defaultMissionStack.missionRecords.begin()->abilityRecordInfos.begin()->id; } return result; } ErrCode STAbilityUtil::GetRunningProcessInfo( std::vector<RunningProcessInfo> &runningProcessInfo, sptr<IAppMgr> &appMs, const time_t &delay) { ErrCode result = ERR_OK; appMs = GetAppMgrService(); if (appMs == nullptr) { result = OHOS::ERR_INVALID_VALUE; HILOG_ERROR("failed to get app manager service"); return result; } std::this_thread::sleep_for(std::chrono::milliseconds(delay)); result = appMs->GetAllRunningProcesses(runningProcessInfo); if (result == ERR_OK) { HILOG_INFO("get running process info successfully."); } else { HILOG_INFO("failed to get running process info."); } return result; } ErrCode STAbilityUtil::KillApplication(const std::string &appName, sptr<IAppMgr> &appMs, const time_t &delay) { ErrCode result = ERR_OK; appMs = GetAppMgrService(); if (appMs == nullptr) { result = OHOS::ERR_INVALID_VALUE; HILOG_ERROR("failed to get app manager service"); return result; } result = appMs->GetAmsMgr()->KillApplication(appName); std::this_thread::sleep_for(std::chrono::milliseconds(delay)); if (result == ERR_OK) { HILOG_INFO("kill application:%{public}s successfully.", appName.c_str()); } else { HILOG_INFO("failed to kill application:%{public}s.", appName.c_str()); } return result; } RunningProcessInfo STAbilityUtil::GetAppProcessInfoByName( const std::string &processName, sptr<IAppMgr> &appMs, const time_t &delay) { RunningProcessInfo appProcessInfo; appProcessInfo.pid_ = 0; std::vector<RunningProcessInfo> runningProcessInfo; if (ERR_OK == GetRunningProcessInfo(runningProcessInfo, appMs, delay)) { for (const auto &info : runningProcessInfo) { if (processName == info.processName_) { appProcessInfo = info; } } } return appProcessInfo; } int STAbilityUtil::WaitCompleted(Event &event, const std::string &eventName, const int code, const int timeout) { HILOG_INFO("WaitCompleted"); return event.WaitingMessage(std::to_string(code) + eventName, timeout, false); } void STAbilityUtil::Completed(Event &event, const std::string &eventName, const int code) { HILOG_INFO("Completed"); return event.CompleteMessage(std::to_string(code) + eventName); } void STAbilityUtil::Completed(Event &event, const std::string &eventName, const int code, const std::string &data) { HILOG_INFO("STAbilityUtil::Completed"); return event.CompleteMessage(std::to_string(code) + eventName, data); } std::string STAbilityUtil::GetData(Event &event, const std::string &eventName, const int code) { HILOG_INFO("STAbilityUtil::GetData"); return event.GetData(std::to_string(code) + eventName); } void STAbilityUtil::CleanMsg(Event &event) { HILOG_INFO("CleanMsg"); return event.Clean(); } std::vector<std::string> STAbilityUtil::SerializationStOperatorToVector(StOperator &ParentOperator) { std::vector<std::string> vectorOperator; PushOperatorInVector(vectorOperator, ParentOperator); return vectorOperator; } void STAbilityUtil::DeserializationStOperatorFromVector( StOperator &ParentOperator, std::vector<std::string> &vectorOperator) { PullOperatorFromVector(ParentOperator, vectorOperator); } void STAbilityUtil::PushOperatorInVector(std::vector<std::string> &vectorOperator, StOperator &ParentOperator) { vectorOperator.emplace_back(std::to_string(ParentOperator.GetChildOperator().size())); vectorOperator.emplace_back(ParentOperator.GetAbilityType()); vectorOperator.emplace_back(ParentOperator.GetBundleName()); vectorOperator.emplace_back(ParentOperator.GetAbilityName()); vectorOperator.emplace_back(ParentOperator.GetOperatorName()); vectorOperator.emplace_back(ParentOperator.GetMessage()); for (auto child : ParentOperator.GetChildOperator()) { PushOperatorInVector(vectorOperator, *child); } } void STAbilityUtil::PullOperatorFromVector(StOperator &ParentOperator, std::vector<std::string> &vectorOperator) { int childnum = std::stoi(vectorOperator.front()); vectorOperator.erase(vectorOperator.begin()); std::string abilityType = vectorOperator.front(); vectorOperator.erase(vectorOperator.begin()); std::string bundleName = vectorOperator.front(); vectorOperator.erase(vectorOperator.begin()); std::string abilityName = vectorOperator.front(); vectorOperator.erase(vectorOperator.begin()); std::string operatorName = vectorOperator.front(); vectorOperator.erase(vectorOperator.begin()); std::string message = vectorOperator.front(); vectorOperator.erase(vectorOperator.begin()); ParentOperator.SetAbilityType(abilityType) .SetBundleName(bundleName) .SetAbilityName(abilityName) .SetOperatorName(operatorName) .SetMessage(message); for (int i = 0; i < childnum; i++) { auto child = std::make_shared<StOperator>(); if (child == nullptr) { return; } ParentOperator.AddChildOperator(child); PullOperatorFromVector(*(child.get()), vectorOperator); } } int STAbilityUtil::RemoveStack( int id, sptr<AAFwk::IAbilityManager> &abilityMs, const time_t &backHmoeDelay, const time_t &removeDelay) { Want wantEntity; wantEntity.AddEntity(Want::FLAG_HOME_INTENT_FROM_SYSTEM); StartAbility(wantEntity, abilityMs); std::this_thread::sleep_for(std::chrono::milliseconds(backHmoeDelay)); if (!abilityMs) { HILOG_INFO("RemoveStack abilityMs nullptr"); return OHOS::ERR_INVALID_VALUE; } int result = abilityMs->RemoveStack(id); std::this_thread::sleep_for(std::chrono::milliseconds(removeDelay)); return result; } class InstallToolStatusReceiver : public StatusReceiverHost { public: InstallToolStatusReceiver(); virtual ~InstallToolStatusReceiver() override; virtual void OnStatusNotify(const int progress) override; virtual void OnFinished(const int32_t resultCode, const std::string &resultMsg) override; static int TestWaitCompleted(Event &event, const std::string eventName, const int code, const int timeout = 10); static void TestCompleted(Event &event, const std::string &eventName, const int code); Event event_ = STtools::Event(); private: int iProgress_ = 0; DISALLOW_COPY_AND_MOVE(InstallToolStatusReceiver); }; InstallToolStatusReceiver::InstallToolStatusReceiver() { std::cout << "create status receiver instance" << std::endl; } InstallToolStatusReceiver::~InstallToolStatusReceiver() { std::cout << "destroy status receiver instance" << std::endl; } void InstallToolStatusReceiver::OnStatusNotify(const int progress) { iProgress_ = progress; std::cout << "destroy status receiver instance" << progress << std::endl; } void InstallToolStatusReceiver::OnFinished(const int32_t resultCode, const std::string &resultMsg) { std::cout << "on finished result is " << resultCode << " " << resultMsg << std::endl; TestCompleted(event_, resultMsg, resultCode); } int InstallToolStatusReceiver::TestWaitCompleted( Event &event, const std::string eventName, const int code, const int timeout) { std::cout << "TestWaitCompleted " << eventName << std::endl; return STAbilityUtil::WaitCompleted(event, eventName, code, timeout); } void InstallToolStatusReceiver::TestCompleted(Event &event, const std::string &eventName, const int code) { std::cout << "TestCompleted " << eventName << std::endl; STAbilityUtil::Completed(event, eventName, code); return; } const std::string MSG_SUCCESS = "[SUCCESS]"; void STAbilityUtil::Install(const std::string &bundleFilePath, const InstallFlag installFlag) { std::string bundlePath = "/system/vendor/" + bundleFilePath + ".hap"; std::string installMsg = ""; sptr<IBundleInstaller> installerProxy = GetInstallerProxy(); if (!installerProxy) { std::cout << "get bundle installer Failure." << std::endl; installMsg = "Failure"; return; } InstallParam installParam; installParam.installFlag = installFlag; sptr<InstallToolStatusReceiver> statusReceiver(new (std::nothrow) InstallToolStatusReceiver()); if (statusReceiver == nullptr) { std::cout << "get statusReceiver Failure." << std::endl; return; } bool installResult = installerProxy->Install(bundlePath, installParam, statusReceiver); if (!installResult) { installMsg = "Failure"; return; } if (InstallToolStatusReceiver::TestWaitCompleted(statusReceiver->event_, MSG_SUCCESS, 0) == 0) { installMsg = "Success"; } else { installMsg = "Failure"; } } void STAbilityUtil::Uninstall(const std::string &bundleName) { std::string uninstallMsg = ""; sptr<IBundleInstaller> installerProxy = GetInstallerProxy(); if (!installerProxy) { std::cout << "get bundle installer Failure." << std::endl; uninstallMsg = "Failure"; return; } if (bundleName.empty()) { std::cout << "bundelname is null." << std::endl; uninstallMsg = "Failure"; } else { sptr<InstallToolStatusReceiver> statusReceiver(new (std::nothrow) InstallToolStatusReceiver()); if (statusReceiver == nullptr) { std::cout << "get statusReceiver Failure." << std::endl; uninstallMsg = "Failure"; return; } InstallParam installParam; bool uninstallResult = installerProxy->Uninstall(bundleName, installParam, statusReceiver); if (!uninstallResult) { std::cout << "Uninstall Failure." << std::endl; uninstallMsg = "Failure"; return; } if (InstallToolStatusReceiver::TestWaitCompleted(statusReceiver->event_, MSG_SUCCESS, 0) == 0) { uninstallMsg = "Success"; } else { uninstallMsg = "Failure"; } } } sptr<IBundleInstaller> STAbilityUtil::GetInstallerProxy() { sptr<IBundleMgr> bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { std::cout << "bundle mgr proxy is nullptr." << std::endl; return nullptr; } sptr<IBundleInstaller> installerProxy = bundleMgrProxy->GetBundleInstaller(); if (!installerProxy) { std::cout << "fail to get bundle installer proxy" << std::endl; return nullptr; } std::cout << "get bundle installer proxy success." << std::endl; return installerProxy; } sptr<IBundleMgr> STAbilityUtil::GetBundleMgrProxy() { sptr<ISystemAbilityManager> systemAbilityManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); if (!systemAbilityManager) { std::cout << "fail to get system ability mgr." << std::endl; return nullptr; } sptr<IRemoteObject> remoteObject = systemAbilityManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); if (!remoteObject) { std::cout << "fail to get bundle manager proxy." << std::endl; return nullptr; } std::cout << "get bundle manager proxy success." << std::endl; return iface_cast<IBundleMgr>(remoteObject); } } // namespace STABUtil } // namespace OHOS
#include <iostream> using namespace std; int main() { int time; cin >> time; int h, m, s; s = time % 60; m = (time / 60) % 60; h = time / 60 / 60; cout << h << ":" << m << ":" << s << endl; return 0; }
//-----------------------------------------------------------------------------------------------// // xbw32 for Windows (generate of numeric combinations for bingo or lotery) // // Created by wilsonsouza 2013, 2014, 2015, 2016, 2017, 2018 // // WR Devinfo // (c) 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2016, 2017, 2018 //-----------------------------------------------------------------------------------------------// #include <bb.table_interface.hpp> #include <bb.mdichildwindow.hpp> #include <sql.table.hpp> #include <sql.query.hpp> namespace bb { table_resources::table_resources(mdichildwindow * frame) : table_interface{ frame } { m_table_id = TABLE_ID::RESOURCES; } //-----------------------------------------------------------------------------------------------// table_interface & table_resources::write(std::unicodestring const & group, int const & page) { return *this; } //-----------------------------------------------------------------------------------------------// table_interface & table_resources::read(std::unicodestring const & group, int const & page) { return *this; } //-----------------------------------------------------------------------------------------------// table_interface & table_resources::erase(std::unicodestring const & group, int const & page, int const & number) { return *this; } //-----------------------------------------------------------------------------------------------// table_interface & table_resources::lookup(std::unicodestring const & group, int const & page, int const & number) { return *this; } //-----------------------------------------------------------------------------------------------// table_interface & table_resources::update(std::unicodestring const & group, int const & page, int const & number) { return *this; } //-----------------------------------------------------------------------------------------------// std::unicodestring table_resources::prepare_query(table_interface::MODE const & mode, std::unicodestring const & group, int const & page, int const & number) { return std::unicodestring{}; } }