text
stringlengths
54
60.6k
<commit_before>#define GLX_GLXEXT_PROTOTYPES /* * Copyright (C) 2013-2014 Nick Guletskii * * 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 "GLXOSD.hpp" #include "glinject.hpp" #include "Utils.hpp" #include "OSDInstance.hpp" #include "ConfigurationManager.hpp" #include <dlfcn.h> #include <fstream> #include <iostream> #include <limits> #include <sstream> #include <sys/types.h> #include <sys/stat.h> #include <sys/unistd.h> namespace glxosd { GLXOSD* GLXOSD::glxosdInstance = nullptr; bool frameLoggingEnabled = false; bool frameLogDumpInProgress = false; bool osdVisible = true; bool toggleVsync = false; KeyCombo frameLoggingToggleKey; KeyCombo osdToggleKey; KeyCombo vsyncToggleKey; int frameLogId = 0; uint64_t frameLogMonotonicTimeOffset = std::numeric_limits<uint64_t>::max(); std::string frameLogFilename = ""; std::string frameLogDirectory = ""; uint64_t frameLoggingDuration = 0; std::ofstream frameLogStream; std::vector<std::pair<GLXDrawable, uint64_t> > frameLog; bool keepFrameLogInMemory = false; bool frameLogToggledThisFrame = false; bool osdToggledThisFrame = false; bool vsyncToggledThisFrame = false; /* * RAII is much better than try/finally, especially in this case! /s */ class GlinjectGLLockRAIIHelper { public: GlinjectGLLockRAIIHelper() { glinject_lock_gl(); } ~GlinjectGLLockRAIIHelper() { glinject_unlock_gl(); } }; GLXOSD* GLXOSD::instance() { if (glxosdInstance == nullptr) { glxosdInstance = new GLXOSD(); } return glxosdInstance; } GLXOSD::GLXOSD() { configurationManager = new ConfigurationManager(); frameLoggingToggleKey = stringToKeyCombo( getConfigurationManager().getProperty<std::string>( "frame_logging_toggle_keycombo")); frameLoggingDuration = getConfigurationManager().getProperty<uint64_t>( "frame_logging_duration_ms"); osdToggleKey = stringToKeyCombo( getConfigurationManager().getProperty<std::string>( "osd_toggle_keycombo")); vsyncToggleKey = stringToKeyCombo( getConfigurationManager().getProperty<std::string>( "vsync_toggle_keycombo")); frameLogDirectory = getConfigurationManager().getProperty<std::string>( "frame_log_directory_string"); keepFrameLogInMemory = getConfigurationManager().getProperty<bool>( "frame_log_keep_in_memory_bool"); drawableHandlers = new std::map<GLXContext, glxosd::OSDInstance*>; pluginConstructors = new std::vector<PluginConstructor>(); pluginDataProviders = new std::vector<PluginDataProvider>(); pluginDestructors = new std::vector<PluginDestructor>(); pluginSharedObjectHandles = new std::vector<void*>(); loadAllPlugins(); std::for_each(pluginConstructors->begin(), pluginConstructors->end(), [this](PluginConstructor pluginConstructor) {pluginConstructor(this);}); } void GLXOSD::osdHandleBufferSwap(Display* display, GLXDrawable drawable) { osdToggledThisFrame = false; frameLogToggledThisFrame = false; unsigned int width = 1; unsigned int height = 1; if (toggleVsync) { unsigned int swapInterval; glXQueryDrawable(display, drawable, GLX_SWAP_INTERVAL_EXT, &swapInterval); swapInterval = (swapInterval > 0) ? 0 : 1; glXSwapIntervalEXT(display, drawable, swapInterval); toggleVsync = false; } if (osdVisible && display && drawable) { auto it = drawableHandlers->find(glXGetCurrentContext()); OSDInstance* instance; if (it == drawableHandlers->end()) { instance = new OSDInstance(); drawableHandlers->insert( std::pair<GLXContext, glxosd::OSDInstance*>( glXGetCurrentContext(), instance)); } else { instance = (*it).second; } GlinjectGLLockRAIIHelper raiiHelper; GLint viewport[4]; rgl(GetIntegerv)(GL_VIEWPORT, viewport); width = viewport[2]; height = viewport[3]; if (width < 1 || height < 1) { return; } instance->render(width, height); } if (isFrameLoggingEnabled()) { frameLogTick(drawable); } } void GLXOSD::frameLogTick(GLXDrawable drawable) { if (frameLoggingDuration > 0 && frameLogMonotonicTimeOffset + frameLoggingDuration * 1000000 < getMonotonicTimeNanoseconds()) { stopFrameLogging(); return; } Lock lock(&frameLogMutex); if(keepFrameLogInMemory) { frameLog.push_back( std::pair<GLXDrawable, uint64_t>( drawable, (getMonotonicTimeNanoseconds() - frameLogMonotonicTimeOffset) ) ); } else { frameLogStream << drawable << "," << (getMonotonicTimeNanoseconds() - frameLogMonotonicTimeOffset) << std::endl; } } void GLXOSD::osdHandleContextDestruction(Display* display, GLXContext context) { auto it = drawableHandlers->find(context); if (it != drawableHandlers->end()) { delete (*it).second; drawableHandlers->erase(it); } } void createDirectory(std::string path) { for (size_t i = 1; i < path.length(); i++) { if (path[i] == '/') { int status = mkdir(path.substr(0, i).c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); if (status == 0) continue; int errsv = errno; switch (errsv) { case EACCES: throw std::runtime_error( "Couldn't create directory " + path + ": access denied."); case EEXIST: goto next; case ELOOP: throw std::runtime_error( "Couldn't create directory " + path + ": loop in the tree."); case EMLINK: throw std::runtime_error( "Couldn't create directory " + path + ": the link count of the parent directory would exceed {LINK_MAX}."); case ENAMETOOLONG: throw std::runtime_error( "Couldn't create directory " + path + ": the length of the path argument exceeds {PATH_MAX} or a pathname component is longer than {NAME_MAX}."); case ENOSPC: throw std::runtime_error( "Couldn't create directory " + path + ": the file system does not contain enough space to hold the contents of the new directory or to extend the parent directory of the new directory."); case ENOTDIR: throw std::runtime_error( "Couldn't create directory " + path + ": a component of the path is not a directory."); case EROFS: throw std::runtime_error( "Couldn't create directory " + path + ": read only filesystem."); } } next: ; } } void GLXOSD::startFrameLogging() { Lock lock(&frameLogMutex); frameLoggingEnabled = true; createDirectory(frameLogDirectory); std::stringstream nameStream; nameStream << frameLogDirectory << "/glxosd_" << getpid() << "_" << std::time(0) << "_" << frameLogId++ << ".log"; frameLogFilename = nameStream.str(); if(!keepFrameLogInMemory) { frameLogStream.open(frameLogFilename, std::ofstream::out); } frameLogMonotonicTimeOffset = getMonotonicTimeNanoseconds(); } void GLXOSD::stopFrameLogging() { Lock lock(&frameLogMutex); frameLoggingEnabled = false; if(keepFrameLogInMemory) { frameLogDumpInProgress = true; frameLogStream.open(frameLogFilename, std::ofstream::out); for(auto frameLogEntry : frameLog){ frameLogStream << frameLogEntry.first << "," << frameLogEntry.second << "\n"; } frameLogStream.flush(); frameLogDumpInProgress = false; frameLog.clear(); } frameLogStream.close(); frameLogStream.clear(); } void GLXOSD::osdHandleKeyPress(XKeyEvent* event) { if (!frameLogToggledThisFrame && keyComboMatches(frameLoggingToggleKey, event)) { frameLogToggledThisFrame = true; if (frameLoggingEnabled) stopFrameLogging(); else startFrameLogging(); } if (!osdToggledThisFrame && keyComboMatches(osdToggleKey, event)) { osdToggledThisFrame = true; osdVisible = !osdVisible; } if (!vsyncToggledThisFrame && keyComboMatches(vsyncToggleKey, event)) { vsyncToggledThisFrame = false; toggleVsync = true; } } Bool GLXOSD::osdEventFilter(Display* display, XEvent* event, XPointer pointer) { if (event->type != KeyPress) return false; XKeyEvent * keyEvent = &event->xkey; return keyComboMatches(osdToggleKey, keyEvent) || keyComboMatches(frameLoggingToggleKey, keyEvent); } bool GLXOSD::isFrameLoggingEnabled() { return frameLoggingEnabled; } bool GLXOSD::isFrameLoggingDumpInProgress() { return frameLogDumpInProgress; } ConfigurationManager & GLXOSD::getConfigurationManager() { return *configurationManager; } void GLXOSD::cleanup() { if (glxosdInstance == nullptr) { return; } delete glxosdInstance; } GLXOSD::~GLXOSD() { for_each(pluginDestructors->begin(), pluginDestructors->end(), [this](PluginDestructor destructor) { destructor(this); }); delete configurationManager; for_each(pluginSharedObjectHandles->begin(), pluginSharedObjectHandles->end(), [](void* handle) { dlclose(handle); }); delete pluginSharedObjectHandles; delete pluginDataProviders; delete drawableHandlers; glxosdInstance = nullptr; } /* * Plugin function getters */ std::vector<PluginDataProvider> *GLXOSD::getPluginDataProviders() { return pluginDataProviders; } /* * Plugin management */ void GLXOSD::loadPlugin(std::string name) { std::cout << "[GLXOSD] Loading " << name << std::endl; void *handle = dlopen(name.c_str(), RTLD_LAZY); if (!handle) { throw std::runtime_error( "[GLXOSD] Could not load plugin: " + std::string(dlerror())); } pluginSharedObjectHandles->push_back(handle); pluginConstructors->push_back( PluginConstructor(handle, "glxosdPluginConstructor")); pluginDataProviders->push_back( PluginDataProvider(handle, "glxosdPluginDataProvider")); pluginDestructors->push_back( PluginDestructor(handle, "glxosdPluginDestructor")); std::cout << "[GLXOSD] Loaded " << name << std::endl; } void GLXOSD::loadAllPlugins() { std::istringstream ss(getEnvironment("GLXOSD_PLUGINS")); std::string token; while (std::getline(ss, token, ':')) { if (token.empty()) { continue; } loadPlugin(token); } } /* * Wrappers */ void osdHandleBufferSwap(Display* display, GLXDrawable drawable) { GLXOSD::instance()->osdHandleBufferSwap(display, drawable); } void osdHandleContextDestruction(Display* display, GLXContext context) { GLXOSD::instance()->osdHandleContextDestruction(display, context); } void osdHandleKeyPress(XKeyEvent* event) { GLXOSD::instance()->osdHandleKeyPress(event); } Bool osdEventFilter(Display* display, XEvent* event, XPointer pointer) { return GLXOSD::instance()->osdEventFilter(display, event, pointer); } } <commit_msg>Use the GLX drawable dimensions instead of GL_VIEWPORT<commit_after>#define GLX_GLXEXT_PROTOTYPES /* * Copyright (C) 2013-2014 Nick Guletskii * * 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 "GLXOSD.hpp" #include "glinject.hpp" #include "Utils.hpp" #include "OSDInstance.hpp" #include "ConfigurationManager.hpp" #include <dlfcn.h> #include <fstream> #include <iostream> #include <limits> #include <sstream> #include <sys/types.h> #include <sys/stat.h> #include <sys/unistd.h> namespace glxosd { GLXOSD* GLXOSD::glxosdInstance = nullptr; bool frameLoggingEnabled = false; bool frameLogDumpInProgress = false; bool osdVisible = true; bool toggleVsync = false; KeyCombo frameLoggingToggleKey; KeyCombo osdToggleKey; KeyCombo vsyncToggleKey; int frameLogId = 0; uint64_t frameLogMonotonicTimeOffset = std::numeric_limits<uint64_t>::max(); std::string frameLogFilename = ""; std::string frameLogDirectory = ""; uint64_t frameLoggingDuration = 0; std::ofstream frameLogStream; std::vector<std::pair<GLXDrawable, uint64_t> > frameLog; bool keepFrameLogInMemory = false; bool frameLogToggledThisFrame = false; bool osdToggledThisFrame = false; bool vsyncToggledThisFrame = false; /* * RAII is much better than try/finally, especially in this case! /s */ class GlinjectGLLockRAIIHelper { public: GlinjectGLLockRAIIHelper() { glinject_lock_gl(); } ~GlinjectGLLockRAIIHelper() { glinject_unlock_gl(); } }; GLXOSD* GLXOSD::instance() { if (glxosdInstance == nullptr) { glxosdInstance = new GLXOSD(); } return glxosdInstance; } GLXOSD::GLXOSD() { configurationManager = new ConfigurationManager(); frameLoggingToggleKey = stringToKeyCombo( getConfigurationManager().getProperty<std::string>( "frame_logging_toggle_keycombo")); frameLoggingDuration = getConfigurationManager().getProperty<uint64_t>( "frame_logging_duration_ms"); osdToggleKey = stringToKeyCombo( getConfigurationManager().getProperty<std::string>( "osd_toggle_keycombo")); vsyncToggleKey = stringToKeyCombo( getConfigurationManager().getProperty<std::string>( "vsync_toggle_keycombo")); frameLogDirectory = getConfigurationManager().getProperty<std::string>( "frame_log_directory_string"); keepFrameLogInMemory = getConfigurationManager().getProperty<bool>( "frame_log_keep_in_memory_bool"); drawableHandlers = new std::map<GLXContext, glxosd::OSDInstance*>; pluginConstructors = new std::vector<PluginConstructor>(); pluginDataProviders = new std::vector<PluginDataProvider>(); pluginDestructors = new std::vector<PluginDestructor>(); pluginSharedObjectHandles = new std::vector<void*>(); loadAllPlugins(); std::for_each(pluginConstructors->begin(), pluginConstructors->end(), [this](PluginConstructor pluginConstructor) {pluginConstructor(this);}); } void GLXOSD::osdHandleBufferSwap(Display* display, GLXDrawable drawable) { osdToggledThisFrame = false; frameLogToggledThisFrame = false; if (toggleVsync) { unsigned int swapInterval; glXQueryDrawable(display, drawable, GLX_SWAP_INTERVAL_EXT, &swapInterval); swapInterval = (swapInterval > 0) ? 0 : 1; glXSwapIntervalEXT(display, drawable, swapInterval); toggleVsync = false; } if (osdVisible && display && drawable) { auto it = drawableHandlers->find(glXGetCurrentContext()); OSDInstance* instance; if (it == drawableHandlers->end()) { instance = new OSDInstance(); drawableHandlers->insert( std::pair<GLXContext, glxosd::OSDInstance*>( glXGetCurrentContext(), instance)); } else { instance = (*it).second; } GlinjectGLLockRAIIHelper raiiHelper; unsigned int windowWidth = 0, windowHeight = 0; glXQueryDrawable(display, drawable, GLX_WIDTH, &windowWidth); glXQueryDrawable(display, drawable, GLX_HEIGHT, &windowHeight); GLint viewport[4]; rgl(GetIntegerv)(GL_VIEWPORT, viewport); rgl(Viewport)(0, 0, windowWidth, windowHeight); if (windowWidth < 1 || windowHeight < 1) { return; } instance->render(windowWidth, windowHeight); rgl(Viewport)(viewport[0], viewport[1], viewport[2], viewport[3]); } if (isFrameLoggingEnabled()) { frameLogTick(drawable); } } void GLXOSD::frameLogTick(GLXDrawable drawable) { if (frameLoggingDuration > 0 && frameLogMonotonicTimeOffset + frameLoggingDuration * 1000000 < getMonotonicTimeNanoseconds()) { stopFrameLogging(); return; } Lock lock(&frameLogMutex); if(keepFrameLogInMemory) { frameLog.push_back( std::pair<GLXDrawable, uint64_t>( drawable, (getMonotonicTimeNanoseconds() - frameLogMonotonicTimeOffset) ) ); } else { frameLogStream << drawable << "," << (getMonotonicTimeNanoseconds() - frameLogMonotonicTimeOffset) << std::endl; } } void GLXOSD::osdHandleContextDestruction(Display* display, GLXContext context) { auto it = drawableHandlers->find(context); if (it != drawableHandlers->end()) { delete (*it).second; drawableHandlers->erase(it); } } void createDirectory(std::string path) { for (size_t i = 1; i < path.length(); i++) { if (path[i] == '/') { int status = mkdir(path.substr(0, i).c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); if (status == 0) continue; int errsv = errno; switch (errsv) { case EACCES: throw std::runtime_error( "Couldn't create directory " + path + ": access denied."); case EEXIST: goto next; case ELOOP: throw std::runtime_error( "Couldn't create directory " + path + ": loop in the tree."); case EMLINK: throw std::runtime_error( "Couldn't create directory " + path + ": the link count of the parent directory would exceed {LINK_MAX}."); case ENAMETOOLONG: throw std::runtime_error( "Couldn't create directory " + path + ": the length of the path argument exceeds {PATH_MAX} or a pathname component is longer than {NAME_MAX}."); case ENOSPC: throw std::runtime_error( "Couldn't create directory " + path + ": the file system does not contain enough space to hold the contents of the new directory or to extend the parent directory of the new directory."); case ENOTDIR: throw std::runtime_error( "Couldn't create directory " + path + ": a component of the path is not a directory."); case EROFS: throw std::runtime_error( "Couldn't create directory " + path + ": read only filesystem."); } } next: ; } } void GLXOSD::startFrameLogging() { Lock lock(&frameLogMutex); frameLoggingEnabled = true; createDirectory(frameLogDirectory); std::stringstream nameStream; nameStream << frameLogDirectory << "/glxosd_" << getpid() << "_" << std::time(0) << "_" << frameLogId++ << ".log"; frameLogFilename = nameStream.str(); if(!keepFrameLogInMemory) { frameLogStream.open(frameLogFilename, std::ofstream::out); } frameLogMonotonicTimeOffset = getMonotonicTimeNanoseconds(); } void GLXOSD::stopFrameLogging() { Lock lock(&frameLogMutex); frameLoggingEnabled = false; if(keepFrameLogInMemory) { frameLogDumpInProgress = true; frameLogStream.open(frameLogFilename, std::ofstream::out); for(auto frameLogEntry : frameLog){ frameLogStream << frameLogEntry.first << "," << frameLogEntry.second << "\n"; } frameLogStream.flush(); frameLogDumpInProgress = false; frameLog.clear(); } frameLogStream.close(); frameLogStream.clear(); } void GLXOSD::osdHandleKeyPress(XKeyEvent* event) { if (!frameLogToggledThisFrame && keyComboMatches(frameLoggingToggleKey, event)) { frameLogToggledThisFrame = true; if (frameLoggingEnabled) stopFrameLogging(); else startFrameLogging(); } if (!osdToggledThisFrame && keyComboMatches(osdToggleKey, event)) { osdToggledThisFrame = true; osdVisible = !osdVisible; } if (!vsyncToggledThisFrame && keyComboMatches(vsyncToggleKey, event)) { vsyncToggledThisFrame = false; toggleVsync = true; } } Bool GLXOSD::osdEventFilter(Display* display, XEvent* event, XPointer pointer) { if (event->type != KeyPress) return false; XKeyEvent * keyEvent = &event->xkey; return keyComboMatches(osdToggleKey, keyEvent) || keyComboMatches(frameLoggingToggleKey, keyEvent); } bool GLXOSD::isFrameLoggingEnabled() { return frameLoggingEnabled; } bool GLXOSD::isFrameLoggingDumpInProgress() { return frameLogDumpInProgress; } ConfigurationManager & GLXOSD::getConfigurationManager() { return *configurationManager; } void GLXOSD::cleanup() { if (glxosdInstance == nullptr) { return; } delete glxosdInstance; } GLXOSD::~GLXOSD() { for_each(pluginDestructors->begin(), pluginDestructors->end(), [this](PluginDestructor destructor) { destructor(this); }); delete configurationManager; for_each(pluginSharedObjectHandles->begin(), pluginSharedObjectHandles->end(), [](void* handle) { dlclose(handle); }); delete pluginSharedObjectHandles; delete pluginDataProviders; delete drawableHandlers; glxosdInstance = nullptr; } /* * Plugin function getters */ std::vector<PluginDataProvider> *GLXOSD::getPluginDataProviders() { return pluginDataProviders; } /* * Plugin management */ void GLXOSD::loadPlugin(std::string name) { std::cout << "[GLXOSD] Loading " << name << std::endl; void *handle = dlopen(name.c_str(), RTLD_LAZY); if (!handle) { throw std::runtime_error( "[GLXOSD] Could not load plugin: " + std::string(dlerror())); } pluginSharedObjectHandles->push_back(handle); pluginConstructors->push_back( PluginConstructor(handle, "glxosdPluginConstructor")); pluginDataProviders->push_back( PluginDataProvider(handle, "glxosdPluginDataProvider")); pluginDestructors->push_back( PluginDestructor(handle, "glxosdPluginDestructor")); std::cout << "[GLXOSD] Loaded " << name << std::endl; } void GLXOSD::loadAllPlugins() { std::istringstream ss(getEnvironment("GLXOSD_PLUGINS")); std::string token; while (std::getline(ss, token, ':')) { if (token.empty()) { continue; } loadPlugin(token); } } /* * Wrappers */ void osdHandleBufferSwap(Display* display, GLXDrawable drawable) { GLXOSD::instance()->osdHandleBufferSwap(display, drawable); } void osdHandleContextDestruction(Display* display, GLXContext context) { GLXOSD::instance()->osdHandleContextDestruction(display, context); } void osdHandleKeyPress(XKeyEvent* event) { GLXOSD::instance()->osdHandleKeyPress(event); } Bool osdEventFilter(Display* display, XEvent* event, XPointer pointer) { return GLXOSD::instance()->osdEventFilter(display, event, pointer); } } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// /// @brief upload request handler /// /// @file /// /// DISCLAIMER /// /// Copyright 2014 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 Jan Steemann /// @author Copyright 2014, ArangoDB GmbH, Cologne, Germany /// @author Copyright 2012-2014, triAGENS GmbH, Cologne, Germany //////////////////////////////////////////////////////////////////////////////// #include "RestUploadHandler.h" #include "Basics/FileUtils.h" #include "Basics/files.h" #include "Basics/logging.h" #include "Basics/StringUtils.h" #include "HttpServer/HttpServer.h" #include "Rest/HttpRequest.h" using namespace std; using namespace triagens::basics; using namespace triagens::rest; using namespace triagens::arango; // ----------------------------------------------------------------------------- // --SECTION-- constructors and destructors // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @brief constructor //////////////////////////////////////////////////////////////////////////////// RestUploadHandler::RestUploadHandler (HttpRequest* request) : RestVocbaseBaseHandler(request) { } //////////////////////////////////////////////////////////////////////////////// /// @brief destructor //////////////////////////////////////////////////////////////////////////////// RestUploadHandler::~RestUploadHandler () { } // ----------------------------------------------------------------------------- // --SECTION-- Handler methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// Handler::status_t RestUploadHandler::execute () { // extract the request type const HttpRequest::HttpRequestType type = _request->requestType(); if (type != HttpRequest::HTTP_REQUEST_POST) { generateError(HttpResponse::METHOD_NOT_ALLOWED, TRI_ERROR_HTTP_METHOD_NOT_ALLOWED); return status_t(Handler::HANDLER_DONE); } char* filename = nullptr; if (TRI_GetTempName("uploads", &filename, false) != TRI_ERROR_NO_ERROR) { generateError(HttpResponse::SERVER_ERROR, TRI_ERROR_INTERNAL, "could not generate temp file"); return status_t(Handler::HANDLER_FAILED); } char* relative = TRI_GetFilename(filename); LOG_TRACE("saving uploaded file of length %llu in file '%s', relative '%s'", (unsigned long long) _request->bodySize(), filename, relative); char const* body = _request->body(); size_t bodySize = _request->bodySize(); bool found; char const* value = _request->value("multipart", found); bool multiPart = false; if (found) { multiPart = triagens::basics::StringUtils::boolean(value); if (multiPart) { if (! parseMultiPart(body, bodySize)) { TRI_Free(TRI_CORE_MEM_ZONE, relative); TRI_Free(TRI_CORE_MEM_ZONE, filename); generateError(HttpResponse::SERVER_ERROR, TRI_ERROR_INTERNAL, "invalid multipart request"); return status_t(Handler::HANDLER_FAILED); } } } try { FileUtils::spit(string(filename), body, bodySize); TRI_Free(TRI_CORE_MEM_ZONE, filename); } catch (...) { TRI_Free(TRI_CORE_MEM_ZONE, relative); TRI_Free(TRI_CORE_MEM_ZONE, filename); generateError(HttpResponse::SERVER_ERROR, TRI_ERROR_INTERNAL, "could not save file"); return status_t(Handler::HANDLER_FAILED); } char* fullName = TRI_Concatenate2File("uploads", relative); TRI_Free(TRI_CORE_MEM_ZONE, relative); // create the response _response = createResponse(HttpResponse::CREATED); _response->setContentType("application/json; charset=utf-8"); TRI_json_t json; TRI_InitObjectJson(TRI_UNKNOWN_MEM_ZONE, &json); TRI_Insert3ObjectJson(TRI_UNKNOWN_MEM_ZONE, &json, "filename", TRI_CreateStringCopyJson(TRI_UNKNOWN_MEM_ZONE, fullName, strlen(fullName))); TRI_Free(TRI_CORE_MEM_ZONE, fullName); generateResult(HttpResponse::CREATED, &json); TRI_DestroyJson(TRI_UNKNOWN_MEM_ZONE, &json); // success return status_t(Handler::HANDLER_DONE); } //////////////////////////////////////////////////////////////////////////////// /// @brief parses a multi-part request body and determines the boundaries of /// its first element //////////////////////////////////////////////////////////////////////////////// bool RestUploadHandler::parseMultiPart (char const*& body, size_t& length) { char const* beg = _request->body(); char const* end = beg + _request->bodySize(); while (beg < end && (*beg == '\r' || *beg == '\n' || *beg == ' ')) { ++beg; } // find delimiter char const* ptr = beg; while (ptr < end && *ptr == '-') { ++ptr; } while (ptr < end && *ptr != '\r' && *ptr != '\n') { ++ptr; } if (ptr == beg) { // oops return false; } std::string const delimiter(beg, ptr - beg); if (ptr < end && *ptr == '\r') { ++ptr; } if (ptr < end && *ptr == '\n') { ++ptr; } std::vector<std::pair<char const*, size_t>> parts; while (ptr < end) { char const* p = TRI_IsContainedMemory(ptr, end - ptr, delimiter.c_str(), delimiter.size()); if (p == nullptr || p + delimiter.size() + 2 >= end || p - 2 <= ptr) { return false; } char const* q = p; if (*(q - 1) == '\n') { --q; } if (*(q - 1) == '\r') { --q; } parts.push_back(std::make_pair(ptr, q - ptr)); ptr = p + delimiter.size(); if (*ptr == '-' && *(ptr + 1) == '-') { // eom break; } if (*ptr == '\r') { ++ptr; } if (ptr < end && *ptr == '\n') { ++ptr; } } for (auto& part : parts) { auto ptr = part.first; auto end = part.first + part.second; char const* data = nullptr; while (ptr < end) { while (ptr < end && *ptr == ' ') { ++ptr; } if (ptr < end && (*ptr == '\r' || *ptr == '\n')) { // end of headers if (*ptr == '\r') { ++ptr; } if (ptr < end && *ptr == '\n') { ++ptr; } data = ptr; break; } // header line char const* eol = TRI_IsContainedMemory(ptr, end - ptr, "\r\n", 2); if (eol == nullptr) { eol = TRI_IsContainedMemory(ptr, end - ptr, "\n", 1); } if (eol == nullptr) { return false; } char const* colon = TRI_IsContainedMemory(ptr, end - ptr, ":", 1); if (colon == nullptr) { return false; } char const* p = colon; while (p > ptr && *(p - 1) == ' ') { --p; } ++colon; while (colon < eol && *colon == ' ') { ++colon; } char const* q = eol; while (q > ptr && *(q - 1) == ' ') { --q; } ptr = eol; if (*ptr == '\r') { ++ptr; } if (ptr < end && *ptr == '\n') { ++ptr; } } if (data == nullptr) { return false; } body = data; length = static_cast<size_t>(end - data); // stop after the first found element break; } return true; } // ----------------------------------------------------------------------------- // --SECTION-- END-OF-FILE // ----------------------------------------------------------------------------- // Local Variables: // mode: outline-minor // outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @page\\|// --SECTION--\\|/// @\\}" // End: <commit_msg>reduce var scope<commit_after>//////////////////////////////////////////////////////////////////////////////// /// @brief upload request handler /// /// @file /// /// DISCLAIMER /// /// Copyright 2014 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 Jan Steemann /// @author Copyright 2014, ArangoDB GmbH, Cologne, Germany /// @author Copyright 2012-2014, triAGENS GmbH, Cologne, Germany //////////////////////////////////////////////////////////////////////////////// #include "RestUploadHandler.h" #include "Basics/FileUtils.h" #include "Basics/files.h" #include "Basics/logging.h" #include "Basics/StringUtils.h" #include "HttpServer/HttpServer.h" #include "Rest/HttpRequest.h" using namespace std; using namespace triagens::basics; using namespace triagens::rest; using namespace triagens::arango; // ----------------------------------------------------------------------------- // --SECTION-- constructors and destructors // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @brief constructor //////////////////////////////////////////////////////////////////////////////// RestUploadHandler::RestUploadHandler (HttpRequest* request) : RestVocbaseBaseHandler(request) { } //////////////////////////////////////////////////////////////////////////////// /// @brief destructor //////////////////////////////////////////////////////////////////////////////// RestUploadHandler::~RestUploadHandler () { } // ----------------------------------------------------------------------------- // --SECTION-- Handler methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// Handler::status_t RestUploadHandler::execute () { // extract the request type const HttpRequest::HttpRequestType type = _request->requestType(); if (type != HttpRequest::HTTP_REQUEST_POST) { generateError(HttpResponse::METHOD_NOT_ALLOWED, TRI_ERROR_HTTP_METHOD_NOT_ALLOWED); return status_t(Handler::HANDLER_DONE); } char* filename = nullptr; if (TRI_GetTempName("uploads", &filename, false) != TRI_ERROR_NO_ERROR) { generateError(HttpResponse::SERVER_ERROR, TRI_ERROR_INTERNAL, "could not generate temp file"); return status_t(Handler::HANDLER_FAILED); } char* relative = TRI_GetFilename(filename); LOG_TRACE("saving uploaded file of length %llu in file '%s', relative '%s'", (unsigned long long) _request->bodySize(), filename, relative); char const* body = _request->body(); size_t bodySize = _request->bodySize(); bool found; char const* value = _request->value("multipart", found); if (found) { bool multiPart = triagens::basics::StringUtils::boolean(value); if (multiPart) { if (! parseMultiPart(body, bodySize)) { TRI_Free(TRI_CORE_MEM_ZONE, relative); TRI_Free(TRI_CORE_MEM_ZONE, filename); generateError(HttpResponse::SERVER_ERROR, TRI_ERROR_INTERNAL, "invalid multipart request"); return status_t(Handler::HANDLER_FAILED); } } } try { FileUtils::spit(string(filename), body, bodySize); TRI_Free(TRI_CORE_MEM_ZONE, filename); } catch (...) { TRI_Free(TRI_CORE_MEM_ZONE, relative); TRI_Free(TRI_CORE_MEM_ZONE, filename); generateError(HttpResponse::SERVER_ERROR, TRI_ERROR_INTERNAL, "could not save file"); return status_t(Handler::HANDLER_FAILED); } char* fullName = TRI_Concatenate2File("uploads", relative); TRI_Free(TRI_CORE_MEM_ZONE, relative); // create the response _response = createResponse(HttpResponse::CREATED); _response->setContentType("application/json; charset=utf-8"); TRI_json_t json; TRI_InitObjectJson(TRI_UNKNOWN_MEM_ZONE, &json); TRI_Insert3ObjectJson(TRI_UNKNOWN_MEM_ZONE, &json, "filename", TRI_CreateStringCopyJson(TRI_UNKNOWN_MEM_ZONE, fullName, strlen(fullName))); TRI_Free(TRI_CORE_MEM_ZONE, fullName); generateResult(HttpResponse::CREATED, &json); TRI_DestroyJson(TRI_UNKNOWN_MEM_ZONE, &json); // success return status_t(Handler::HANDLER_DONE); } //////////////////////////////////////////////////////////////////////////////// /// @brief parses a multi-part request body and determines the boundaries of /// its first element //////////////////////////////////////////////////////////////////////////////// bool RestUploadHandler::parseMultiPart (char const*& body, size_t& length) { char const* beg = _request->body(); char const* end = beg + _request->bodySize(); while (beg < end && (*beg == '\r' || *beg == '\n' || *beg == ' ')) { ++beg; } // find delimiter char const* ptr = beg; while (ptr < end && *ptr == '-') { ++ptr; } while (ptr < end && *ptr != '\r' && *ptr != '\n') { ++ptr; } if (ptr == beg) { // oops return false; } std::string const delimiter(beg, ptr - beg); if (ptr < end && *ptr == '\r') { ++ptr; } if (ptr < end && *ptr == '\n') { ++ptr; } std::vector<std::pair<char const*, size_t>> parts; while (ptr < end) { char const* p = TRI_IsContainedMemory(ptr, end - ptr, delimiter.c_str(), delimiter.size()); if (p == nullptr || p + delimiter.size() + 2 >= end || p - 2 <= ptr) { return false; } char const* q = p; if (*(q - 1) == '\n') { --q; } if (*(q - 1) == '\r') { --q; } parts.push_back(std::make_pair(ptr, q - ptr)); ptr = p + delimiter.size(); if (*ptr == '-' && *(ptr + 1) == '-') { // eom break; } if (*ptr == '\r') { ++ptr; } if (ptr < end && *ptr == '\n') { ++ptr; } } for (auto& part : parts) { auto ptr = part.first; auto end = part.first + part.second; char const* data = nullptr; while (ptr < end) { while (ptr < end && *ptr == ' ') { ++ptr; } if (ptr < end && (*ptr == '\r' || *ptr == '\n')) { // end of headers if (*ptr == '\r') { ++ptr; } if (ptr < end && *ptr == '\n') { ++ptr; } data = ptr; break; } // header line char const* eol = TRI_IsContainedMemory(ptr, end - ptr, "\r\n", 2); if (eol == nullptr) { eol = TRI_IsContainedMemory(ptr, end - ptr, "\n", 1); } if (eol == nullptr) { return false; } char const* colon = TRI_IsContainedMemory(ptr, end - ptr, ":", 1); if (colon == nullptr) { return false; } char const* p = colon; while (p > ptr && *(p - 1) == ' ') { --p; } ++colon; while (colon < eol && *colon == ' ') { ++colon; } char const* q = eol; while (q > ptr && *(q - 1) == ' ') { --q; } ptr = eol; if (*ptr == '\r') { ++ptr; } if (ptr < end && *ptr == '\n') { ++ptr; } } if (data == nullptr) { return false; } body = data; length = static_cast<size_t>(end - data); // stop after the first found element break; } return true; } // ----------------------------------------------------------------------------- // --SECTION-- END-OF-FILE // ----------------------------------------------------------------------------- // Local Variables: // mode: outline-minor // outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @page\\|// --SECTION--\\|/// @\\}" // End: <|endoftext|>
<commit_before>/* open source routing machine Copyright (C) Dennis Luxen, 2010 This program is free software; you can redistribute it and/or modify it under the terms of the GNU AFFERO General Public License as published by the Free Software Foundation; either version 3 of the License, or any later version. 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 Affero General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA or see http://www.gnu.org/licenses/agpl.txt. */ #include <climits> #include <fstream> #include <istream> #include <iostream> #include <cstring> #include <string> #include <vector> #ifdef _OPENMP #include <omp.h> #endif #include "typedefs.h" #include <boost/asio.hpp> #include <boost/thread.hpp> #include <boost/bind.hpp> #include "HttpServer/server.h" #include "DataStructures/StaticGraph.h" using namespace std; typedef ContractionCleanup::Edge::EdgeData EdgeData; typedef StaticGraph<EdgeData>::InputEdge GraphEdge; typedef http::server<StaticGraph<EdgeData> > server; /* * TODO: Description of command line arguments */ int main (int argc, char *argv[]) { double time; if(argc < 2) { cerr << "Correct usage:" << endl << argv[0] << " <hsgr data> <nodes data>" << endl; exit(-1); } if (argv[0] == 0) { cerr << "Missing data files!" << endl; return -1; } ifstream in(argv[1], ios::binary); ifstream in2(argv[2], ios::binary); NodeInformationHelpDesk * kdtreeService = new NodeInformationHelpDesk(); time = get_timestamp(); cout << "deserializing edge data from " << argv[1] << " ..." << flush; std::vector< GraphEdge> edgelist; while(!in.eof()) { GraphEdge g; EdgeData e; int distance; bool shortcut; bool forward; bool backward; NodeID middle; NodeID source; NodeID target; in.read((char *)&(distance), sizeof(int)); assert(distance > 0); in.read((char *)&(shortcut), sizeof(bool)); in.read((char *)&(forward), sizeof(bool)); in.read((char *)&(backward), sizeof(bool)); in.read((char *)&(middle), sizeof(NodeID)); in.read((char *)&(source), sizeof(NodeID)); in.read((char *)&(target), sizeof(NodeID)); e.backward = backward; e.distance = distance; e.forward = forward; e.middle = middle; e.shortcut = shortcut; g.data = e; g.source = source; g.target = target; edgelist.push_back(g); } in.close(); cout << "in " << get_timestamp() - time << "s" << endl; cout << "search graph has " << edgelist.size() << " edges" << endl; time = get_timestamp(); cout << "deserializing node map and building kd-tree ..." << flush; kdtreeService->initKDTree(in2); cout << "in " << get_timestamp() - time << "s" << endl; time = get_timestamp(); StaticGraph<EdgeData> * graph = new StaticGraph<EdgeData>(kdtreeService->getNumberOfNodes()-1, edgelist); cout << "checking data sanity ..." << flush; NodeID numberOfNodes = graph->GetNumberOfNodes(); for ( NodeID node = 0; node < numberOfNodes; ++node ) { for ( StaticGraph<EdgeData>::EdgeIterator edge = graph->BeginEdges( node ), endEdges = graph->EndEdges( node ); edge != endEdges; ++edge ) { const NodeID start = node; const NodeID target = graph->GetTarget( edge ); const EdgeData& data = graph->GetEdgeData( edge ); const NodeID middle = data.middle; assert(start != target); if(data.shortcut) { if(graph->FindEdge(start, middle) == SPECIAL_EDGEID && graph->FindEdge(middle, start) == SPECIAL_EDGEID) { assert(false); cerr << "hierarchy broken" << endl; exit(-1); } if(graph->FindEdge(middle, target) == SPECIAL_EDGEID && graph->FindEdge(target, middle) == SPECIAL_EDGEID) { assert(false); cerr << "hierarchy broken" << endl; exit(-1); } } } } cout << "in " << get_timestamp() - time << "s" << endl; cout << "building search graph ..." << flush; SearchEngine<EdgeData, StaticGraph<EdgeData> > * sEngine = new SearchEngine<EdgeData, StaticGraph<EdgeData> >(graph, kdtreeService); cout << "in " << get_timestamp() - time << "s" << endl; time = get_timestamp(); try { // Block all signals for background thread. sigset_t new_mask; sigfillset(&new_mask); sigset_t old_mask; pthread_sigmask(SIG_BLOCK, &new_mask, &old_mask); cout << "starting web server ..." << flush; // Run server in background thread. server s("0.0.0.0", "5000", omp_get_num_procs(), sEngine); boost::thread t(boost::bind(&server::run, &s)); cout << "ok" << endl; // Restore previous signals. pthread_sigmask(SIG_SETMASK, &old_mask, 0); // Wait for signal indicating time to shut down. sigset_t wait_mask; sigemptyset(&wait_mask); sigaddset(&wait_mask, SIGINT); sigaddset(&wait_mask, SIGQUIT); sigaddset(&wait_mask, SIGTERM); pthread_sigmask(SIG_BLOCK, &wait_mask, 0); int sig = 0; sigwait(&wait_mask, &sig); // Stop the server. s.stop(); t.join(); } catch (std::exception& e) { std::cerr << "exception: " << e.what() << "\n"; } cout << "graceful shutdown after " << get_timestamp() - time << "s" << endl; delete kdtreeService; return 0; } <commit_msg>sanity check for nodes in loaded graph<commit_after>/* open source routing machine Copyright (C) Dennis Luxen, 2010 This program is free software; you can redistribute it and/or modify it under the terms of the GNU AFFERO General Public License as published by the Free Software Foundation; either version 3 of the License, or any later version. 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 Affero General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA or see http://www.gnu.org/licenses/agpl.txt. */ #include <climits> #include <fstream> #include <istream> #include <iostream> #include <cstring> #include <string> #include <vector> #ifdef _OPENMP #include <omp.h> #endif #include "typedefs.h" #include <boost/asio.hpp> #include <boost/thread.hpp> #include <boost/bind.hpp> #include "HttpServer/server.h" #include "DataStructures/StaticGraph.h" using namespace std; typedef ContractionCleanup::Edge::EdgeData EdgeData; typedef StaticGraph<EdgeData>::InputEdge GraphEdge; typedef http::server<StaticGraph<EdgeData> > server; /* * TODO: Description of command line arguments */ int main (int argc, char *argv[]) { double time; if(argc < 2) { cerr << "Correct usage:" << endl << argv[0] << " <hsgr data> <nodes data>" << endl; exit(-1); } if (argv[0] == 0) { cerr << "Missing data files!" << endl; return -1; } ifstream in(argv[1], ios::binary); ifstream in2(argv[2], ios::binary); NodeInformationHelpDesk * kdtreeService = new NodeInformationHelpDesk(); time = get_timestamp(); cout << "deserializing edge data from " << argv[1] << " ..." << flush; std::vector< GraphEdge> edgelist; while(!in.eof()) { GraphEdge g; EdgeData e; int distance; bool shortcut; bool forward; bool backward; NodeID middle; NodeID source; NodeID target; in.read((char *)&(distance), sizeof(int)); assert(distance > 0); in.read((char *)&(shortcut), sizeof(bool)); in.read((char *)&(forward), sizeof(bool)); in.read((char *)&(backward), sizeof(bool)); in.read((char *)&(middle), sizeof(NodeID)); in.read((char *)&(source), sizeof(NodeID)); in.read((char *)&(target), sizeof(NodeID)); e.backward = backward; e.distance = distance; e.forward = forward; e.middle = middle; e.shortcut = shortcut; g.data = e; g.source = source; g.target = target; edgelist.push_back(g); } in.close(); cout << "in " << get_timestamp() - time << "s" << endl; cout << "search graph has " << edgelist.size() << " edges" << endl; time = get_timestamp(); cout << "deserializing node map and building kd-tree ..." << flush; kdtreeService->initKDTree(in2); cout << "in " << get_timestamp() - time << "s" << endl; time = get_timestamp(); StaticGraph<EdgeData> * graph = new StaticGraph<EdgeData>(kdtreeService->getNumberOfNodes()-1, edgelist); cout << "checking data sanity ..." << flush; NodeID numberOfNodes = graph->GetNumberOfNodes(); for ( NodeID node = 0; node < numberOfNodes; ++node ) { for ( StaticGraph<EdgeData>::EdgeIterator edge = graph->BeginEdges( node ), endEdges = graph->EndEdges( node ); edge != endEdges; ++edge ) { const NodeID start = node; const NodeID target = graph->GetTarget( edge ); const EdgeData& data = graph->GetEdgeData( edge ); const NodeID middle = data.middle; assert(start != target); if(data.shortcut) { if(graph->FindEdge(start, middle) == SPECIAL_EDGEID && graph->FindEdge(middle, start) == SPECIAL_EDGEID) { assert(false); cerr << "hierarchy broken" << endl; exit(-1); } if(graph->FindEdge(middle, target) == SPECIAL_EDGEID && graph->FindEdge(target, middle) == SPECIAL_EDGEID) { assert(false); cerr << "hierarchy broken" << endl; exit(-1); } } } if(graph->GetOutDegree(node) == 0) { cerr << "found node with degree 0: " << node << endl; } } cout << "in " << get_timestamp() - time << "s" << endl; cout << "building search graph ..." << flush; SearchEngine<EdgeData, StaticGraph<EdgeData> > * sEngine = new SearchEngine<EdgeData, StaticGraph<EdgeData> >(graph, kdtreeService); cout << "in " << get_timestamp() - time << "s" << endl; time = get_timestamp(); try { // Block all signals for background thread. sigset_t new_mask; sigfillset(&new_mask); sigset_t old_mask; pthread_sigmask(SIG_BLOCK, &new_mask, &old_mask); cout << "starting web server ..." << flush; // Run server in background thread. server s("0.0.0.0", "5000", omp_get_num_procs(), sEngine); boost::thread t(boost::bind(&server::run, &s)); cout << "ok" << endl; // Restore previous signals. pthread_sigmask(SIG_SETMASK, &old_mask, 0); // Wait for signal indicating time to shut down. sigset_t wait_mask; sigemptyset(&wait_mask); sigaddset(&wait_mask, SIGINT); sigaddset(&wait_mask, SIGQUIT); sigaddset(&wait_mask, SIGTERM); pthread_sigmask(SIG_BLOCK, &wait_mask, 0); int sig = 0; sigwait(&wait_mask, &sig); // Stop the server. s.stop(); t.join(); } catch (std::exception& e) { std::cerr << "exception: " << e.what() << "\n"; } cout << "graceful shutdown after " << get_timestamp() - time << "s" << endl; delete kdtreeService; return 0; } <|endoftext|>
<commit_before>/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. 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 (C) 2015 Cloudius Systems, Ltd. */ #pragma once #include <unordered_map> #include <unordered_set> #include "core/future.hh" #include "net/api.hh" #include "core/reactor.hh" #include "core/iostream.hh" #include "core/shared_ptr.hh" #include "rpc/rpc_types.hh" namespace rpc { using id_type = int64_t; struct SerializerConcept { // For each serializable type T, implement class T; template <typename Output> friend void write(const SerializerConcept&, Output& output, const T& data); template <typename Input> friend T read(const SerializerConcept&, Input& input, type<T> type_tag); // type_tag used to disambiguate // Input and Output expose void read(char*, size_t) and write(const char*, size_t). }; static constexpr char rpc_magic[] = "SSTARRPC"; struct negotiation_frame { char magic[sizeof(rpc_magic) - 1]; uint32_t required_features_mask; uint32_t optional_features_mask; uint32_t len; // additional negotiation data length } __attribute__((packed)); // MsgType is a type that holds type of a message. The type should be hashable // and serializable. It is preferable to use enum for message types, but // do not forget to provide hash function for it template<typename Serializer, typename MsgType = uint32_t> class protocol { class connection { protected: connected_socket _fd; input_stream<char> _read_buf; output_stream<char> _write_buf; future<> _output_ready = make_ready_future<>(); bool _error = false; protocol& _proto; promise<> _stopped; public: connection(connected_socket&& fd, protocol& proto) : _fd(std::move(fd)), _read_buf(_fd.input()), _write_buf(_fd.output()), _proto(proto) {} connection(protocol& proto) : _proto(proto) {} // functions below are public because they are used by external heavily templated functions // and I am not smart enough to know how to define them as friends auto& in() { return _read_buf; } auto& out() { return _write_buf; } auto& out_ready() { return _output_ready; } bool error() { return _error; } auto& serializer() { return _proto._serializer; } auto& get_protocol() { return _proto; } future<> stop() { _fd.shutdown_input(); _fd.shutdown_output(); return _stopped.get_future(); } }; friend connection; public: class server { public: class connection : public protocol::connection, public enable_lw_shared_from_this<connection> { server& _server; client_info _info; stats _stats; private: future<negotiation_frame> negotiate_protocol(input_stream<char>& in); future<MsgType, int64_t, std::experimental::optional<temporary_buffer<char>>> read_request_frame(input_stream<char>& in); public: connection(server& s, connected_socket&& fd, socket_address&& addr, protocol& proto); future<> process(); future<> respond(int64_t msg_id, sstring&& data); client_info& info() { return _info; } const client_info& info() const { return _info; } stats get_stats() const { return _stats; } stats& get_stats_internal() { return _stats; } ipv4_addr peer_address() const { return ipv4_addr(_info.addr); } }; private: protocol& _proto; server_socket _ss; std::unordered_set<connection*> _conns; bool _stopping = false; promise<> _ss_stopped; public: server(protocol& proto, ipv4_addr addr); server(protocol& proto, server_socket); void accept(); future<> stop() { _stopping = true; // prevents closed connections to be deleted from _conns _ss.abort_accept(); return when_all(_ss_stopped.get_future(), parallel_for_each(_conns, [] (connection* conn) { return conn->stop(); }) ).discard_result(); } template<typename Func> void foreach_connection(Func&& f) { for (auto c : _conns) { f(*c); } } friend connection; }; class client : public protocol::connection { promise<> _connected_promise; bool _connected = false; id_type _message_id = 1; struct reply_handler_base { timer<> t; virtual void operator()(client&, id_type, temporary_buffer<char> data) = 0; virtual void timeout() {} virtual ~reply_handler_base() {}; }; public: template<typename Reply, typename Func> struct reply_handler final : reply_handler_base { Func func; Reply reply; reply_handler(Func&& f) : func(std::move(f)) {} virtual void operator()(client& client, id_type msg_id, temporary_buffer<char> data) override { return func(reply, client, msg_id, std::move(data)); } virtual void timeout() override { reply.done = true; reply.p.set_exception(timeout_error()); } virtual ~reply_handler() {} }; private: std::unordered_map<id_type, std::unique_ptr<reply_handler_base>> _outstanding; stats _stats; ipv4_addr _server_addr; private: future<negotiation_frame> negotiate_protocol(input_stream<char>& in); future<int64_t, std::experimental::optional<temporary_buffer<char>>> read_response_frame(input_stream<char>& in); public: client(protocol& proto, ipv4_addr addr, ipv4_addr local = ipv4_addr()); /** * Create client object using the connected_socket result of the * provided future. * * @param addr the remote address identifying this client * @param f a future<> resulting in a connected_socket for the connection */ client(protocol& proto, ipv4_addr addr, future<connected_socket> f); stats get_stats() const { stats res = _stats; res.wait_reply = _outstanding.size(); return res; } stats& get_stats_internal() { return _stats; } auto next_message_id() { return _message_id++; } void wait_for_reply(id_type id, std::unique_ptr<reply_handler_base>&& h, std::experimental::optional<steady_clock_type::time_point> timeout) { if (timeout) { h->t.set_callback(std::bind(std::mem_fn(&client::wait_timed_out), this, id)); h->t.arm(timeout.value()); } _outstanding.emplace(id, std::move(h)); } void wait_timed_out(id_type id) { struct timeout_handler : reply_handler_base { virtual void operator()(client& client, id_type msg_id, temporary_buffer<char> data) {} }; _stats.timeout++; _outstanding[id]->timeout(); _outstanding[id] = std::make_unique<timeout_handler>(); } future<> stop() { if (_connected && !this->_error) { this->_error = true; return connection::stop(); } else { // connection::stop will fail on shutdown(); since we can't shutdown a // connect(), just wait for it to timeout return this->_stopped.get_future(); } } ipv4_addr peer_address() const { return _server_addr; } }; friend server; private: using rpc_handler = std::function<void (lw_shared_ptr<typename server::connection>, int64_t msgid, temporary_buffer<char> data)>; std::unordered_map<MsgType, rpc_handler> _handlers; Serializer _serializer; std::function<void(const sstring&)> _logger; public: protocol(Serializer&& serializer) : _serializer(std::forward<Serializer>(serializer)) {} template<typename Func> auto make_client(MsgType t); // returns a function which type depends on Func // if Func == Ret(Args...) then return function is // future<Ret>(protocol::client&, Args...) template<typename Func> auto register_handler(MsgType t, Func&& func); void unregister_handler(MsgType t) { _handlers.erase(t); } void set_logger(std::function<void(const sstring&)> logger) { _logger = logger; } void log(const sstring& str) { if (_logger) { _logger(str); _logger("\n"); } } void log(const client_info& info, id_type msg_id, const sstring& str) { log(to_sstring("client ") + inet_ntoa(info.addr.as_posix_sockaddr_in().sin_addr) + " msg_id " + to_sstring(msg_id) + ": " + str); } void log(const client_info& info, const sstring& str) { log(to_sstring("client ") + inet_ntoa(info.addr.as_posix_sockaddr_in().sin_addr) + ": " + str); } void log(ipv4_addr addr, const sstring& str) { log(to_sstring("client ") + inet_ntoa(in_addr{addr.ip}) + ": " + str); } private: void register_receiver(MsgType t, rpc_handler&& handler) { _handlers.emplace(t, std::move(handler)); } }; } #include "rpc_impl.hh" <commit_msg>rpc: fix peer address printing during logging<commit_after>/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. 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 (C) 2015 Cloudius Systems, Ltd. */ #pragma once #include <unordered_map> #include <unordered_set> #include "core/future.hh" #include "net/api.hh" #include "core/reactor.hh" #include "core/iostream.hh" #include "core/shared_ptr.hh" #include "rpc/rpc_types.hh" namespace rpc { using id_type = int64_t; struct SerializerConcept { // For each serializable type T, implement class T; template <typename Output> friend void write(const SerializerConcept&, Output& output, const T& data); template <typename Input> friend T read(const SerializerConcept&, Input& input, type<T> type_tag); // type_tag used to disambiguate // Input and Output expose void read(char*, size_t) and write(const char*, size_t). }; static constexpr char rpc_magic[] = "SSTARRPC"; struct negotiation_frame { char magic[sizeof(rpc_magic) - 1]; uint32_t required_features_mask; uint32_t optional_features_mask; uint32_t len; // additional negotiation data length } __attribute__((packed)); // MsgType is a type that holds type of a message. The type should be hashable // and serializable. It is preferable to use enum for message types, but // do not forget to provide hash function for it template<typename Serializer, typename MsgType = uint32_t> class protocol { class connection { protected: connected_socket _fd; input_stream<char> _read_buf; output_stream<char> _write_buf; future<> _output_ready = make_ready_future<>(); bool _error = false; protocol& _proto; promise<> _stopped; public: connection(connected_socket&& fd, protocol& proto) : _fd(std::move(fd)), _read_buf(_fd.input()), _write_buf(_fd.output()), _proto(proto) {} connection(protocol& proto) : _proto(proto) {} // functions below are public because they are used by external heavily templated functions // and I am not smart enough to know how to define them as friends auto& in() { return _read_buf; } auto& out() { return _write_buf; } auto& out_ready() { return _output_ready; } bool error() { return _error; } auto& serializer() { return _proto._serializer; } auto& get_protocol() { return _proto; } future<> stop() { _fd.shutdown_input(); _fd.shutdown_output(); return _stopped.get_future(); } }; friend connection; public: class server { public: class connection : public protocol::connection, public enable_lw_shared_from_this<connection> { server& _server; client_info _info; stats _stats; private: future<negotiation_frame> negotiate_protocol(input_stream<char>& in); future<MsgType, int64_t, std::experimental::optional<temporary_buffer<char>>> read_request_frame(input_stream<char>& in); public: connection(server& s, connected_socket&& fd, socket_address&& addr, protocol& proto); future<> process(); future<> respond(int64_t msg_id, sstring&& data); client_info& info() { return _info; } const client_info& info() const { return _info; } stats get_stats() const { return _stats; } stats& get_stats_internal() { return _stats; } ipv4_addr peer_address() const { return ipv4_addr(_info.addr); } }; private: protocol& _proto; server_socket _ss; std::unordered_set<connection*> _conns; bool _stopping = false; promise<> _ss_stopped; public: server(protocol& proto, ipv4_addr addr); server(protocol& proto, server_socket); void accept(); future<> stop() { _stopping = true; // prevents closed connections to be deleted from _conns _ss.abort_accept(); return when_all(_ss_stopped.get_future(), parallel_for_each(_conns, [] (connection* conn) { return conn->stop(); }) ).discard_result(); } template<typename Func> void foreach_connection(Func&& f) { for (auto c : _conns) { f(*c); } } friend connection; }; class client : public protocol::connection { promise<> _connected_promise; bool _connected = false; id_type _message_id = 1; struct reply_handler_base { timer<> t; virtual void operator()(client&, id_type, temporary_buffer<char> data) = 0; virtual void timeout() {} virtual ~reply_handler_base() {}; }; public: template<typename Reply, typename Func> struct reply_handler final : reply_handler_base { Func func; Reply reply; reply_handler(Func&& f) : func(std::move(f)) {} virtual void operator()(client& client, id_type msg_id, temporary_buffer<char> data) override { return func(reply, client, msg_id, std::move(data)); } virtual void timeout() override { reply.done = true; reply.p.set_exception(timeout_error()); } virtual ~reply_handler() {} }; private: std::unordered_map<id_type, std::unique_ptr<reply_handler_base>> _outstanding; stats _stats; ipv4_addr _server_addr; private: future<negotiation_frame> negotiate_protocol(input_stream<char>& in); future<int64_t, std::experimental::optional<temporary_buffer<char>>> read_response_frame(input_stream<char>& in); public: client(protocol& proto, ipv4_addr addr, ipv4_addr local = ipv4_addr()); /** * Create client object using the connected_socket result of the * provided future. * * @param addr the remote address identifying this client * @param f a future<> resulting in a connected_socket for the connection */ client(protocol& proto, ipv4_addr addr, future<connected_socket> f); stats get_stats() const { stats res = _stats; res.wait_reply = _outstanding.size(); return res; } stats& get_stats_internal() { return _stats; } auto next_message_id() { return _message_id++; } void wait_for_reply(id_type id, std::unique_ptr<reply_handler_base>&& h, std::experimental::optional<steady_clock_type::time_point> timeout) { if (timeout) { h->t.set_callback(std::bind(std::mem_fn(&client::wait_timed_out), this, id)); h->t.arm(timeout.value()); } _outstanding.emplace(id, std::move(h)); } void wait_timed_out(id_type id) { struct timeout_handler : reply_handler_base { virtual void operator()(client& client, id_type msg_id, temporary_buffer<char> data) {} }; _stats.timeout++; _outstanding[id]->timeout(); _outstanding[id] = std::make_unique<timeout_handler>(); } future<> stop() { if (_connected && !this->_error) { this->_error = true; return connection::stop(); } else { // connection::stop will fail on shutdown(); since we can't shutdown a // connect(), just wait for it to timeout return this->_stopped.get_future(); } } ipv4_addr peer_address() const { return _server_addr; } }; friend server; private: using rpc_handler = std::function<void (lw_shared_ptr<typename server::connection>, int64_t msgid, temporary_buffer<char> data)>; std::unordered_map<MsgType, rpc_handler> _handlers; Serializer _serializer; std::function<void(const sstring&)> _logger; public: protocol(Serializer&& serializer) : _serializer(std::forward<Serializer>(serializer)) {} template<typename Func> auto make_client(MsgType t); // returns a function which type depends on Func // if Func == Ret(Args...) then return function is // future<Ret>(protocol::client&, Args...) template<typename Func> auto register_handler(MsgType t, Func&& func); void unregister_handler(MsgType t) { _handlers.erase(t); } void set_logger(std::function<void(const sstring&)> logger) { _logger = logger; } void log(const sstring& str) { if (_logger) { _logger(str); _logger("\n"); } } void log(const client_info& info, id_type msg_id, const sstring& str) { log(to_sstring("client ") + inet_ntoa(info.addr.as_posix_sockaddr_in().sin_addr) + " msg_id " + to_sstring(msg_id) + ": " + str); } void log(const client_info& info, const sstring& str) { log(to_sstring("client ") + inet_ntoa(info.addr.as_posix_sockaddr_in().sin_addr) + ": " + str); } void log(ipv4_addr addr, const sstring& str) { log(to_sstring("client ") + inet_ntoa(in_addr{net::ntoh(addr.ip)}) + ": " + str); } private: void register_receiver(MsgType t, rpc_handler&& handler) { _handlers.emplace(t, std::move(handler)); } }; } #include "rpc_impl.hh" <|endoftext|>
<commit_before>/* * Redox - A modern, asynchronous, and wicked fast C++11 client for Redis * * https://github.com/hmartiro/redox * * Copyright 2015 - Hayk Martirosyan <hayk.mart at gmail dot com> * * 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 <vector> #include <set> #include <unordered_set> #include "command.hpp" #include "client.hpp" using namespace std; namespace redox { template <class ReplyT> Command<ReplyT>::Command(Redox *rdx, long id, const vector<string> &cmd, const function<void(Command<ReplyT> &)> &callback, double repeat, double after, bool free_memory, log::Logger &logger) : rdx_(rdx), id_(id), cmd_(cmd), repeat_(repeat), after_(after), free_memory_(free_memory), callback_(callback), last_error_(), logger_(logger) { timer_guard_.lock(); } template <class ReplyT> void Command<ReplyT>::wait() { unique_lock<mutex> lk(waiter_lock_); waiter_.wait(lk, [this]() { return waiting_done_.load(); }); waiting_done_ = {false}; } template <class ReplyT> void Command<ReplyT>::processReply(redisReply *r) { last_error_.clear(); reply_obj_ = r; if (reply_obj_ == nullptr) { reply_status_ = ERROR_REPLY; last_error_ = "Received null redisReply* from hiredis."; logger_.error() << last_error_; Redox::disconnectedCallback(rdx_->ctx_, REDIS_ERR); } else { lock_guard<mutex> lg(reply_guard_); parseReplyObject(); } invoke(); pending_--; waiting_done_ = true; waiter_.notify_all(); // Always free the reply object for repeating commands if (repeat_ > 0) { freeReply(); } else { // User calls .free() if (!free_memory_) return; // Free non-repeating commands automatically // once we receive expected replies if (pending_ == 0) free(); } } // This is the only method in Command that has // access to private members of Redox template <class ReplyT> void Command<ReplyT>::free() { lock_guard<mutex> lg(rdx_->free_queue_guard_); rdx_->commands_to_free_.push(id_); ev_async_send(rdx_->evloop_, &rdx_->watcher_free_); } template <class ReplyT> void Command<ReplyT>::freeReply() { if (reply_obj_ == nullptr) return; freeReplyObject(reply_obj_); reply_obj_ = nullptr; } /** * Create a copy of the reply and return it. Use a guard * to make sure we don't return a reply while it is being * modified. */ template <class ReplyT> ReplyT Command<ReplyT>::reply() { lock_guard<mutex> lg(reply_guard_); if (!ok()) { logger_.warning() << cmd() << ": Accessing reply value while status != OK."; } return reply_val_; } template <class ReplyT> string Command<ReplyT>::cmd() const { return rdx_->vecToStr(cmd_); } template <class ReplyT> bool Command<ReplyT>::isExpectedReply(int type) { if (reply_obj_->type == type) { reply_status_ = OK_REPLY; return true; } if (checkErrorReply() || checkNilReply()) return false; stringstream errorMessage; errorMessage << "Received reply of type " << reply_obj_->type << ", expected type " << type << "."; last_error_ = errorMessage.str(); logger_.error() << cmd() << ": " << last_error_; reply_status_ = WRONG_TYPE; return false; } template <class ReplyT> bool Command<ReplyT>::isExpectedReply(int typeA, int typeB) { if ((reply_obj_->type == typeA) || (reply_obj_->type == typeB)) { reply_status_ = OK_REPLY; return true; } if (checkErrorReply() || checkNilReply()) return false; stringstream errorMessage; errorMessage << "Received reply of type " << reply_obj_->type << ", expected type " << typeA << " or " << typeB << "."; last_error_ = errorMessage.str(); logger_.error() << cmd() << ": " << last_error_; reply_status_ = WRONG_TYPE; return false; } template <class ReplyT> bool Command<ReplyT>::checkErrorReply() { if (reply_obj_->type == REDIS_REPLY_ERROR) { if (reply_obj_->str != 0) { last_error_ = reply_obj_->str; } logger_.error() << cmd() << ": " << last_error_; reply_status_ = ERROR_REPLY; return true; } return false; } template <class ReplyT> bool Command<ReplyT>::checkNilReply() { if (reply_obj_->type == REDIS_REPLY_NIL) { logger_.warning() << cmd() << ": Nil reply."; reply_status_ = NIL_REPLY; return true; } return false; } // ---------------------------------------------------------------------------- // Specializations of parseReplyObject for all expected return types // ---------------------------------------------------------------------------- template <> void Command<redisReply *>::parseReplyObject() { if (!checkErrorReply()) reply_status_ = OK_REPLY; reply_val_ = reply_obj_; } template <> void Command<string>::parseReplyObject() { if (!isExpectedReply(REDIS_REPLY_STRING, REDIS_REPLY_STATUS)) return; reply_val_ = {reply_obj_->str, static_cast<size_t>(reply_obj_->len)}; } template <> void Command<char *>::parseReplyObject() { if (!isExpectedReply(REDIS_REPLY_STRING, REDIS_REPLY_STATUS)) return; reply_val_ = reply_obj_->str; } template <> void Command<int>::parseReplyObject() { if (!isExpectedReply(REDIS_REPLY_INTEGER)) return; reply_val_ = (int)reply_obj_->integer; } template <> void Command<long long int>::parseReplyObject() { if (!isExpectedReply(REDIS_REPLY_INTEGER)) return; reply_val_ = reply_obj_->integer; } template <> void Command<nullptr_t>::parseReplyObject() { if (!isExpectedReply(REDIS_REPLY_NIL)) return; reply_val_ = nullptr; } template <> void Command<vector<string>>::parseReplyObject() { if (!isExpectedReply(REDIS_REPLY_ARRAY)) return; for (size_t i = 0; i < reply_obj_->elements; i++) { redisReply *r = *(reply_obj_->element + i); reply_val_.emplace_back(r->str, r->len); } } template <> void Command<unordered_set<string>>::parseReplyObject() { if (!isExpectedReply(REDIS_REPLY_ARRAY)) return; for (size_t i = 0; i < reply_obj_->elements; i++) { redisReply *r = *(reply_obj_->element + i); reply_val_.emplace(r->str, r->len); } } template <> void Command<set<string>>::parseReplyObject() { if (!isExpectedReply(REDIS_REPLY_ARRAY)) return; for (size_t i = 0; i < reply_obj_->elements; i++) { redisReply *r = *(reply_obj_->element + i); reply_val_.emplace(r->str, r->len); } } // Explicit template instantiation for available types, so that the generated // library contains them and we can keep the method definitions out of the // header file. template class Command<redisReply *>; template class Command<string>; template class Command<char *>; template class Command<int>; template class Command<long long int>; template class Command<nullptr_t>; template class Command<vector<string>>; template class Command<set<string>>; template class Command<unordered_set<string>>; } // End namespace redox <commit_msg>Fix condition variable usage in Command<commit_after>/* * Redox - A modern, asynchronous, and wicked fast C++11 client for Redis * * https://github.com/hmartiro/redox * * Copyright 2015 - Hayk Martirosyan <hayk.mart at gmail dot com> * * 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 <vector> #include <set> #include <unordered_set> #include "command.hpp" #include "client.hpp" using namespace std; namespace redox { template <class ReplyT> Command<ReplyT>::Command(Redox *rdx, long id, const vector<string> &cmd, const function<void(Command<ReplyT> &)> &callback, double repeat, double after, bool free_memory, log::Logger &logger) : rdx_(rdx), id_(id), cmd_(cmd), repeat_(repeat), after_(after), free_memory_(free_memory), callback_(callback), last_error_(), logger_(logger) { timer_guard_.lock(); } template <class ReplyT> void Command<ReplyT>::wait() { unique_lock<mutex> lk(waiter_lock_); waiter_.wait(lk, [this]() { return waiting_done_.load(); }); waiting_done_ = {false}; } template <class ReplyT> void Command<ReplyT>::processReply(redisReply *r) { last_error_.clear(); reply_obj_ = r; if (reply_obj_ == nullptr) { reply_status_ = ERROR_REPLY; last_error_ = "Received null redisReply* from hiredis."; logger_.error() << last_error_; Redox::disconnectedCallback(rdx_->ctx_, REDIS_ERR); } else { lock_guard<mutex> lg(reply_guard_); parseReplyObject(); } invoke(); pending_--; { unique_lock<mutex> lk(waiter_lock_); waiting_done_ = true; } waiter_.notify_all(); // Always free the reply object for repeating commands if (repeat_ > 0) { freeReply(); } else { // User calls .free() if (!free_memory_) return; // Free non-repeating commands automatically // once we receive expected replies if (pending_ == 0) free(); } } // This is the only method in Command that has // access to private members of Redox template <class ReplyT> void Command<ReplyT>::free() { lock_guard<mutex> lg(rdx_->free_queue_guard_); rdx_->commands_to_free_.push(id_); ev_async_send(rdx_->evloop_, &rdx_->watcher_free_); } template <class ReplyT> void Command<ReplyT>::freeReply() { if (reply_obj_ == nullptr) return; freeReplyObject(reply_obj_); reply_obj_ = nullptr; } /** * Create a copy of the reply and return it. Use a guard * to make sure we don't return a reply while it is being * modified. */ template <class ReplyT> ReplyT Command<ReplyT>::reply() { lock_guard<mutex> lg(reply_guard_); if (!ok()) { logger_.warning() << cmd() << ": Accessing reply value while status != OK."; } return reply_val_; } template <class ReplyT> string Command<ReplyT>::cmd() const { return rdx_->vecToStr(cmd_); } template <class ReplyT> bool Command<ReplyT>::isExpectedReply(int type) { if (reply_obj_->type == type) { reply_status_ = OK_REPLY; return true; } if (checkErrorReply() || checkNilReply()) return false; stringstream errorMessage; errorMessage << "Received reply of type " << reply_obj_->type << ", expected type " << type << "."; last_error_ = errorMessage.str(); logger_.error() << cmd() << ": " << last_error_; reply_status_ = WRONG_TYPE; return false; } template <class ReplyT> bool Command<ReplyT>::isExpectedReply(int typeA, int typeB) { if ((reply_obj_->type == typeA) || (reply_obj_->type == typeB)) { reply_status_ = OK_REPLY; return true; } if (checkErrorReply() || checkNilReply()) return false; stringstream errorMessage; errorMessage << "Received reply of type " << reply_obj_->type << ", expected type " << typeA << " or " << typeB << "."; last_error_ = errorMessage.str(); logger_.error() << cmd() << ": " << last_error_; reply_status_ = WRONG_TYPE; return false; } template <class ReplyT> bool Command<ReplyT>::checkErrorReply() { if (reply_obj_->type == REDIS_REPLY_ERROR) { if (reply_obj_->str != 0) { last_error_ = reply_obj_->str; } logger_.error() << cmd() << ": " << last_error_; reply_status_ = ERROR_REPLY; return true; } return false; } template <class ReplyT> bool Command<ReplyT>::checkNilReply() { if (reply_obj_->type == REDIS_REPLY_NIL) { logger_.warning() << cmd() << ": Nil reply."; reply_status_ = NIL_REPLY; return true; } return false; } // ---------------------------------------------------------------------------- // Specializations of parseReplyObject for all expected return types // ---------------------------------------------------------------------------- template <> void Command<redisReply *>::parseReplyObject() { if (!checkErrorReply()) reply_status_ = OK_REPLY; reply_val_ = reply_obj_; } template <> void Command<string>::parseReplyObject() { if (!isExpectedReply(REDIS_REPLY_STRING, REDIS_REPLY_STATUS)) return; reply_val_ = {reply_obj_->str, static_cast<size_t>(reply_obj_->len)}; } template <> void Command<char *>::parseReplyObject() { if (!isExpectedReply(REDIS_REPLY_STRING, REDIS_REPLY_STATUS)) return; reply_val_ = reply_obj_->str; } template <> void Command<int>::parseReplyObject() { if (!isExpectedReply(REDIS_REPLY_INTEGER)) return; reply_val_ = (int)reply_obj_->integer; } template <> void Command<long long int>::parseReplyObject() { if (!isExpectedReply(REDIS_REPLY_INTEGER)) return; reply_val_ = reply_obj_->integer; } template <> void Command<nullptr_t>::parseReplyObject() { if (!isExpectedReply(REDIS_REPLY_NIL)) return; reply_val_ = nullptr; } template <> void Command<vector<string>>::parseReplyObject() { if (!isExpectedReply(REDIS_REPLY_ARRAY)) return; for (size_t i = 0; i < reply_obj_->elements; i++) { redisReply *r = *(reply_obj_->element + i); reply_val_.emplace_back(r->str, r->len); } } template <> void Command<unordered_set<string>>::parseReplyObject() { if (!isExpectedReply(REDIS_REPLY_ARRAY)) return; for (size_t i = 0; i < reply_obj_->elements; i++) { redisReply *r = *(reply_obj_->element + i); reply_val_.emplace(r->str, r->len); } } template <> void Command<set<string>>::parseReplyObject() { if (!isExpectedReply(REDIS_REPLY_ARRAY)) return; for (size_t i = 0; i < reply_obj_->elements; i++) { redisReply *r = *(reply_obj_->element + i); reply_val_.emplace(r->str, r->len); } } // Explicit template instantiation for available types, so that the generated // library contains them and we can keep the method definitions out of the // header file. template class Command<redisReply *>; template class Command<string>; template class Command<char *>; template class Command<int>; template class Command<long long int>; template class Command<nullptr_t>; template class Command<vector<string>>; template class Command<set<string>>; template class Command<unordered_set<string>>; } // End namespace redox <|endoftext|>
<commit_before>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: viewcontactofunocontrol.hxx,v $ * $Revision: 1.6 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org 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 Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef SVX_SDR_CONTACT_VIEWCONTACTOFUNOCONTROL_HXX #define SVX_SDR_CONTACT_VIEWCONTACTOFUNOCONTROL_HXX /** === begin UNO includes === **/ #include <com/sun/star/uno/Reference.hxx> /** === end UNO includes === **/ #include <svx/sdr/contact/viewcontactofsdrmediaobj.hxx> #include <svx/svxdllapi.h> #include <memory> class OutputDevice; class Window; class SdrUnoObj; namespace com { namespace sun { namespace star { namespace awt { class XControl; class XControlContainer; } } } } //........................................................................ namespace sdr { namespace contact { //........................................................................ //==================================================================== //= ViewContactOfUnoControl //==================================================================== class ViewContactOfUnoControl_Impl; class SVX_DLLPRIVATE ViewContactOfUnoControl : public ViewContactOfSdrObj { private: ::std::auto_ptr< ViewContactOfUnoControl_Impl > m_pImpl; public: ViewContactOfUnoControl( SdrUnoObj& _rUnoObject ); virtual ~ViewContactOfUnoControl(); /** access control to selected members */ struct SdrUnoObjAccessControl { friend class ::SdrUnoObj; private: SdrUnoObjAccessControl() { } }; /** retrieves the XControl asscociated with the ViewContact and the given device */ ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl > getUnoControlForDevice( const OutputDevice* _pDevice, const SdrUnoObjAccessControl& ) const; /** retrieves a temporary XControl instance, whose parent is the given window @seealso SdrUnoObj::GetTemporaryControlForWindow */ ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl > getTemporaryControlForWindow( const Window& _rWindow, ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlContainer >& _inout_ControlContainer ) const; /** invalidates all ViewObjectContacts This method is necessary when an SdrUnoObj changes completely, e.g. when some foreign instance set a new ->XControlModel. */ void invalidateAllContacts( const SdrUnoObjAccessControl& ); protected: virtual ViewObjectContact& CreateObjectSpecificViewObjectContact( ObjectContact& _rObjectContact ); // ViewContactOfSdrObj overridables virtual sal_Bool ShouldPaintObject( DisplayInfo& rDisplayInfo, const ViewObjectContact& rAssociatedVOC ); private: ViewContactOfUnoControl(); // never implemented ViewContactOfUnoControl( const ViewContactOfUnoControl& ); // never implemented ViewContactOfUnoControl& operator=( const ViewContactOfUnoControl& ); // never implemented }; //........................................................................ } } // namespace sdr::contact //........................................................................ #endif // SVX_SDR_CONTACT_VIEWCONTACTOFUNOCONTROL_HXX <commit_msg>INTEGRATION: CWS controlperformance (1.5.360); FILE MERGED 2008/03/28 13:18:51 fs 1.5.360.1: during #b6673211#: getUnoControlForDevice seems to be unused<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: viewcontactofunocontrol.hxx,v $ * $Revision: 1.7 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org 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 Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef SVX_SDR_CONTACT_VIEWCONTACTOFUNOCONTROL_HXX #define SVX_SDR_CONTACT_VIEWCONTACTOFUNOCONTROL_HXX /** === begin UNO includes === **/ #include <com/sun/star/uno/Reference.hxx> /** === end UNO includes === **/ #include <svx/sdr/contact/viewcontactofsdrmediaobj.hxx> #include <svx/svxdllapi.h> #include <memory> class OutputDevice; class Window; class SdrUnoObj; namespace com { namespace sun { namespace star { namespace awt { class XControl; class XControlContainer; } } } } //........................................................................ namespace sdr { namespace contact { //........................................................................ //==================================================================== //= ViewContactOfUnoControl //==================================================================== class ViewContactOfUnoControl_Impl; class SVX_DLLPRIVATE ViewContactOfUnoControl : public ViewContactOfSdrObj { private: ::std::auto_ptr< ViewContactOfUnoControl_Impl > m_pImpl; public: ViewContactOfUnoControl( SdrUnoObj& _rUnoObject ); virtual ~ViewContactOfUnoControl(); /** access control to selected members */ struct SdrUnoObjAccessControl { friend class ::SdrUnoObj; private: SdrUnoObjAccessControl() { } }; /** retrieves a temporary XControl instance, whose parent is the given window @seealso SdrUnoObj::GetTemporaryControlForWindow */ ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl > getTemporaryControlForWindow( const Window& _rWindow, ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlContainer >& _inout_ControlContainer ) const; /** invalidates all ViewObjectContacts This method is necessary when an SdrUnoObj changes completely, e.g. when some foreign instance set a new ->XControlModel. */ void invalidateAllContacts( const SdrUnoObjAccessControl& ); protected: virtual ViewObjectContact& CreateObjectSpecificViewObjectContact( ObjectContact& _rObjectContact ); // ViewContactOfSdrObj overridables virtual sal_Bool ShouldPaintObject( DisplayInfo& rDisplayInfo, const ViewObjectContact& rAssociatedVOC ); private: ViewContactOfUnoControl(); // never implemented ViewContactOfUnoControl( const ViewContactOfUnoControl& ); // never implemented ViewContactOfUnoControl& operator=( const ViewContactOfUnoControl& ); // never implemented }; //........................................................................ } } // namespace sdr::contact //........................................................................ #endif // SVX_SDR_CONTACT_VIEWCONTACTOFUNOCONTROL_HXX <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: AccessibleGraphicShape.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: thb $ $Date: 2002-11-29 17:56:47 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SVX_ACCESSIBILITY_ACCESSIBLE_GRAPHIC_SHAPE_HXX #include "AccessibleGraphicShape.hxx" #endif #include "ShapeTypeHandler.hxx" #include "SvxShapeTypes.hxx" using namespace ::accessibility; using namespace ::rtl; using namespace ::com::sun::star; using namespace ::drafts::com::sun::star::accessibility; //===== internal ============================================================ AccessibleGraphicShape::AccessibleGraphicShape ( const AccessibleShapeInfo& rShapeInfo, const AccessibleShapeTreeInfo& rShapeTreeInfo) : AccessibleShape (rShapeInfo, rShapeTreeInfo) { } AccessibleGraphicShape::~AccessibleGraphicShape (void) { } //===== XAccessibleImage ==================================================== ::rtl::OUString SAL_CALL AccessibleGraphicShape::getAccessibleImageDescription (void) throw (::com::sun::star::uno::RuntimeException) { return AccessibleShape::getAccessibleDescription (); } sal_Int32 SAL_CALL AccessibleGraphicShape::getAccessibleImageHeight (void) throw (::com::sun::star::uno::RuntimeException) { return AccessibleShape::getSize().Height; } sal_Int32 SAL_CALL AccessibleGraphicShape::getAccessibleImageWidth (void) throw (::com::sun::star::uno::RuntimeException) { return AccessibleShape::getSize().Width; } //===== XInterface ========================================================== com::sun::star::uno::Any SAL_CALL AccessibleGraphicShape::queryInterface (const com::sun::star::uno::Type & rType) throw (::com::sun::star::uno::RuntimeException) { ::com::sun::star::uno::Any aReturn = AccessibleShape::queryInterface (rType); if ( ! aReturn.hasValue()) aReturn = ::cppu::queryInterface (rType, static_cast<XAccessibleImage*>(this)); return aReturn; } void SAL_CALL AccessibleGraphicShape::acquire (void) throw () { AccessibleShape::acquire (); } void SAL_CALL AccessibleGraphicShape::release (void) throw () { AccessibleShape::release (); } //===== XServiceInfo ======================================================== ::rtl::OUString SAL_CALL AccessibleGraphicShape::getImplementationName (void) throw (::com::sun::star::uno::RuntimeException) { return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("AccessibleGraphicShape")); } ::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL AccessibleGraphicShape::getSupportedServiceNames (void) throw (::com::sun::star::uno::RuntimeException) { ThrowIfDisposed (); // Get list of supported service names from base class... uno::Sequence<OUString> aServiceNames = AccessibleShape::getSupportedServiceNames(); sal_Int32 nCount (aServiceNames.getLength()); // ...and add additional names. aServiceNames.realloc (nCount + 1); static const OUString sAdditionalServiceName (RTL_CONSTASCII_USTRINGPARAM( "drafts.com.sun.star.drawing.AccessibleGraphicShape")); aServiceNames[nCount] = sAdditionalServiceName; return aServiceNames; } //===== XTypeProvider =================================================== uno::Sequence<uno::Type> SAL_CALL AccessibleGraphicShape::getTypes (void) throw (uno::RuntimeException) { // Get list of types from the context base implementation... uno::Sequence<uno::Type> aTypeList (AccessibleShape::getTypes()); // ...and add the additional type for the component. long nTypeCount = aTypeList.getLength(); aTypeList.realloc (nTypeCount + 1); const uno::Type aImageType = ::getCppuType((const uno::Reference<XAccessibleImage>*)0); aTypeList[nTypeCount] = aImageType; return aTypeList; } /// Create the base name of this object, i.e. the name without appended number. ::rtl::OUString AccessibleGraphicShape::CreateAccessibleBaseName (void) throw (::com::sun::star::uno::RuntimeException) { ::rtl::OUString sName; ShapeTypeId nShapeType = ShapeTypeHandler::Instance().GetTypeId (mxShape); switch (nShapeType) { case DRAWING_GRAPHIC_OBJECT: sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("GraphicObjectShape")); break; default: sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("UnknownAccessibleGraphicShape")); uno::Reference<drawing::XShapeDescriptor> xDescriptor (mxShape, uno::UNO_QUERY); if (xDescriptor.is()) sName += ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM(": ")) + xDescriptor->getShapeType(); } return sName; } ::rtl::OUString AccessibleGraphicShape::CreateAccessibleDescription (void) throw (::com::sun::star::uno::RuntimeException) { return CreateAccessibleName (); } <commit_msg>INTEGRATION: CWS uaa02 (1.10.170); FILE MERGED 2003/04/14 16:56:41 thb 1.10.170.2: #108900# Moved service descriptions from drafts, changed getCharacterBounds() behaviour and implemented TEXT_CHANGED new/old value calculations 2003/04/11 17:06:50 mt 1.10.170.1: #108656# Moved accessibility from drafts to final<commit_after>/************************************************************************* * * $RCSfile: AccessibleGraphicShape.cxx,v $ * * $Revision: 1.11 $ * * last change: $Author: vg $ $Date: 2003-04-24 16:53:35 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SVX_ACCESSIBILITY_ACCESSIBLE_GRAPHIC_SHAPE_HXX #include "AccessibleGraphicShape.hxx" #endif #include "ShapeTypeHandler.hxx" #include "SvxShapeTypes.hxx" using namespace ::accessibility; using namespace ::rtl; using namespace ::com::sun::star; using namespace ::com::sun::star::accessibility; //===== internal ============================================================ AccessibleGraphicShape::AccessibleGraphicShape ( const AccessibleShapeInfo& rShapeInfo, const AccessibleShapeTreeInfo& rShapeTreeInfo) : AccessibleShape (rShapeInfo, rShapeTreeInfo) { } AccessibleGraphicShape::~AccessibleGraphicShape (void) { } //===== XAccessibleImage ==================================================== ::rtl::OUString SAL_CALL AccessibleGraphicShape::getAccessibleImageDescription (void) throw (::com::sun::star::uno::RuntimeException) { return AccessibleShape::getAccessibleDescription (); } sal_Int32 SAL_CALL AccessibleGraphicShape::getAccessibleImageHeight (void) throw (::com::sun::star::uno::RuntimeException) { return AccessibleShape::getSize().Height; } sal_Int32 SAL_CALL AccessibleGraphicShape::getAccessibleImageWidth (void) throw (::com::sun::star::uno::RuntimeException) { return AccessibleShape::getSize().Width; } //===== XInterface ========================================================== com::sun::star::uno::Any SAL_CALL AccessibleGraphicShape::queryInterface (const com::sun::star::uno::Type & rType) throw (::com::sun::star::uno::RuntimeException) { ::com::sun::star::uno::Any aReturn = AccessibleShape::queryInterface (rType); if ( ! aReturn.hasValue()) aReturn = ::cppu::queryInterface (rType, static_cast<XAccessibleImage*>(this)); return aReturn; } void SAL_CALL AccessibleGraphicShape::acquire (void) throw () { AccessibleShape::acquire (); } void SAL_CALL AccessibleGraphicShape::release (void) throw () { AccessibleShape::release (); } //===== XServiceInfo ======================================================== ::rtl::OUString SAL_CALL AccessibleGraphicShape::getImplementationName (void) throw (::com::sun::star::uno::RuntimeException) { return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("AccessibleGraphicShape")); } ::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL AccessibleGraphicShape::getSupportedServiceNames (void) throw (::com::sun::star::uno::RuntimeException) { ThrowIfDisposed (); // Get list of supported service names from base class... uno::Sequence<OUString> aServiceNames = AccessibleShape::getSupportedServiceNames(); sal_Int32 nCount (aServiceNames.getLength()); // ...and add additional names. aServiceNames.realloc (nCount + 1); static const OUString sAdditionalServiceName (RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.drawing.AccessibleGraphicShape")); aServiceNames[nCount] = sAdditionalServiceName; return aServiceNames; } //===== XTypeProvider =================================================== uno::Sequence<uno::Type> SAL_CALL AccessibleGraphicShape::getTypes (void) throw (uno::RuntimeException) { // Get list of types from the context base implementation... uno::Sequence<uno::Type> aTypeList (AccessibleShape::getTypes()); // ...and add the additional type for the component. long nTypeCount = aTypeList.getLength(); aTypeList.realloc (nTypeCount + 1); const uno::Type aImageType = ::getCppuType((const uno::Reference<XAccessibleImage>*)0); aTypeList[nTypeCount] = aImageType; return aTypeList; } /// Create the base name of this object, i.e. the name without appended number. ::rtl::OUString AccessibleGraphicShape::CreateAccessibleBaseName (void) throw (::com::sun::star::uno::RuntimeException) { ::rtl::OUString sName; ShapeTypeId nShapeType = ShapeTypeHandler::Instance().GetTypeId (mxShape); switch (nShapeType) { case DRAWING_GRAPHIC_OBJECT: sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("GraphicObjectShape")); break; default: sName = ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM("UnknownAccessibleGraphicShape")); uno::Reference<drawing::XShapeDescriptor> xDescriptor (mxShape, uno::UNO_QUERY); if (xDescriptor.is()) sName += ::rtl::OUString (RTL_CONSTASCII_USTRINGPARAM(": ")) + xDescriptor->getShapeType(); } return sName; } ::rtl::OUString AccessibleGraphicShape::CreateAccessibleDescription (void) throw (::com::sun::star::uno::RuntimeException) { return CreateAccessibleName (); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: customshapeproperties.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: rt $ $Date: 2005-09-09 00:11:38 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SDR_PROPERTIES_CUSTOMSHAPEPROPERTIES_HXX #include <svx/sdr/properties/customshapeproperties.hxx> #endif #ifndef _SVDOASHP_HXX #include <svdoashp.hxx> #endif #ifndef _EEITEMID_HXX #include <eeitemid.hxx> #endif #ifndef _SDTAGITM_HXX #include <sdtagitm.hxx> #endif #ifndef _SFX_WHITER_HXX #include <svtools/whiter.hxx> #endif #ifndef _SFXITEMSET_HXX #include <svtools/itemset.hxx> #endif ////////////////////////////////////////////////////////////////////////////// namespace sdr { namespace properties { SfxItemSet& CustomShapeProperties::CreateObjectSpecificItemSet(SfxItemPool& rPool) { return *(new SfxItemSet(rPool, // ranges from SdrAttrObj SDRATTR_START, SDRATTR_SHADOW_LAST, SDRATTR_MISC_FIRST, SDRATTR_MISC_LAST, SDRATTR_TEXTDIRECTION, SDRATTR_TEXTDIRECTION, // Graphic Attributes SDRATTR_GRAF_FIRST, SDRATTR_GRAF_LAST, // 3d Properties SDRATTR_3D_FIRST, SDRATTR_3D_LAST, // CustomShape properties SDRATTR_CUSTOMSHAPE_FIRST, SDRATTR_CUSTOMSHAPE_LAST, // range from SdrTextObj EE_ITEMS_START, EE_ITEMS_END, // end 0, 0)); } sal_Bool CustomShapeProperties::AllowItemChange(const sal_uInt16 nWhich, const SfxPoolItem* pNewItem ) const { sal_Bool bAllowItemChange = sal_True; if ( !pNewItem ) { if ( ( nWhich >= SDRATTR_CUSTOMSHAPE_FIRST ) && ( nWhich <= SDRATTR_CUSTOMSHAPE_LAST ) ) bAllowItemChange = sal_False; } if ( bAllowItemChange ) bAllowItemChange = TextProperties::AllowItemChange( nWhich, pNewItem ); return bAllowItemChange; } void CustomShapeProperties::ClearObjectItem(const sal_uInt16 nWhich) { if ( !nWhich ) { SfxWhichIter aIter( *mpItemSet ); sal_uInt16 nWhich = aIter.FirstWhich(); while( nWhich ) { TextProperties::ClearObjectItem( nWhich ); nWhich = aIter.NextWhich(); } } else TextProperties::ClearObjectItem( nWhich ); } void CustomShapeProperties::ClearObjectItemDirect(const sal_uInt16 nWhich) { if ( !nWhich ) { SfxWhichIter aIter( *mpItemSet ); sal_uInt16 nWhich = aIter.FirstWhich(); while( nWhich ) { TextProperties::ClearObjectItemDirect( nWhich ); nWhich = aIter.NextWhich(); } } else TextProperties::ClearObjectItemDirect( nWhich ); } void CustomShapeProperties::ItemSetChanged(const SfxItemSet& rSet) { SdrObjCustomShape& rObj = (SdrObjCustomShape&)GetSdrObject(); if( SFX_ITEM_SET == rSet.GetItemState( SDRATTR_TEXT_AUTOGROWHEIGHT ) ) { rObj.bTextFrame = ((SdrTextAutoGrowHeightItem&)rSet.Get( SDRATTR_TEXT_AUTOGROWHEIGHT )).GetValue() != 0; } // call parent TextProperties::ItemSetChanged(rSet); // local changes, removing cached objects rObj.InvalidateRenderGeometry(); } void CustomShapeProperties::ItemChange(const sal_uInt16 nWhich, const SfxPoolItem* pNewItem) { SdrTextObj& rObj = (SdrTextObj&)GetSdrObject(); OutlinerParaObject* pParaObj = rObj.GetOutlinerParaObject(); if( pNewItem && ( SDRATTR_TEXT_AUTOGROWHEIGHT == nWhich ) ) { rObj.bTextFrame = ((SdrTextAutoGrowHeightItem*)pNewItem)->GetValue() != 0; } // call parent TextProperties::ItemChange( nWhich, pNewItem ); } void CustomShapeProperties::ForceDefaultAttributes() { /* SJ: Following is is no good if creating customshapes leading to objects that are white after loading via xml SdrTextObj& rObj = (SdrTextObj&)GetSdrObject(); sal_Bool bTextFrame(rObj.IsTextFrame()); // force ItemSet GetObjectItemSet(); if(bTextFrame) { mpItemSet->Put(XLineStyleItem(XLINE_NONE)); mpItemSet->Put(XFillColorItem(String(), Color(COL_WHITE))); mpItemSet->Put(XFillStyleItem(XFILL_NONE)); } else { mpItemSet->Put(SvxAdjustItem(SVX_ADJUST_CENTER)); mpItemSet->Put(SdrTextHorzAdjustItem(SDRTEXTHORZADJUST_CENTER)); mpItemSet->Put(SdrTextVertAdjustItem(SDRTEXTVERTADJUST_CENTER)); } */ } CustomShapeProperties::CustomShapeProperties(SdrObject& rObj) : TextProperties(rObj) { } CustomShapeProperties::CustomShapeProperties(const CustomShapeProperties& rProps, SdrObject& rObj) : TextProperties(rProps, rObj) { } CustomShapeProperties::~CustomShapeProperties() { } BaseProperties& CustomShapeProperties::Clone(SdrObject& rObj) const { return *(new CustomShapeProperties(*this, rObj)); } } // end of namespace properties } // end of namespace sdr ////////////////////////////////////////////////////////////////////////////// // eof <commit_msg>INTEGRATION: CWS sj22 (1.5.462); FILE MERGED 2005/06/30 10:20:22 sj 1.5.462.2: #48499# fixed customshape update problem 2005/06/30 03:25:57 sj 1.5.462.1: #i48499# fixed customshape update problem<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: customshapeproperties.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: hr $ $Date: 2005-09-23 13:52:06 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SDR_PROPERTIES_CUSTOMSHAPEPROPERTIES_HXX #include <svx/sdr/properties/customshapeproperties.hxx> #endif #ifndef _SFXITEMSET_HXX #include <svtools/itemset.hxx> #endif #ifndef _SFXSTYLE_HXX #include <svtools/style.hxx> #endif #ifndef _SVDOASHP_HXX #include <svdoashp.hxx> #endif #ifndef _EEITEMID_HXX #include <eeitemid.hxx> #endif #ifndef _SDTAGITM_HXX #include <sdtagitm.hxx> #endif #ifndef _SFX_WHITER_HXX #include <svtools/whiter.hxx> #endif #ifndef _SFXITEMSET_HXX #include <svtools/itemset.hxx> #endif #ifndef _SFXSMPLHINT_HXX #include <svtools/smplhint.hxx> #endif ////////////////////////////////////////////////////////////////////////////// namespace sdr { namespace properties { SfxItemSet& CustomShapeProperties::CreateObjectSpecificItemSet(SfxItemPool& rPool) { return *(new SfxItemSet(rPool, // ranges from SdrAttrObj SDRATTR_START, SDRATTR_SHADOW_LAST, SDRATTR_MISC_FIRST, SDRATTR_MISC_LAST, SDRATTR_TEXTDIRECTION, SDRATTR_TEXTDIRECTION, // Graphic Attributes SDRATTR_GRAF_FIRST, SDRATTR_GRAF_LAST, // 3d Properties SDRATTR_3D_FIRST, SDRATTR_3D_LAST, // CustomShape properties SDRATTR_CUSTOMSHAPE_FIRST, SDRATTR_CUSTOMSHAPE_LAST, // range from SdrTextObj EE_ITEMS_START, EE_ITEMS_END, // end 0, 0)); } sal_Bool CustomShapeProperties::AllowItemChange(const sal_uInt16 nWhich, const SfxPoolItem* pNewItem ) const { sal_Bool bAllowItemChange = sal_True; if ( !pNewItem ) { if ( ( nWhich >= SDRATTR_CUSTOMSHAPE_FIRST ) && ( nWhich <= SDRATTR_CUSTOMSHAPE_LAST ) ) bAllowItemChange = sal_False; } if ( bAllowItemChange ) bAllowItemChange = TextProperties::AllowItemChange( nWhich, pNewItem ); return bAllowItemChange; } void CustomShapeProperties::ClearObjectItem(const sal_uInt16 nWhich) { if ( !nWhich ) { SfxWhichIter aIter( *mpItemSet ); sal_uInt16 nWhich = aIter.FirstWhich(); while( nWhich ) { TextProperties::ClearObjectItem( nWhich ); nWhich = aIter.NextWhich(); } } else TextProperties::ClearObjectItem( nWhich ); } void CustomShapeProperties::ClearObjectItemDirect(const sal_uInt16 nWhich) { if ( !nWhich ) { SfxWhichIter aIter( *mpItemSet ); sal_uInt16 nWhich = aIter.FirstWhich(); while( nWhich ) { TextProperties::ClearObjectItemDirect( nWhich ); nWhich = aIter.NextWhich(); } } else TextProperties::ClearObjectItemDirect( nWhich ); } void CustomShapeProperties::ItemSetChanged(const SfxItemSet& rSet) { SdrObjCustomShape& rObj = (SdrObjCustomShape&)GetSdrObject(); if( SFX_ITEM_SET == rSet.GetItemState( SDRATTR_TEXT_AUTOGROWHEIGHT ) ) { rObj.bTextFrame = ((SdrTextAutoGrowHeightItem&)rSet.Get( SDRATTR_TEXT_AUTOGROWHEIGHT )).GetValue() != 0; } // call parent TextProperties::ItemSetChanged(rSet); // local changes, removing cached objects rObj.InvalidateRenderGeometry(); } void CustomShapeProperties::ItemChange(const sal_uInt16 nWhich, const SfxPoolItem* pNewItem) { SdrTextObj& rObj = (SdrTextObj&)GetSdrObject(); OutlinerParaObject* pParaObj = rObj.GetOutlinerParaObject(); if( pNewItem && ( SDRATTR_TEXT_AUTOGROWHEIGHT == nWhich ) ) { rObj.bTextFrame = ((SdrTextAutoGrowHeightItem*)pNewItem)->GetValue() != 0; } // call parent TextProperties::ItemChange( nWhich, pNewItem ); } void CustomShapeProperties::ForceDefaultAttributes() { /* SJ: Following is is no good if creating customshapes leading to objects that are white after loading via xml SdrTextObj& rObj = (SdrTextObj&)GetSdrObject(); sal_Bool bTextFrame(rObj.IsTextFrame()); // force ItemSet GetObjectItemSet(); if(bTextFrame) { mpItemSet->Put(XLineStyleItem(XLINE_NONE)); mpItemSet->Put(XFillColorItem(String(), Color(COL_WHITE))); mpItemSet->Put(XFillStyleItem(XFILL_NONE)); } else { mpItemSet->Put(SvxAdjustItem(SVX_ADJUST_CENTER)); mpItemSet->Put(SdrTextHorzAdjustItem(SDRTEXTHORZADJUST_CENTER)); mpItemSet->Put(SdrTextVertAdjustItem(SDRTEXTVERTADJUST_CENTER)); } */ } CustomShapeProperties::CustomShapeProperties(SdrObject& rObj) : TextProperties(rObj) { } CustomShapeProperties::CustomShapeProperties(const CustomShapeProperties& rProps, SdrObject& rObj) : TextProperties(rProps, rObj) { } CustomShapeProperties::~CustomShapeProperties() { } BaseProperties& CustomShapeProperties::Clone(SdrObject& rObj) const { return *(new CustomShapeProperties(*this, rObj)); } void CustomShapeProperties::Notify( SfxBroadcaster& rBC, const SfxHint& rHint ) { TextProperties::Notify( rBC, rHint ); sal_Bool bRemoveRenderGeometry = sal_False; const SfxStyleSheetHint *pStyleHint = PTR_CAST( SfxStyleSheetHint, &rHint ); const SfxSimpleHint *pSimpleHint = PTR_CAST( SfxSimpleHint, &rHint ); if ( pStyleHint && pStyleHint->GetStyleSheet() == GetStyleSheet() ) { switch( pStyleHint->GetHint() ) { case SFX_STYLESHEET_MODIFIED : case SFX_STYLESHEET_CHANGED : bRemoveRenderGeometry = sal_True; break; }; } else if ( pSimpleHint && pSimpleHint->GetId() == SFX_HINT_DATACHANGED ) { bRemoveRenderGeometry = sal_True; } if ( bRemoveRenderGeometry ) { // local changes, removing cached objects SdrObjCustomShape& rObj = (SdrObjCustomShape&)GetSdrObject(); rObj.InvalidateRenderGeometry(); } } } // end of namespace properties } // end of namespace sdr ////////////////////////////////////////////////////////////////////////////// // eof <|endoftext|>
<commit_before>// $Id: kelly_error_estimator.C,v 1.8 2005-03-10 22:05:48 jwpeterson Exp $ // The libMesh Finite Element Library. // Copyright (C) 2002-2005 Benjamin S. Kirk, John W. Peterson // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library 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 // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // C++ includes #include <algorithm> // for std::fill #include <cmath> // for sqrt // Local Includes #include "libmesh_common.h" #include "kelly_error_estimator.h" #include "dof_map.h" #include "fe.h" #include "fe_interface.h" #include "quadrature_gauss.h" #include "libmesh_logging.h" #include "elem.h" //----------------------------------------------------------------- // ErrorEstimator implementations void KellyErrorEstimator::estimate_error (const System& system, std::vector<float>& error_per_cell) { START_LOG("flux_jump()", "KellyErrorEstimator"); /* Conventions for assigning the direction of the normal: - e & f are global element ids Case (1.) Elements are at the same level, e<f Compute the flux jump on the face and add it as a contribution to error_per_cell[e] and error_per_cell[f] ---------------------- | | | | | f | | | | | e |---> n | | | | | | | ---------------------- Case (2.) The neighbor is at a higher level. Compute the flux jump on e's face and add it as a contribution to error_per_cell[e] and error_per_cell[f] ---------------------- | | | | | | e |---> n | | | | | |-----------| f | | | | | | | | | | | | | ---------------------- */ // The current mesh const Mesh& mesh = system.get_mesh(); // The dimensionality of the mesh const unsigned int dim = mesh.mesh_dimension(); // The number of variables in the system const unsigned int n_vars = system.n_vars(); // The DofMap for this system const DofMap& dof_map = system.get_dof_map(); // Resize the error_per_cell vector to be // the number of elements, initialize it to 0. error_per_cell.resize (mesh.n_elem()); std::fill (error_per_cell.begin(), error_per_cell.end(), 0.); // Check for a valid component_mask if (!component_mask.empty()) if (component_mask.size() != n_vars) { std::cerr << "ERROR: component_mask is the wrong size:" << std::endl << " component_mask.size()=" << component_mask.size() << std::endl << " n_vars=" << n_vars << std::endl; error(); } // Loop over all the variables in the system for (unsigned int var=0; var<n_vars; var++) { // Possibly skip this variable if (!component_mask.empty()) if (component_mask[var] == false) continue; // The (string) name of this variable const std::string& var_name = system.variable_name(var); // The type of finite element to use for this variable const FEType& fe_type = dof_map.variable_type (var); // Finite element objects for the same face from // different sides AutoPtr<FEBase> fe_e (FEBase::build (dim, fe_type)); AutoPtr<FEBase> fe_f (FEBase::build (dim, fe_type)); // Build an appropriate Gaussian quadrature rule QGauss qrule (dim-1, fe_type.default_quadrature_order()); // Tell the finite element for element e about the quadrature // rule. The finite element for element f need not know about it fe_e->attach_quadrature_rule (&qrule); // By convention we will always do the integration // on the face of element e. Get its Jacobian values, etc.. const std::vector<Real>& JxW_face = fe_e->get_JxW(); const std::vector<Point>& qface_point = fe_e->get_xyz(); const std::vector<Point>& face_normals = fe_e->get_normals(); // The quadrature points on element f. These will be computed // from the quadrature points on element e. std::vector<Point> qp_f; // The shape function gradients on elements e & f const std::vector<std::vector<RealGradient> > & dphi_e = fe_e->get_dphi(); const std::vector<std::vector<RealGradient> > & dphi_f = fe_f->get_dphi(); // The global DOF indices for elements e & f std::vector<unsigned int> dof_indices_e; std::vector<unsigned int> dof_indices_f; // Iterate over all the active elements in the mesh // that live on this processor. MeshBase::const_element_iterator elem_it = mesh.active_local_elements_begin(); const MeshBase::const_element_iterator elem_end = mesh.active_local_elements_end(); for (; elem_it != elem_end; ++elem_it) { // e is necessarily an active element on the local processor const Elem* e = *elem_it; const unsigned int e_id = e->id(); // Loop over the neighbors of element e for (unsigned int n_e=0; n_e<e->n_neighbors(); n_e++) { if (e->neighbor(n_e) != NULL) // e is not on the boundary { const Elem* f = e->neighbor(n_e); const unsigned int f_id = f->id(); if ( //------------------------------------- ((f->active()) && (f->level() == e->level()) && (e_id < f_id)) // Case 1. || //------------------------------------- (f->level() < e->level()) // Case 2. ) //------------------------------------- { // Update the shape functions on side s_e of // element e fe_e->reinit (e, n_e); // Build the side AutoPtr<Elem> side (e->side(n_e)); // Get the maximum h for this side const Real h = side->hmax(); // Get the DOF indices for the two elements dof_map.dof_indices (e, dof_indices_e, var); dof_map.dof_indices (f, dof_indices_f, var); // The number of DOFS on each element const unsigned int n_dofs_e = dof_indices_e.size(); const unsigned int n_dofs_f = dof_indices_f.size(); // The number of quadrature points const unsigned int n_qp = qrule.n_points(); // Find the location of the quadrature points // on element f FEInterface::inverse_map (dim, fe_type, f, qface_point, qp_f); // Compute the shape functions on element f // at the quadrature points of element e fe_f->reinit (f, &qp_f); // The error contribution from this face Real error = 1.e-10; // loop over the integration points on the face for (unsigned int qp=0; qp<n_qp; qp++) { // The solution gradient from each element Gradient grad_e, grad_f; // Compute the solution gradient on element e for (unsigned int i=0; i<n_dofs_e; i++) grad_e.add_scaled (dphi_e[i][qp], system.current_solution(dof_indices_e[i])); // Compute the solution gradient on element f for (unsigned int i=0; i<n_dofs_f; i++) grad_f.add_scaled (dphi_f[i][qp], system.current_solution(dof_indices_f[i])); // The flux jump at the face const Number jump = (grad_e - grad_f)*face_normals[qp]; // The flux jump squared. If using complex numbers, // std::norm(z) returns |z|^2, where |z| is the modulus of z. #ifndef USE_COMPLEX_NUMBERS const Real jump2 = jump*jump; #else const Real jump2 = std::norm(jump); #endif // Integrate the error on the face. The error is // scaled by an additional power of h, where h is // the maximum side length for the element. This // arises in the definition of the indicator. error += JxW_face[qp]*h*jump2; } // End quadrature point loop // Add the error contribution to elements e & f error_per_cell[e_id] += error; error_per_cell[f_id] += error; } // end if case 1 or case 2 } // if (e->neigbor(n_e) != NULL) // Otherwise, e is on the boundary. If it happens to // be on a Dirichlet boundary, we need not do anything. // On the other hand, if e is on a Neumann (flux) boundary // with grad(u).n = g, we need to compute the additional residual // (h * \int |g - grad(u_h).n|^2 dS)^(1/2). // We can only do this with some knowledge of the boundary // conditions, i.e. the user must have attached an appropriate // BC function. else { if (this->_bc_function != NULL) { // here(); // Update the shape functions on side s_e of element e fe_e->reinit (e, n_e); // The reinitialization also recomputes the locations of // the quadrature points on the side. By checking if the // first quadrature point on the side is on a flux boundary // for a particular variable, we will determine if the whole // element is on a flux boundary (assuming quadrature points // are strictly contained in the side). if (this->_bc_function(system, qface_point[0], var_name).first) { // Build the side AutoPtr<Elem> side (e->side(n_e)); // Get the maximum h for this side const Real h = side->hmax(); // Get the DOF indices dof_map.dof_indices (e, dof_indices_e, var); // The number of DOFS on each element const unsigned int n_dofs_e = dof_indices_e.size(); // The number of quadrature points const unsigned int n_qp = qrule.n_points(); // The error contribution from this face Real error = 1.e-10; // loop over the integration points on the face. for (unsigned int qp=0; qp<n_qp; qp++) { // Value of the imposed flux BC at this quadrature point. const std::pair<bool,Real> flux_bc = this->_bc_function(system, qface_point[qp], var_name); // Be sure the BC function still thinks we're on the // flux boundary. assert (flux_bc.first == true); // The solution gradient from each element Gradient grad_e; // Compute the solution gradient on element e for (unsigned int i=0; i<n_dofs_e; i++) grad_e.add_scaled (dphi_e[i][qp], system.current_solution(dof_indices_e[i])); // The difference between the desired BC and the approximate solution. const Number jump = flux_bc.second - grad_e*face_normals[qp]; // The flux jump squared. If using complex numbers, // std::norm(z) returns |z|^2, where |z| is the modulus of z. #ifndef USE_COMPLEX_NUMBERS const Real jump2 = jump*jump; #else const Real jump2 = std::norm(jump); #endif // std::cout << "Error contribution from " // << var_name // << " flux BC: " // << JxW_face[qp]*h*jump2 // << std::endl; // Integrate the error on the face. The error is // scaled by an additional power of h, where h is // the maximum side length for the element. This // arises in the definition of the indicator. error += JxW_face[qp]*h*jump2; } // End quadrature point loop // Add the error contribution to elements e & f error_per_cell[e_id] += error; } // end if side on flux boundary } // end if _bc_function != NULL } // end if (e->neighbor(n_e) == NULL) } // end loop over neighbors } // End loop over active local elements } // End loop over variables // Each processor has now computed the error contribuions // for its local elements. We need to sum the vector // and then take the square-root of each component. Note // that we only need to sum if we are running on multiple // processors, and we only need to take the square-root // if the value is nonzero. There will in general be many // zeros for the inactive elements. // First sum the vector this->reduce_error(error_per_cell); // Compute the square-root of each component. for (unsigned int i=0; i<error_per_cell.size(); i++) if (error_per_cell[i] != 0.) error_per_cell[i] = std::sqrt(error_per_cell[i]); STOP_LOG("flux_jump()", "KellyErrorEstimator"); } void KellyErrorEstimator::attach_flux_bc_function (std::pair<bool,Real> fptr(const System& system, const Point& p, const std::string& var_name)) { assert (fptr != NULL); _bc_function = fptr; } <commit_msg>apparently 1.e-10 is too large for some applications. Just needs to be a small positive number, but should not otherwise affect the error vector<commit_after>// $Id: kelly_error_estimator.C,v 1.9 2005-03-21 01:36:31 benkirk Exp $ // The libMesh Finite Element Library. // Copyright (C) 2002-2005 Benjamin S. Kirk, John W. Peterson // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library 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 // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // C++ includes #include <algorithm> // for std::fill #include <cmath> // for sqrt // Local Includes #include "libmesh_common.h" #include "kelly_error_estimator.h" #include "dof_map.h" #include "fe.h" #include "fe_interface.h" #include "quadrature_gauss.h" #include "libmesh_logging.h" #include "elem.h" //----------------------------------------------------------------- // ErrorEstimator implementations void KellyErrorEstimator::estimate_error (const System& system, std::vector<float>& error_per_cell) { START_LOG("flux_jump()", "KellyErrorEstimator"); /* Conventions for assigning the direction of the normal: - e & f are global element ids Case (1.) Elements are at the same level, e<f Compute the flux jump on the face and add it as a contribution to error_per_cell[e] and error_per_cell[f] ---------------------- | | | | | f | | | | | e |---> n | | | | | | | ---------------------- Case (2.) The neighbor is at a higher level. Compute the flux jump on e's face and add it as a contribution to error_per_cell[e] and error_per_cell[f] ---------------------- | | | | | | e |---> n | | | | | |-----------| f | | | | | | | | | | | | | ---------------------- */ // The current mesh const Mesh& mesh = system.get_mesh(); // The dimensionality of the mesh const unsigned int dim = mesh.mesh_dimension(); // The number of variables in the system const unsigned int n_vars = system.n_vars(); // The DofMap for this system const DofMap& dof_map = system.get_dof_map(); // Resize the error_per_cell vector to be // the number of elements, initialize it to 0. error_per_cell.resize (mesh.n_elem()); std::fill (error_per_cell.begin(), error_per_cell.end(), 0.); // Check for a valid component_mask if (!component_mask.empty()) if (component_mask.size() != n_vars) { std::cerr << "ERROR: component_mask is the wrong size:" << std::endl << " component_mask.size()=" << component_mask.size() << std::endl << " n_vars=" << n_vars << std::endl; error(); } // Loop over all the variables in the system for (unsigned int var=0; var<n_vars; var++) { // Possibly skip this variable if (!component_mask.empty()) if (component_mask[var] == false) continue; // The (string) name of this variable const std::string& var_name = system.variable_name(var); // The type of finite element to use for this variable const FEType& fe_type = dof_map.variable_type (var); // Finite element objects for the same face from // different sides AutoPtr<FEBase> fe_e (FEBase::build (dim, fe_type)); AutoPtr<FEBase> fe_f (FEBase::build (dim, fe_type)); // Build an appropriate Gaussian quadrature rule QGauss qrule (dim-1, fe_type.default_quadrature_order()); // Tell the finite element for element e about the quadrature // rule. The finite element for element f need not know about it fe_e->attach_quadrature_rule (&qrule); // By convention we will always do the integration // on the face of element e. Get its Jacobian values, etc.. const std::vector<Real>& JxW_face = fe_e->get_JxW(); const std::vector<Point>& qface_point = fe_e->get_xyz(); const std::vector<Point>& face_normals = fe_e->get_normals(); // The quadrature points on element f. These will be computed // from the quadrature points on element e. std::vector<Point> qp_f; // The shape function gradients on elements e & f const std::vector<std::vector<RealGradient> > & dphi_e = fe_e->get_dphi(); const std::vector<std::vector<RealGradient> > & dphi_f = fe_f->get_dphi(); // The global DOF indices for elements e & f std::vector<unsigned int> dof_indices_e; std::vector<unsigned int> dof_indices_f; // Iterate over all the active elements in the mesh // that live on this processor. MeshBase::const_element_iterator elem_it = mesh.active_local_elements_begin(); const MeshBase::const_element_iterator elem_end = mesh.active_local_elements_end(); for (; elem_it != elem_end; ++elem_it) { // e is necessarily an active element on the local processor const Elem* e = *elem_it; const unsigned int e_id = e->id(); // Loop over the neighbors of element e for (unsigned int n_e=0; n_e<e->n_neighbors(); n_e++) { if (e->neighbor(n_e) != NULL) // e is not on the boundary { const Elem* f = e->neighbor(n_e); const unsigned int f_id = f->id(); if ( //------------------------------------- ((f->active()) && (f->level() == e->level()) && (e_id < f_id)) // Case 1. || //------------------------------------- (f->level() < e->level()) // Case 2. ) //------------------------------------- { // Update the shape functions on side s_e of // element e fe_e->reinit (e, n_e); // Build the side AutoPtr<Elem> side (e->side(n_e)); // Get the maximum h for this side const Real h = side->hmax(); // Get the DOF indices for the two elements dof_map.dof_indices (e, dof_indices_e, var); dof_map.dof_indices (f, dof_indices_f, var); // The number of DOFS on each element const unsigned int n_dofs_e = dof_indices_e.size(); const unsigned int n_dofs_f = dof_indices_f.size(); // The number of quadrature points const unsigned int n_qp = qrule.n_points(); // Find the location of the quadrature points // on element f FEInterface::inverse_map (dim, fe_type, f, qface_point, qp_f); // Compute the shape functions on element f // at the quadrature points of element e fe_f->reinit (f, &qp_f); // The error contribution from this face Real error = 1.e-30; // loop over the integration points on the face for (unsigned int qp=0; qp<n_qp; qp++) { // The solution gradient from each element Gradient grad_e, grad_f; // Compute the solution gradient on element e for (unsigned int i=0; i<n_dofs_e; i++) grad_e.add_scaled (dphi_e[i][qp], system.current_solution(dof_indices_e[i])); // Compute the solution gradient on element f for (unsigned int i=0; i<n_dofs_f; i++) grad_f.add_scaled (dphi_f[i][qp], system.current_solution(dof_indices_f[i])); // The flux jump at the face const Number jump = (grad_e - grad_f)*face_normals[qp]; // The flux jump squared. If using complex numbers, // std::norm(z) returns |z|^2, where |z| is the modulus of z. #ifndef USE_COMPLEX_NUMBERS const Real jump2 = jump*jump; #else const Real jump2 = std::norm(jump); #endif // Integrate the error on the face. The error is // scaled by an additional power of h, where h is // the maximum side length for the element. This // arises in the definition of the indicator. error += JxW_face[qp]*h*jump2; } // End quadrature point loop // Add the error contribution to elements e & f error_per_cell[e_id] += error; error_per_cell[f_id] += error; } // end if case 1 or case 2 } // if (e->neigbor(n_e) != NULL) // Otherwise, e is on the boundary. If it happens to // be on a Dirichlet boundary, we need not do anything. // On the other hand, if e is on a Neumann (flux) boundary // with grad(u).n = g, we need to compute the additional residual // (h * \int |g - grad(u_h).n|^2 dS)^(1/2). // We can only do this with some knowledge of the boundary // conditions, i.e. the user must have attached an appropriate // BC function. else { if (this->_bc_function != NULL) { // here(); // Update the shape functions on side s_e of element e fe_e->reinit (e, n_e); // The reinitialization also recomputes the locations of // the quadrature points on the side. By checking if the // first quadrature point on the side is on a flux boundary // for a particular variable, we will determine if the whole // element is on a flux boundary (assuming quadrature points // are strictly contained in the side). if (this->_bc_function(system, qface_point[0], var_name).first) { // Build the side AutoPtr<Elem> side (e->side(n_e)); // Get the maximum h for this side const Real h = side->hmax(); // Get the DOF indices dof_map.dof_indices (e, dof_indices_e, var); // The number of DOFS on each element const unsigned int n_dofs_e = dof_indices_e.size(); // The number of quadrature points const unsigned int n_qp = qrule.n_points(); // The error contribution from this face Real error = 1.e-10; // loop over the integration points on the face. for (unsigned int qp=0; qp<n_qp; qp++) { // Value of the imposed flux BC at this quadrature point. const std::pair<bool,Real> flux_bc = this->_bc_function(system, qface_point[qp], var_name); // Be sure the BC function still thinks we're on the // flux boundary. assert (flux_bc.first == true); // The solution gradient from each element Gradient grad_e; // Compute the solution gradient on element e for (unsigned int i=0; i<n_dofs_e; i++) grad_e.add_scaled (dphi_e[i][qp], system.current_solution(dof_indices_e[i])); // The difference between the desired BC and the approximate solution. const Number jump = flux_bc.second - grad_e*face_normals[qp]; // The flux jump squared. If using complex numbers, // std::norm(z) returns |z|^2, where |z| is the modulus of z. #ifndef USE_COMPLEX_NUMBERS const Real jump2 = jump*jump; #else const Real jump2 = std::norm(jump); #endif // std::cout << "Error contribution from " // << var_name // << " flux BC: " // << JxW_face[qp]*h*jump2 // << std::endl; // Integrate the error on the face. The error is // scaled by an additional power of h, where h is // the maximum side length for the element. This // arises in the definition of the indicator. error += JxW_face[qp]*h*jump2; } // End quadrature point loop // Add the error contribution to elements e & f error_per_cell[e_id] += error; } // end if side on flux boundary } // end if _bc_function != NULL } // end if (e->neighbor(n_e) == NULL) } // end loop over neighbors } // End loop over active local elements } // End loop over variables // Each processor has now computed the error contribuions // for its local elements. We need to sum the vector // and then take the square-root of each component. Note // that we only need to sum if we are running on multiple // processors, and we only need to take the square-root // if the value is nonzero. There will in general be many // zeros for the inactive elements. // First sum the vector this->reduce_error(error_per_cell); // Compute the square-root of each component. for (unsigned int i=0; i<error_per_cell.size(); i++) if (error_per_cell[i] != 0.) error_per_cell[i] = std::sqrt(error_per_cell[i]); STOP_LOG("flux_jump()", "KellyErrorEstimator"); } void KellyErrorEstimator::attach_flux_bc_function (std::pair<bool,Real> fptr(const System& system, const Point& p, const std::string& var_name)) { assert (fptr != NULL); _bc_function = fptr; } <|endoftext|>
<commit_before>#include "qca.hpp" #include "utilities.hpp" #include <map> #include "version.hpp" #include <ctime> /* * TODO * ---- * * * P-P for three plaquets (bond system) * * P-P with dead cell (bond and qf) * * energies with dead cell? -- shouldn't make much difference * * grand canonical * * number of electrons per cell for different a and b * * number of electrons, considering Vext or dead cell * * P-P * * compare energy, P-P for bond, qf, gc * * * * Output for the following command does not look correct to me: * ./runQca -m bondDP -p 1 -P 0 -Pext 0,1,2,3 -a 1,2 -E */ class EpsilonLess { public: EpsilonLess (double e_ = 1E-10) : e(e_) {} bool operator() (double a, double b) { return b-a > e; } private: double e; }; CommandLineOptions setupCLOptions () { CommandLineOptions o; o.add("help", "h", "Print this help message.") .add("version", "Print program version.") .add("model", "m", "Which QCA model to use. Options are: bond, bondDP, fixed2, fixed6, fixed2DP, fixed6DP, grand, grand2DP, grand6DP.") .add("", "p", "Number of plaquets.") .add("", "t", "Hopping parameter.") .add("", "td", "Diagonal hopping parameter.") .add("", "ti", "Inter-plaquet hopping parameter.") .add("", "V0", "On-site coulomb repulsion (Hubbard U).") .add("", "mu", "Chemical potential.") .add("", "Vext", "External potential.") .add("", "Pext", "External, 'driving' polarisation of a 'dead plaquet' to the left of the linear chain system.") .add("", "a", "Intra-plaquet spacing.") .add("", "b", "Inter-plaquet spacing.") .add("", "beta", "Inverse temperature.") .add("energy-spectrum", "E", "Calculate the energy spectrum.") .add("polarisation", "P", "Calculate the polarisation for the specified plaquet(s).") .add("particle-number", "N", "Calculate the particle number for the specified plaquet(s)."); o["p"].setDefault(1); o["t"].setDefault(1); o["td"].setDefault(0); o["ti"].setDefault(0); o["V0"].setDefault(0); o["mu"].setDefault(0); o["Vext"].setDefault(0); o["Pext"].setDefault(0); o["a"].setDefault(1); o["b"].setDefault(1.75); o["beta"].setDefault(1); return o; } void printUsage (CommandLineOptions& o) { std::cerr << "Usage: " << std::endl; std::cerr << o.usage(); } enum OutputMode {Header, Line, None}; template<class System> class Measurement { public: Measurement (OptionSection o_) : o(o_), s(o_), needHeader(true), globalFirst(true) { for (OptionSection::OptionsType::iterator i=o.getOptions().begin(); i!=o.getOptions().end(); i++) outputConfig[i->getName()] = Header; outputConfig["energy-spectrum"] = None; outputConfig["polarisation"] = None; outputConfig["particle-number"] = None; outputConfig["help"] = None; outputConfig["version"] = None; } void setParam (const std::string& param, const OptionValue& value) { o[param] = value; if (outputConfig[param] == Header) needHeader = true; } void measure (const std::string& param, const OptionValue& value) { setParam(param, value); measure(); } void measure () { s.setParameters(o); s.update(); if (o["energy-spectrum"].isSet()) measureEnergies(); if (o["polarisation"].isSet()) measurePolarisation(); if (o["particle-number"].isSet()) measureParticleNumber(); store(); } void measureEnergies () { E.resize(0); typedef std::map<double, int, EpsilonLess> myMap; typedef myMap::const_iterator mapIt; myMap evs; for (int i=0; i<s.energies().size(); i++) evs[s.energies()(i)]++; for (mapIt i=evs.begin(); i!=evs.end(); i++) { std::vector<double> v(3); v[0] = i->first; v[1] = i->first - s.Emin(); v[2] = i->second; E.push_back(v); } } void measurePolarisation () { P.resize(0); std::vector<size_t> ps = o["polarisation"]; for (size_t i=0; i<ps.size(); i++) { if (ps[i] >= s.N_p) { std::cerr << std::endl << "Polarisation: There is no plaquet " << ps[i] << " in this system." << std::endl; std::exit(EXIT_FAILURE); } P.push_back(s.measure(o["beta"], s.P(ps[i]))); } } void measureParticleNumber () { N.resize(0); std::vector<size_t> ns = o["particle-number"]; for (size_t i=0; i<ns.size(); i++) { if (ns[i] >= s.N_p) { std::cerr << std::endl << "Particle number: There is no plaquet " << ns[i] << " in this system." << std::endl; std::exit(EXIT_FAILURE); } N.push_back(s.measure(o["beta"], s.N(ns[i]))); } } void store () { // always print energy spectrum as a separate block if (o["energy-spectrum"].isSet()) { printHeaderAll(); std::cout << "# " << std::endl << "# E\tE-Emin\tDegeneracy" << std::endl; for (size_t i=0; i<E.size(); i++) std::cout << E[i][0] << "\t" << E[i][1] << "\t" << E[i][2] << std::endl; std::cout << std::endl; } if (o["polarisation"].isSet() || o["particle-number"].isSet()) { if (needHeader) { printHeader(); std::cout << "# " << std::endl << "# "; bool first = true; for (typename OutputMap::const_iterator i=outputConfig.begin(); i!=outputConfig.end(); i++) if (i->second == Line) { if (!first) std::cout << "\t"; else first = false; std::cout << i->first; } if (o["polarisation"].isSet()) { std::vector<size_t> ps = o["polarisation"]; for (size_t i=0; i<ps.size(); i++) { if (!first) std::cout << "\t"; else first = false; std::cout << "P" << ps[i]; } } if (o["particle-number"].isSet()) { std::vector<size_t> ns = o["particle-number"]; for (size_t i=0; i<ns.size(); i++) { if (!first) std::cout << "\t"; else first = false; std::cout << "N" << ns[i]; } } std::cout << std::endl; needHeader = false; } bool first = true; for (typename OutputMap::const_iterator i=outputConfig.begin(); i!=outputConfig.end(); i++) if (i->second == Line) { if (!first) std::cout << "\t"; else first = false; std::cout << o[i->first]; } if (o["polarisation"].isSet()) for (size_t j=0; j<P.size(); j++) { if (!first) std::cout << "\t"; else first = false; std::cout << P[j]; } if (o["particle-number"].isSet()) for (size_t j=0; j<N.size(); j++) { if (!first) std::cout << "\t"; else first = false; std::cout << N[j]; } std::cout << std::endl; } } void printHeader () { if (!globalFirst) std::cout << std::endl; else globalFirst = false; std::cout << "# program version: " << GIT_PROGRAM_VERSION << std::endl << "# date: " << getTime() << std::endl << "# " << std::endl; for (OptionSection::OptionsType::iterator i=o.getOptions().begin(); i!=o.getOptions().end(); i++) if (outputConfig[i->getName()] == Header) std::cout << "# " << i->getName() << " = " << i->getValue() << std::endl; } void printHeaderAll () { if (!globalFirst) std::cout << std::endl; else globalFirst = false; std::cout << "# program version: " << GIT_PROGRAM_VERSION << std::endl << "# date: " << getTime() << std::endl << "# " << std::endl; for (OptionSection::OptionsType::iterator i=o.getOptions().begin(); i!=o.getOptions().end(); i++) if (outputConfig[i->getName()] != None) std::cout << "# " << i->getName() << " = " << i->getValue() << std::endl; } void setOutputMode (std::string param, OutputMode mode) { outputConfig[param] = mode; } std::string getTime () const { std::time_t time; std::time(&time); //std::tm* gmTime = std::gmtime(&time); std::tm* localTime = std::localtime(&time); std::stringstream s; s << Helpers::trim(std::asctime(localTime)); // TODO: find out time difference to UTC and append it as "-0600" //std::cerr << "--> " << std::mktime(localTime) << std::endl; //std::cerr << "--> " << std::mktime(gmTime) << std::endl; //std::time_t diff = std::mktime(localTime) - std::mktime(gmTime); //if (diff<0) //{ // diff *= -1; // std::tm* diffTm = std::gmtime(&diff); // s << " -" << diffTm->tm_hour; //} //else //{ // std::tm* diffTm = std::gmtime(&diff); // s << " +" << diffTm->tm_hour; //} return s.str(); } private: OptionSection o; System s; std::vector<std::vector<double> > E; std::vector<double> P; std::vector<double> N; bool needHeader, globalFirst; typedef std::map<std::string, OutputMode> OutputMap; OutputMap outputConfig; std::vector<std::string> changed; }; bool comparePair (const std::pair<std::string, size_t>& p1, const std::pair<std::string, size_t>& p2) { return p1.second < p2.second; } template<class Measurement> void runMeasurement (Measurement& M, CommandLineOptions& opts, const std::vector<std::pair<std::string, size_t> >& params, size_t pos) { const std::string pName = params[pos].first; if (pos+1 == params.size() && params[pos].second > 1) M.setOutputMode(pName, Line); std::vector<double> v = opts[pName]; for (size_t i=0; i<v.size(); i++) { M.setParam(pName, v[i]); if (pos+1<params.size()) runMeasurement(M, opts, params, pos+1); else M.measure(); } } template<class System> void run (CommandLineOptions& opts) { const char* pnamesv[] = {"t","td","ti","V0","mu","Vext","Pext","a","b","beta"}; size_t pnamesc = 10; std::vector<std::pair<std::string, size_t> > params; for (size_t i=0; i<pnamesc; i++) { std::pair<std::string, size_t> p; p.first = pnamesv[i]; std::vector<double> v = opts[pnamesv[i]]; p.second = v.size(); params.push_back(p); } std::sort(params.begin(), params.end(), comparePair); OptionSection cOpts(opts); cOpts["t"] = 1; cOpts["td"] = 0; cOpts["ti"] = 0; cOpts["V0"] = 0; cOpts["mu"] = 0; cOpts["Vext"] = 0; cOpts["Pext"] = 0; cOpts["a"] = 1; cOpts["b"] = 1.75; cOpts["beta"] = 1; Measurement<System> M(cOpts); runMeasurement(M, opts, params, 0); } int main(int argc, const char** argv) { CommandLineOptions opts = setupCLOptions(); try { opts.parse(argc, argv); } catch (CommandLineOptionsException e) { std::cerr << e.what() << std::endl << std::endl; printUsage(opts); std::exit(EXIT_FAILURE); } if (opts["help"].isSet()) { printUsage(opts); std::exit(EXIT_SUCCESS); } if (opts["version"].isSet()) { std::cout << GIT_PROGRAM_VERSION << std::endl; std::exit(EXIT_SUCCESS); } try { if (opts["model"] == "bond") run<DQcaBondPlain>(opts); else if (opts["model"] == "fixedcharge2" || opts["model"] == "fixed2") run<DQcaFixedCharge2Plain>(opts); else if (opts["model"] == "fixedcharge6" || opts["model"] == "fixed6") run<DQcaFixedCharge6Plain>(opts); else if (opts["model"] == "grandcanonical" || opts["model"] == "grand") run<DQcaGrandCanonicalPlain>(opts); else if (opts["model"] == "bondDP") run<DQcaBondDeadPlaquet>(opts); else if (opts["model"] == "fixedcharge2DP" || opts["model"] == "fixed2DP") run<DQcaFixedCharge2DeadPlaquet>(opts); else if (opts["model"] == "fixedcharge6DP" || opts["model"] == "fixed6DP") run<DQcaFixedCharge6DeadPlaquet>(opts); else if (opts["model"] == "grandcanonical2DP" || opts["model"] == "grand2DP") run<DQcaGrandCanonical2DeadPlaquet>(opts); else if (opts["model"] == "grandcanonical6DP" || opts["model"] == "grand6DP") run<DQcaGrandCanonical6DeadPlaquet>(opts); else { printUsage(opts); std::cerr << std::endl << "Please specify a model." << std::endl; std::exit(EXIT_FAILURE); } } catch (ConversionException e) { std::cerr << "One or more of the specified command line arguments are " << "of the wrong type." << std::endl; std::cerr << "ConversionException: " << e.what() << std::endl; std::exit(EXIT_FAILURE); } return EXIT_SUCCESS; } <commit_msg>Printed date now includes timezone offset.<commit_after>#include "qca.hpp" #include "utilities.hpp" #include <map> #include "version.hpp" #include <ctime> /* * TODO * ---- * * * P-P for three plaquets (bond system) * * P-P with dead cell (bond and qf) * * energies with dead cell? -- shouldn't make much difference * * grand canonical * * number of electrons per cell for different a and b * * number of electrons, considering Vext or dead cell * * P-P * * compare energy, P-P for bond, qf, gc * * * * Output for the following command does not look correct to me: * ./runQca -m bondDP -p 1 -P 0 -Pext 0,1,2,3 -a 1,2 -E */ class EpsilonLess { public: EpsilonLess (double e_ = 1E-10) : e(e_) {} bool operator() (double a, double b) { return b-a > e; } private: double e; }; CommandLineOptions setupCLOptions () { CommandLineOptions o; o.add("help", "h", "Print this help message.") .add("version", "Print program version.") .add("model", "m", "Which QCA model to use. Options are: bond, bondDP, fixed2, fixed6, fixed2DP, fixed6DP, grand, grand2DP, grand6DP.") .add("", "p", "Number of plaquets.") .add("", "t", "Hopping parameter.") .add("", "td", "Diagonal hopping parameter.") .add("", "ti", "Inter-plaquet hopping parameter.") .add("", "V0", "On-site coulomb repulsion (Hubbard U).") .add("", "mu", "Chemical potential.") .add("", "Vext", "External potential.") .add("", "Pext", "External, 'driving' polarisation of a 'dead plaquet' to the left of the linear chain system.") .add("", "a", "Intra-plaquet spacing.") .add("", "b", "Inter-plaquet spacing.") .add("", "beta", "Inverse temperature.") .add("energy-spectrum", "E", "Calculate the energy spectrum.") .add("polarisation", "P", "Calculate the polarisation for the specified plaquet(s).") .add("particle-number", "N", "Calculate the particle number for the specified plaquet(s)."); o["p"].setDefault(1); o["t"].setDefault(1); o["td"].setDefault(0); o["ti"].setDefault(0); o["V0"].setDefault(0); o["mu"].setDefault(0); o["Vext"].setDefault(0); o["Pext"].setDefault(0); o["a"].setDefault(1); o["b"].setDefault(1.75); o["beta"].setDefault(1); return o; } void printUsage (CommandLineOptions& o) { std::cerr << "Usage: " << std::endl; std::cerr << o.usage(); } enum OutputMode {Header, Line, None}; template<class System> class Measurement { public: Measurement (OptionSection o_) : o(o_), s(o_), needHeader(true), globalFirst(true) { for (OptionSection::OptionsType::iterator i=o.getOptions().begin(); i!=o.getOptions().end(); i++) outputConfig[i->getName()] = Header; outputConfig["energy-spectrum"] = None; outputConfig["polarisation"] = None; outputConfig["particle-number"] = None; outputConfig["help"] = None; outputConfig["version"] = None; } void setParam (const std::string& param, const OptionValue& value) { o[param] = value; if (outputConfig[param] == Header) needHeader = true; } void measure (const std::string& param, const OptionValue& value) { setParam(param, value); measure(); } void measure () { s.setParameters(o); s.update(); if (o["energy-spectrum"].isSet()) measureEnergies(); if (o["polarisation"].isSet()) measurePolarisation(); if (o["particle-number"].isSet()) measureParticleNumber(); store(); } void measureEnergies () { E.resize(0); typedef std::map<double, int, EpsilonLess> myMap; typedef myMap::const_iterator mapIt; myMap evs; for (int i=0; i<s.energies().size(); i++) evs[s.energies()(i)]++; for (mapIt i=evs.begin(); i!=evs.end(); i++) { std::vector<double> v(3); v[0] = i->first; v[1] = i->first - s.Emin(); v[2] = i->second; E.push_back(v); } } void measurePolarisation () { P.resize(0); std::vector<size_t> ps = o["polarisation"]; for (size_t i=0; i<ps.size(); i++) { if (ps[i] >= s.N_p) { std::cerr << std::endl << "Polarisation: There is no plaquet " << ps[i] << " in this system." << std::endl; std::exit(EXIT_FAILURE); } P.push_back(s.measure(o["beta"], s.P(ps[i]))); } } void measureParticleNumber () { N.resize(0); std::vector<size_t> ns = o["particle-number"]; for (size_t i=0; i<ns.size(); i++) { if (ns[i] >= s.N_p) { std::cerr << std::endl << "Particle number: There is no plaquet " << ns[i] << " in this system." << std::endl; std::exit(EXIT_FAILURE); } N.push_back(s.measure(o["beta"], s.N(ns[i]))); } } void store () { // always print energy spectrum as a separate block if (o["energy-spectrum"].isSet()) { printHeaderAll(); std::cout << "# " << std::endl << "# E\tE-Emin\tDegeneracy" << std::endl; for (size_t i=0; i<E.size(); i++) std::cout << E[i][0] << "\t" << E[i][1] << "\t" << E[i][2] << std::endl; std::cout << std::endl; } if (o["polarisation"].isSet() || o["particle-number"].isSet()) { if (needHeader) { printHeader(); std::cout << "# " << std::endl << "# "; bool first = true; for (typename OutputMap::const_iterator i=outputConfig.begin(); i!=outputConfig.end(); i++) if (i->second == Line) { if (!first) std::cout << "\t"; else first = false; std::cout << i->first; } if (o["polarisation"].isSet()) { std::vector<size_t> ps = o["polarisation"]; for (size_t i=0; i<ps.size(); i++) { if (!first) std::cout << "\t"; else first = false; std::cout << "P" << ps[i]; } } if (o["particle-number"].isSet()) { std::vector<size_t> ns = o["particle-number"]; for (size_t i=0; i<ns.size(); i++) { if (!first) std::cout << "\t"; else first = false; std::cout << "N" << ns[i]; } } std::cout << std::endl; needHeader = false; } bool first = true; for (typename OutputMap::const_iterator i=outputConfig.begin(); i!=outputConfig.end(); i++) if (i->second == Line) { if (!first) std::cout << "\t"; else first = false; std::cout << o[i->first]; } if (o["polarisation"].isSet()) for (size_t j=0; j<P.size(); j++) { if (!first) std::cout << "\t"; else first = false; std::cout << P[j]; } if (o["particle-number"].isSet()) for (size_t j=0; j<N.size(); j++) { if (!first) std::cout << "\t"; else first = false; std::cout << N[j]; } std::cout << std::endl; } } void printHeader () { if (!globalFirst) std::cout << std::endl; else globalFirst = false; std::cout << "# program version: " << GIT_PROGRAM_VERSION << std::endl << "# date: " << getDate() << std::endl << "# " << std::endl; for (OptionSection::OptionsType::iterator i=o.getOptions().begin(); i!=o.getOptions().end(); i++) if (outputConfig[i->getName()] == Header) std::cout << "# " << i->getName() << " = " << i->getValue() << std::endl; } void printHeaderAll () { if (!globalFirst) std::cout << std::endl; else globalFirst = false; std::cout << "# program version: " << GIT_PROGRAM_VERSION << std::endl << "# date: " << getDate() << std::endl << "# " << std::endl; for (OptionSection::OptionsType::iterator i=o.getOptions().begin(); i!=o.getOptions().end(); i++) if (outputConfig[i->getName()] != None) std::cout << "# " << i->getName() << " = " << i->getValue() << std::endl; } void setOutputMode (std::string param, OutputMode mode) { outputConfig[param] = mode; } std::string getDate () const { time_t t; tm localTime; char cstr[100]; time(&t); tzset(); localtime_r(&t, &localTime); strftime(cstr, 100, "%a %b %d %T %Y %z", &localTime); return cstr; } private: OptionSection o; System s; std::vector<std::vector<double> > E; std::vector<double> P; std::vector<double> N; bool needHeader, globalFirst; typedef std::map<std::string, OutputMode> OutputMap; OutputMap outputConfig; std::vector<std::string> changed; }; bool comparePair (const std::pair<std::string, size_t>& p1, const std::pair<std::string, size_t>& p2) { return p1.second < p2.second; } template<class Measurement> void runMeasurement (Measurement& M, CommandLineOptions& opts, const std::vector<std::pair<std::string, size_t> >& params, size_t pos) { const std::string pName = params[pos].first; if (pos+1 == params.size() && params[pos].second > 1) M.setOutputMode(pName, Line); std::vector<double> v = opts[pName]; for (size_t i=0; i<v.size(); i++) { M.setParam(pName, v[i]); if (pos+1<params.size()) runMeasurement(M, opts, params, pos+1); else M.measure(); } } template<class System> void run (CommandLineOptions& opts) { const char* pnamesv[] = {"t","td","ti","V0","mu","Vext","Pext","a","b","beta"}; size_t pnamesc = 10; std::vector<std::pair<std::string, size_t> > params; for (size_t i=0; i<pnamesc; i++) { std::pair<std::string, size_t> p; p.first = pnamesv[i]; std::vector<double> v = opts[pnamesv[i]]; p.second = v.size(); params.push_back(p); } std::sort(params.begin(), params.end(), comparePair); OptionSection cOpts(opts); cOpts["t"] = 1; cOpts["td"] = 0; cOpts["ti"] = 0; cOpts["V0"] = 0; cOpts["mu"] = 0; cOpts["Vext"] = 0; cOpts["Pext"] = 0; cOpts["a"] = 1; cOpts["b"] = 1.75; cOpts["beta"] = 1; Measurement<System> M(cOpts); runMeasurement(M, opts, params, 0); } int main(int argc, const char** argv) { CommandLineOptions opts = setupCLOptions(); try { opts.parse(argc, argv); } catch (CommandLineOptionsException e) { std::cerr << e.what() << std::endl << std::endl; printUsage(opts); std::exit(EXIT_FAILURE); } if (opts["help"].isSet()) { printUsage(opts); std::exit(EXIT_SUCCESS); } if (opts["version"].isSet()) { std::cout << GIT_PROGRAM_VERSION << std::endl; std::exit(EXIT_SUCCESS); } try { if (opts["model"] == "bond") run<DQcaBondPlain>(opts); else if (opts["model"] == "fixedcharge2" || opts["model"] == "fixed2") run<DQcaFixedCharge2Plain>(opts); else if (opts["model"] == "fixedcharge6" || opts["model"] == "fixed6") run<DQcaFixedCharge6Plain>(opts); else if (opts["model"] == "grandcanonical" || opts["model"] == "grand") run<DQcaGrandCanonicalPlain>(opts); else if (opts["model"] == "bondDP") run<DQcaBondDeadPlaquet>(opts); else if (opts["model"] == "fixedcharge2DP" || opts["model"] == "fixed2DP") run<DQcaFixedCharge2DeadPlaquet>(opts); else if (opts["model"] == "fixedcharge6DP" || opts["model"] == "fixed6DP") run<DQcaFixedCharge6DeadPlaquet>(opts); else if (opts["model"] == "grandcanonical2DP" || opts["model"] == "grand2DP") run<DQcaGrandCanonical2DeadPlaquet>(opts); else if (opts["model"] == "grandcanonical6DP" || opts["model"] == "grand6DP") run<DQcaGrandCanonical6DeadPlaquet>(opts); else { printUsage(opts); std::cerr << std::endl << "Please specify a model." << std::endl; std::exit(EXIT_FAILURE); } } catch (ConversionException e) { std::cerr << "One or more of the specified command line arguments are " << "of the wrong type." << std::endl; std::cerr << "ConversionException: " << e.what() << std::endl; std::exit(EXIT_FAILURE); } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#ifndef __PROCESS_TIMEOUT_HPP__ #define __PROCESS_TIMEOUT_HPP__ #include <process/process.hpp> #include <process/time.hpp> #include <stout/duration.hpp> namespace process { class Timeout { public: Timeout() : timeout(Clock::now()) {} explicit Timeout(const Time& time) : timeout(time) {} Timeout(const Timeout& that) : timeout(that.timeout) {} // Constructs a Timeout instance from a Time that is the 'duration' // from now. static Timeout in(const Duration& duration) { return Timeout(Clock::now() + duration); } Timeout& operator = (const Timeout& that) { if (this != &that) { timeout = that.timeout; } return *this; } Timeout& operator = (const Duration& duration) { timeout = Clock::now() + duration; return *this; } bool operator == (const Timeout& that) const { return timeout == that.timeout; } bool operator < (const Timeout& that) const { return timeout < that.timeout; } bool operator <= (const Timeout& that) const { return timeout <= that.timeout; } // Returns the value of the timeout as a Time object. Time time() const { return timeout; } // Returns the amount of time remaining. Duration remaining() const { Duration remaining = timeout - Clock::now(); return remaining > Duration::zero() ? remaining : Duration::zero(); } // Returns true if the timeout expired. bool expired() const { return timeout <= Clock::now(); } private: Time timeout; }; } // namespace process { #endif // __PROCESS_TIMEOUT_HPP__ <commit_msg>Reduced over-include in libprocess Socket.<commit_after>#ifndef __PROCESS_TIMEOUT_HPP__ #define __PROCESS_TIMEOUT_HPP__ #include <process/clock.hpp> #include <process/time.hpp> #include <stout/duration.hpp> namespace process { class Timeout { public: Timeout() : timeout(Clock::now()) {} explicit Timeout(const Time& time) : timeout(time) {} Timeout(const Timeout& that) : timeout(that.timeout) {} // Constructs a Timeout instance from a Time that is the 'duration' // from now. static Timeout in(const Duration& duration) { return Timeout(Clock::now() + duration); } Timeout& operator = (const Timeout& that) { if (this != &that) { timeout = that.timeout; } return *this; } Timeout& operator = (const Duration& duration) { timeout = Clock::now() + duration; return *this; } bool operator == (const Timeout& that) const { return timeout == that.timeout; } bool operator < (const Timeout& that) const { return timeout < that.timeout; } bool operator <= (const Timeout& that) const { return timeout <= that.timeout; } // Returns the value of the timeout as a Time object. Time time() const { return timeout; } // Returns the amount of time remaining. Duration remaining() const { Duration remaining = timeout - Clock::now(); return remaining > Duration::zero() ? remaining : Duration::zero(); } // Returns true if the timeout expired. bool expired() const { return timeout <= Clock::now(); } private: Time timeout; }; } // namespace process { #endif // __PROCESS_TIMEOUT_HPP__ <|endoftext|>
<commit_before>// 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 "chrome/browser/android/voice_search_tab_helper.h" #include "base/command_line.h" #include "components/google/core/browser/google_util.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/web_contents.h" #include "content/public/common/content_switches.h" #include "content/public/common/web_preferences.h" #include "jni/VoiceSearchTabHelper_jni.h" using content::WebContents; // Register native methods bool RegisterVoiceSearchTabHelper(JNIEnv* env) { return RegisterNativesImpl(env); } static void UpdateAutoplayStatus(JNIEnv* env, jobject obj, jobject j_web_contents) { // In the case where media autoplay has been disabled by default (e.g. in // performance media tests) do not update it based on navigation changes. const CommandLine& command_line = *CommandLine::ForCurrentProcess(); if (command_line.HasSwitch( switches::kDisableGestureRequirementForMediaPlayback)) return; WebContents* web_contents = WebContents::FromJavaWebContents(j_web_contents); content::RenderViewHost* host = web_contents->GetRenderViewHost(); content::WebPreferences prefs = host->GetWebkitPreferences(); bool gesture_required = !google_util::IsGoogleSearchUrl(web_contents->GetLastCommittedURL()); if (gesture_required != prefs.user_gesture_required_for_media_playback) { // TODO(chrishtr): this is wrong. user_gesture_required_for_media_playback // will be reset the next time a preference changes. prefs.user_gesture_required_for_media_playback = gesture_required; host->UpdateWebkitPreferences(prefs); } } <commit_msg>Revert of Fix early out in UpdateAutoplayStatus. (https://codereview.chromium.org/405253004/)<commit_after>// 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 "chrome/browser/android/voice_search_tab_helper.h" #include "components/google/core/browser/google_util.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/web_contents.h" #include "content/public/common/web_preferences.h" #include "jni/VoiceSearchTabHelper_jni.h" using content::WebContents; // Register native methods bool RegisterVoiceSearchTabHelper(JNIEnv* env) { return RegisterNativesImpl(env); } static void UpdateAutoplayStatus(JNIEnv* env, jobject obj, jobject j_web_contents) { WebContents* web_contents = WebContents::FromJavaWebContents(j_web_contents); content::RenderViewHost* host = web_contents->GetRenderViewHost(); content::WebPreferences prefs = host->GetWebkitPreferences(); // In the case where media autoplay has been enabled by default (e.g. in // performance media tests) do not update it based on navigation changes. // // Note that GetWekitPreferences() is 'stateless'. It returns the default // webkit preferences configuration from command line switches. if (!prefs.user_gesture_required_for_media_playback) return; // TODO(chrishtr): this is wrong. user_gesture_required_for_media_playback // will be reset the next time a preference changes. prefs.user_gesture_required_for_media_playback = !google_util::IsGoogleSearchUrl(web_contents->GetLastCommittedURL()); host->UpdateWebkitPreferences(prefs); } <|endoftext|>
<commit_before>// Copyright (c) 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 "base/command_line.h" #include "base/path_service.h" #include "chrome/browser/chrome_browser_main.h" #include "chrome/browser/chrome_browser_main_extra_parts.h" #include "chrome/browser/chrome_content_browser_client.h" #include "chrome/browser/chromeos/cros/cros_in_process_browser_test.h" #include "chrome/browser/chromeos/login/existing_user_controller.h" #include "chrome/browser/chromeos/login/webui_login_display.h" #include "chrome/browser/chromeos/login/wizard_controller.h" #include "chrome/browser/ui/browser.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/interactive_test_utils.h" #include "chrome/test/base/ui_test_utils.h" #include "chromeos/chromeos_switches.h" #include "content/public/browser/notification_observer.h" #include "content/public/browser/notification_registrar.h" #include "content/public/browser/notification_service.h" #include "content/public/test/test_utils.h" #include "google_apis/gaia/gaia_switches.h" #include "net/test/embedded_test_server/embedded_test_server.h" #include "net/test/embedded_test_server/http_request.h" #include "net/test/embedded_test_server/http_response.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using namespace net::test_server; namespace { // Used to add an observer to NotificationService after it's created. class TestBrowserMainExtraParts : public ChromeBrowserMainExtraParts, public content::NotificationObserver { public: TestBrowserMainExtraParts() : webui_visible_(false), browsing_data_removed_(false), signin_screen_shown_(false) {} virtual ~TestBrowserMainExtraParts() {} // ChromeBrowserMainExtraParts implementation. virtual void PreEarlyInitialization() OVERRIDE { registrar_.Add(this, chrome::NOTIFICATION_LOGIN_WEBUI_VISIBLE, content::NotificationService::AllSources()); registrar_.Add(this, chrome::NOTIFICATION_SESSION_STARTED, content::NotificationService::AllSources()); registrar_.Add(this, chrome::NOTIFICATION_BROWSING_DATA_REMOVED, content::NotificationService::AllSources()); } void set_quit_task(const base::Closure& quit_task) { quit_task_ = quit_task; } private: // Overridden from content::NotificationObserver: virtual void Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) OVERRIDE { if (type == chrome::NOTIFICATION_LOGIN_WEBUI_VISIBLE) { LOG(INFO) << "NOTIFICATION_LOGIN_WEBUI_VISIBLE"; webui_visible_ = true; if (browsing_data_removed_ && !signin_screen_shown_) { signin_screen_shown_ = true; ShowSigninScreen(); } } else if (type == chrome::NOTIFICATION_BROWSING_DATA_REMOVED) { LOG(INFO) << "chrome::NOTIFICATION_BROWSING_DATA_REMOVED"; browsing_data_removed_ = true; if (webui_visible_ && !signin_screen_shown_) { signin_screen_shown_ = true; ShowSigninScreen(); } } else if (type == chrome::NOTIFICATION_SESSION_STARTED) { LOG(INFO) << "chrome::NOTIFICATION_SESSION_STARTED"; quit_task_.Run(); } else { NOTREACHED(); } } void ShowSigninScreen() { chromeos::ExistingUserController* controller = chromeos::ExistingUserController::current_controller(); CHECK(controller); chromeos::WebUILoginDisplay* webui_login_display = static_cast<chromeos::WebUILoginDisplay*>( controller->login_display()); CHECK(webui_login_display); webui_login_display->ShowSigninScreenForCreds("username", "password"); // TODO(glotov): mock GAIA server (test_server_) should support // username/password configuration. } bool webui_visible_, browsing_data_removed_, signin_screen_shown_; content::NotificationRegistrar registrar_; base::Closure quit_task_; GURL gaia_url_; DISALLOW_COPY_AND_ASSIGN(TestBrowserMainExtraParts); }; class TestContentBrowserClient : public chrome::ChromeContentBrowserClient { public: TestContentBrowserClient() {} virtual ~TestContentBrowserClient() {} virtual content::BrowserMainParts* CreateBrowserMainParts( const content::MainFunctionParams& parameters) OVERRIDE { ChromeBrowserMainParts* main_parts = static_cast<ChromeBrowserMainParts*>( ChromeContentBrowserClient::CreateBrowserMainParts(parameters)); browser_main_extra_parts_ = new TestBrowserMainExtraParts(); main_parts->AddParts(browser_main_extra_parts_); return main_parts; } TestBrowserMainExtraParts* browser_main_extra_parts_; private: DISALLOW_COPY_AND_ASSIGN(TestContentBrowserClient); }; const base::FilePath kServiceLogin("chromeos/service_login.html"); class OobeTest : public chromeos::CrosInProcessBrowserTest { protected: virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE { command_line->AppendSwitch(chromeos::switches::kLoginManager); command_line->AppendSwitch(chromeos::switches::kForceLoginManagerInTests); command_line->AppendSwitch( chromeos::switches::kDisableChromeCaptivePortalDetector); command_line->AppendSwitchASCII(chromeos::switches::kLoginProfile, "user"); command_line->AppendSwitchASCII( chromeos::switches::kAuthExtensionPath, "gaia_auth"); } virtual void SetUpInProcessBrowserTestFixture() OVERRIDE { content_browser_client_.reset(new TestContentBrowserClient()); original_content_browser_client_ = content::SetBrowserClientForTesting( content_browser_client_.get()); base::FilePath test_data_dir; PathService::Get(chrome::DIR_TEST_DATA, &test_data_dir); CHECK(file_util::ReadFileToString(test_data_dir.Append(kServiceLogin), &service_login_response_)); } virtual void SetUpOnMainThread() OVERRIDE { test_server_ = new EmbeddedTestServer( content::BrowserThread::GetMessageLoopProxyForThread( content::BrowserThread::IO)); CHECK(test_server_->InitializeAndWaitUntilReady()); test_server_->RegisterRequestHandler( base::Bind(&OobeTest::HandleRequest, base::Unretained(this))); LOG(INFO) << "Set up http server at " << test_server_->base_url(); const GURL gaia_url("http://localhost:" + test_server_->base_url().port()); CommandLine::ForCurrentProcess()->AppendSwitchASCII( ::switches::kGaiaUrl, gaia_url.spec()); } virtual void CleanUpOnMainThread() OVERRIDE { LOG(INFO) << "Stopping the http server."; EXPECT_TRUE(test_server_->ShutdownAndWaitUntilComplete()); delete test_server_; // Destructor wants UI thread. } scoped_ptr<HttpResponse> HandleRequest(const HttpRequest& request) { GURL url = test_server_->GetURL(request.relative_url); LOG(INFO) << "Http request: " << url.spec(); scoped_ptr<BasicHttpResponse> http_response(new BasicHttpResponse()); if (url.path() == "/ServiceLogin") { http_response->set_code(net::test_server::SUCCESS); http_response->set_content(service_login_response_); http_response->set_content_type("text/html"); } else if (url.path() == "/ServiceLoginAuth") { LOG(INFO) << "Params: " << request.content; static const char kContinueParam[] = "continue="; int continue_arg_begin = request.content.find(kContinueParam) + arraysize(kContinueParam) - 1; int continue_arg_end = request.content.find("&", continue_arg_begin); const std::string continue_url = request.content.substr( continue_arg_begin, continue_arg_end - continue_arg_begin); http_response->set_code(net::test_server::SUCCESS); const std::string redirect_js = "document.location.href = unescape('" + continue_url + "');"; http_response->set_content( "<HTML><HEAD><SCRIPT>\n" + redirect_js + "\n</SCRIPT></HEAD></HTML>"); http_response->set_content_type("text/html"); } else { NOTREACHED() << url.path(); } return http_response.PassAs<HttpResponse>(); } scoped_ptr<TestContentBrowserClient> content_browser_client_; content::ContentBrowserClient* original_content_browser_client_; std::string service_login_response_; EmbeddedTestServer* test_server_; // cant use scoped_ptr because destructor // needs UI thread. }; // Test is flaky - http://crbug.com/242587 IN_PROC_BROWSER_TEST_F(OobeTest, DISABLED_NewUser) { chromeos::WizardController::SkipPostLoginScreensForTesting(); chromeos::WizardController* wizard_controller = chromeos::WizardController::default_controller(); CHECK(wizard_controller); wizard_controller->SkipToLoginForTesting(); scoped_refptr<content::MessageLoopRunner> runner = new content::MessageLoopRunner; content_browser_client_->browser_main_extra_parts_->set_quit_task( runner->QuitClosure()); runner->Run(); } } // namespace <commit_msg>Removed OobeTest.* flakiness flag.<commit_after>// Copyright (c) 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 "base/command_line.h" #include "base/path_service.h" #include "chrome/browser/chrome_browser_main.h" #include "chrome/browser/chrome_browser_main_extra_parts.h" #include "chrome/browser/chrome_content_browser_client.h" #include "chrome/browser/chromeos/cros/cros_in_process_browser_test.h" #include "chrome/browser/chromeos/login/existing_user_controller.h" #include "chrome/browser/chromeos/login/webui_login_display.h" #include "chrome/browser/chromeos/login/wizard_controller.h" #include "chrome/browser/ui/browser.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/interactive_test_utils.h" #include "chrome/test/base/ui_test_utils.h" #include "chromeos/chromeos_switches.h" #include "content/public/browser/notification_observer.h" #include "content/public/browser/notification_registrar.h" #include "content/public/browser/notification_service.h" #include "content/public/test/test_utils.h" #include "google_apis/gaia/gaia_switches.h" #include "net/test/embedded_test_server/embedded_test_server.h" #include "net/test/embedded_test_server/http_request.h" #include "net/test/embedded_test_server/http_response.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using namespace net::test_server; namespace { // Used to add an observer to NotificationService after it's created. class TestBrowserMainExtraParts : public ChromeBrowserMainExtraParts, public content::NotificationObserver { public: TestBrowserMainExtraParts() : webui_visible_(false), browsing_data_removed_(false), signin_screen_shown_(false) {} virtual ~TestBrowserMainExtraParts() {} // ChromeBrowserMainExtraParts implementation. virtual void PreEarlyInitialization() OVERRIDE { registrar_.Add(this, chrome::NOTIFICATION_LOGIN_WEBUI_VISIBLE, content::NotificationService::AllSources()); registrar_.Add(this, chrome::NOTIFICATION_SESSION_STARTED, content::NotificationService::AllSources()); registrar_.Add(this, chrome::NOTIFICATION_BROWSING_DATA_REMOVED, content::NotificationService::AllSources()); } void set_quit_task(const base::Closure& quit_task) { quit_task_ = quit_task; } private: // Overridden from content::NotificationObserver: virtual void Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) OVERRIDE { if (type == chrome::NOTIFICATION_LOGIN_WEBUI_VISIBLE) { LOG(INFO) << "NOTIFICATION_LOGIN_WEBUI_VISIBLE"; webui_visible_ = true; if (browsing_data_removed_ && !signin_screen_shown_) { signin_screen_shown_ = true; ShowSigninScreen(); } } else if (type == chrome::NOTIFICATION_BROWSING_DATA_REMOVED) { LOG(INFO) << "chrome::NOTIFICATION_BROWSING_DATA_REMOVED"; browsing_data_removed_ = true; if (webui_visible_ && !signin_screen_shown_) { signin_screen_shown_ = true; ShowSigninScreen(); } } else if (type == chrome::NOTIFICATION_SESSION_STARTED) { LOG(INFO) << "chrome::NOTIFICATION_SESSION_STARTED"; quit_task_.Run(); } else { NOTREACHED(); } } void ShowSigninScreen() { chromeos::ExistingUserController* controller = chromeos::ExistingUserController::current_controller(); CHECK(controller); chromeos::WebUILoginDisplay* webui_login_display = static_cast<chromeos::WebUILoginDisplay*>( controller->login_display()); CHECK(webui_login_display); webui_login_display->ShowSigninScreenForCreds("username", "password"); // TODO(glotov): mock GAIA server (test_server_) should support // username/password configuration. } bool webui_visible_, browsing_data_removed_, signin_screen_shown_; content::NotificationRegistrar registrar_; base::Closure quit_task_; GURL gaia_url_; DISALLOW_COPY_AND_ASSIGN(TestBrowserMainExtraParts); }; class TestContentBrowserClient : public chrome::ChromeContentBrowserClient { public: TestContentBrowserClient() {} virtual ~TestContentBrowserClient() {} virtual content::BrowserMainParts* CreateBrowserMainParts( const content::MainFunctionParams& parameters) OVERRIDE { ChromeBrowserMainParts* main_parts = static_cast<ChromeBrowserMainParts*>( ChromeContentBrowserClient::CreateBrowserMainParts(parameters)); browser_main_extra_parts_ = new TestBrowserMainExtraParts(); main_parts->AddParts(browser_main_extra_parts_); return main_parts; } TestBrowserMainExtraParts* browser_main_extra_parts_; private: DISALLOW_COPY_AND_ASSIGN(TestContentBrowserClient); }; const base::FilePath kServiceLogin("chromeos/service_login.html"); class OobeTest : public chromeos::CrosInProcessBrowserTest { protected: virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE { command_line->AppendSwitch(chromeos::switches::kLoginManager); command_line->AppendSwitch(chromeos::switches::kForceLoginManagerInTests); command_line->AppendSwitch( chromeos::switches::kDisableChromeCaptivePortalDetector); command_line->AppendSwitchASCII(chromeos::switches::kLoginProfile, "user"); command_line->AppendSwitchASCII( chromeos::switches::kAuthExtensionPath, "gaia_auth"); } virtual void SetUpInProcessBrowserTestFixture() OVERRIDE { content_browser_client_.reset(new TestContentBrowserClient()); original_content_browser_client_ = content::SetBrowserClientForTesting( content_browser_client_.get()); base::FilePath test_data_dir; PathService::Get(chrome::DIR_TEST_DATA, &test_data_dir); CHECK(file_util::ReadFileToString(test_data_dir.Append(kServiceLogin), &service_login_response_)); } virtual void SetUpOnMainThread() OVERRIDE { test_server_ = new EmbeddedTestServer( content::BrowserThread::GetMessageLoopProxyForThread( content::BrowserThread::IO)); CHECK(test_server_->InitializeAndWaitUntilReady()); test_server_->RegisterRequestHandler( base::Bind(&OobeTest::HandleRequest, base::Unretained(this))); LOG(INFO) << "Set up http server at " << test_server_->base_url(); const GURL gaia_url("http://localhost:" + test_server_->base_url().port()); CommandLine::ForCurrentProcess()->AppendSwitchASCII( ::switches::kGaiaUrl, gaia_url.spec()); } virtual void CleanUpOnMainThread() OVERRIDE { LOG(INFO) << "Stopping the http server."; EXPECT_TRUE(test_server_->ShutdownAndWaitUntilComplete()); delete test_server_; // Destructor wants UI thread. } scoped_ptr<HttpResponse> HandleRequest(const HttpRequest& request) { GURL url = test_server_->GetURL(request.relative_url); LOG(INFO) << "Http request: " << url.spec(); scoped_ptr<BasicHttpResponse> http_response(new BasicHttpResponse()); if (url.path() == "/ServiceLogin") { http_response->set_code(net::test_server::SUCCESS); http_response->set_content(service_login_response_); http_response->set_content_type("text/html"); } else if (url.path() == "/ServiceLoginAuth") { LOG(INFO) << "Params: " << request.content; static const char kContinueParam[] = "continue="; int continue_arg_begin = request.content.find(kContinueParam) + arraysize(kContinueParam) - 1; int continue_arg_end = request.content.find("&", continue_arg_begin); const std::string continue_url = request.content.substr( continue_arg_begin, continue_arg_end - continue_arg_begin); http_response->set_code(net::test_server::SUCCESS); const std::string redirect_js = "document.location.href = unescape('" + continue_url + "');"; http_response->set_content( "<HTML><HEAD><SCRIPT>\n" + redirect_js + "\n</SCRIPT></HEAD></HTML>"); http_response->set_content_type("text/html"); } else { NOTREACHED() << url.path(); } return http_response.PassAs<HttpResponse>(); } scoped_ptr<TestContentBrowserClient> content_browser_client_; content::ContentBrowserClient* original_content_browser_client_; std::string service_login_response_; EmbeddedTestServer* test_server_; // cant use scoped_ptr because destructor // needs UI thread. }; IN_PROC_BROWSER_TEST_F(OobeTest, NewUser) { chromeos::WizardController::SkipPostLoginScreensForTesting(); chromeos::WizardController* wizard_controller = chromeos::WizardController::default_controller(); CHECK(wizard_controller); wizard_controller->SkipToLoginForTesting(); scoped_refptr<content::MessageLoopRunner> runner = new content::MessageLoopRunner; content_browser_client_->browser_main_extra_parts_->set_quit_task( runner->QuitClosure()); runner->Run(); } } // namespace <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: TestExecutionTimer.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. =========================================================================*/ // This test uses the guts of TestDelaunay2D. I just attach a // vtkExecutionTimer to vtkDelaunay2D so that I can watch // something non-trivial. #include "vtkCellArray.h" #include "vtkDelaunay2D.h" #include "vtkExecutionTimer.h" #include "vtkPoints.h" #include "vtkPolyData.h" #include "vtkSmartPointer.h" #include <cstdlib> int TestExecutionTimer( int argc, char* argv[] ) { vtkPoints *newPts = vtkPoints::New(); newPts->InsertNextPoint( 1.5026018771810041, 1.5026019428618222, 0.0 ); newPts->InsertNextPoint( -1.5026020085426373, 1.5026018115001829, 0.0 ); newPts->InsertNextPoint( -1.5026018353814194, -1.5026019846614038, 0.0 ); newPts->InsertNextPoint( 1.5026019189805875, -1.5026019010622396, 0.0 ); newPts->InsertNextPoint( 5.2149123972752491, 5.2149126252263240, 0.0 ); newPts->InsertNextPoint( -5.2149128531773883, 5.2149121693241645, 0.0 ); newPts->InsertNextPoint( -5.2149122522061022, -5.2149127702954603, 0.0 ); newPts->InsertNextPoint( 5.2149125423443916, -5.2149124801571842, 0.0 ); newPts->InsertNextPoint( 8.9272229173694946, 8.9272233075908254, 0.0 ); newPts->InsertNextPoint( -8.9272236978121402, 8.9272225271481460, 0.0 ); newPts->InsertNextPoint( -8.9272226690307868, -8.9272235559295172, 0.0 ); newPts->InsertNextPoint( 8.9272231657081953, -8.9272230592521282, 0.0 ); newPts->InsertNextPoint( 12.639533437463740, 12.639533989955329, 0.0 ); newPts->InsertNextPoint( -12.639534542446890, 12.639532884972127, 0.0 ); newPts->InsertNextPoint( -12.639533085855469, -12.639534341563573, 0.0 ); newPts->InsertNextPoint( 12.639533789072001, -12.639533638347073, 0.0 ); vtkIdType inNumPts = newPts->GetNumberOfPoints(); vtkPolyData *pointCloud = vtkPolyData::New(); pointCloud->SetPoints(newPts); newPts->Delete(); vtkDelaunay2D *delaunay2D = vtkDelaunay2D::New(); delaunay2D->SetInputData( pointCloud ); pointCloud->Delete(); vtkSmartPointer<vtkExecutionTimer> timer = vtkSmartPointer<vtkExecutionTimer>::New(); timer->SetFilter(delaunay2D); delaunay2D->Update(); std::cout << "TestExecutionTimer: Filter under inspection (" << timer->GetFilter()->GetClassName() << ") execution time: " << std::fixed << std::setprecision(8) << timer->GetElapsedCPUTime() << " sec (CPU), " << timer->GetElapsedWallClockTime() << " sec (wall clock)\n"; // As long as the thing executes without crashing, the test is // successful. return EXIT_SUCCESS; } <commit_msg>Move #include "vtkExecutionTimer.h" to the top of the list<commit_after>/*========================================================================= Program: Visualization Toolkit Module: TestExecutionTimer.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. =========================================================================*/ // This test uses the guts of TestDelaunay2D. I just attach a // vtkExecutionTimer to vtkDelaunay2D so that I can watch // something non-trivial. #include "vtkExecutionTimer.h" #include "vtkCellArray.h" #include "vtkDelaunay2D.h" #include "vtkPoints.h" #include "vtkPolyData.h" #include "vtkSmartPointer.h" #include <cstdlib> int TestExecutionTimer( int argc, char* argv[] ) { vtkPoints *newPts = vtkPoints::New(); newPts->InsertNextPoint( 1.5026018771810041, 1.5026019428618222, 0.0 ); newPts->InsertNextPoint( -1.5026020085426373, 1.5026018115001829, 0.0 ); newPts->InsertNextPoint( -1.5026018353814194, -1.5026019846614038, 0.0 ); newPts->InsertNextPoint( 1.5026019189805875, -1.5026019010622396, 0.0 ); newPts->InsertNextPoint( 5.2149123972752491, 5.2149126252263240, 0.0 ); newPts->InsertNextPoint( -5.2149128531773883, 5.2149121693241645, 0.0 ); newPts->InsertNextPoint( -5.2149122522061022, -5.2149127702954603, 0.0 ); newPts->InsertNextPoint( 5.2149125423443916, -5.2149124801571842, 0.0 ); newPts->InsertNextPoint( 8.9272229173694946, 8.9272233075908254, 0.0 ); newPts->InsertNextPoint( -8.9272236978121402, 8.9272225271481460, 0.0 ); newPts->InsertNextPoint( -8.9272226690307868, -8.9272235559295172, 0.0 ); newPts->InsertNextPoint( 8.9272231657081953, -8.9272230592521282, 0.0 ); newPts->InsertNextPoint( 12.639533437463740, 12.639533989955329, 0.0 ); newPts->InsertNextPoint( -12.639534542446890, 12.639532884972127, 0.0 ); newPts->InsertNextPoint( -12.639533085855469, -12.639534341563573, 0.0 ); newPts->InsertNextPoint( 12.639533789072001, -12.639533638347073, 0.0 ); vtkIdType inNumPts = newPts->GetNumberOfPoints(); vtkPolyData *pointCloud = vtkPolyData::New(); pointCloud->SetPoints(newPts); newPts->Delete(); vtkDelaunay2D *delaunay2D = vtkDelaunay2D::New(); delaunay2D->SetInputData( pointCloud ); pointCloud->Delete(); vtkSmartPointer<vtkExecutionTimer> timer = vtkSmartPointer<vtkExecutionTimer>::New(); timer->SetFilter(delaunay2D); delaunay2D->Update(); std::cout << "TestExecutionTimer: Filter under inspection (" << timer->GetFilter()->GetClassName() << ") execution time: " << std::fixed << std::setprecision(8) << timer->GetElapsedCPUTime() << " sec (CPU), " << timer->GetElapsedWallClockTime() << " sec (wall clock)\n"; // As long as the thing executes without crashing, the test is // successful. return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/********************************************************************** Copyright (c) 2018 Advanced Micro Devices, Inc. All rights reserved. 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_load_utils.h" #include <SceneGraph/scene1.h> #include <scene_io.h> #include <image_io.h> #include <material_io.h> #include "XML/tinyxml2.h" using namespace Baikal; namespace { void LoadMaterials(std::string const& basepath, Scene1::Ptr scene) { // Check it we have material remapping std::ifstream in_materials(basepath + "materials.xml"); std::ifstream in_mapping(basepath + "mapping.xml"); if (!in_materials || !in_mapping) return; auto material_io = Baikal::MaterialIo::CreateMaterialIoXML(); auto mats = material_io->LoadMaterials(basepath + "materials.xml"); auto mapping = material_io->LoadMaterialMapping(basepath + "mapping.xml"); material_io->ReplaceSceneMaterials(*scene, *mats, mapping); } void LoadLights(std::string const& light_file, Scene1::Ptr scene) { if (light_file.empty()) { return; } tinyxml2::XMLDocument doc; doc.LoadFile(light_file.c_str()); auto root = doc.FirstChildElement("light_list"); if (!root) { throw std::runtime_error("Failed to open lights set file."); } tinyxml2::XMLElement* elem = root->FirstChildElement("light"); while (elem) { Light::Ptr light; std::string type = elem->Attribute("type"); if (type == "point") { light = PointLight::Create(); } else if (type == "spot") { auto spot = SpotLight::Create(); RadeonRays::float2 cone_shape(elem->FloatAttribute("csx"), elem->FloatAttribute("csy")); spot->SetConeShape(cone_shape); light = spot; } else if (type == "direct") { light = DirectionalLight::Create(); } else if (type == "ibl") { auto image_io = ImageIo::CreateImageIo(); auto tex = image_io->LoadImage(elem->Attribute("tex")); auto ibl = ImageBasedLight::Create(); ibl->SetTexture(tex); ibl->SetMultiplier(elem->FloatAttribute("mul")); light = ibl; } else { throw std::runtime_error(std::string("Unknown light type: ") + type); } RadeonRays::float3 rad; light->SetPosition({ elem->FloatAttribute("posx"), elem->FloatAttribute("posy"), elem->FloatAttribute("posz")}); light->SetDirection({ elem->FloatAttribute("dirx"), elem->FloatAttribute("diry"), elem->FloatAttribute("dirz")}); light->SetEmittedRadiance({ elem->FloatAttribute("radx"), elem->FloatAttribute("rady"), elem->FloatAttribute("radz")}); scene->AttachLight(light); elem = elem->NextSiblingElement("light"); } } } Scene1::Ptr LoadScene(Baikal::AppSettings const& settings) { #ifdef WIN32 std::string basepath = settings.path + "\\"; #else std::string basepath = settings.path + "/"; #endif std::string filename = basepath + settings.modelname; auto scene = Baikal::SceneIo::LoadScene(filename, basepath); if (scene == nullptr) { throw std::runtime_error("LoadScene(...): cannot create scene"); } LoadMaterials(basepath, scene); LoadLights(settings.light_file, scene); return scene; }<commit_msg>Code review<commit_after>/********************************************************************** Copyright (c) 2018 Advanced Micro Devices, Inc. All rights reserved. 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_load_utils.h" #include <SceneGraph/scene1.h> #include <scene_io.h> #include <image_io.h> #include <material_io.h> #include "XML/tinyxml2.h" using namespace Baikal; namespace { void LoadMaterials(std::string const& basepath, Scene1::Ptr scene) { // Check it we have material remapping std::ifstream in_materials(basepath + "materials.xml"); std::ifstream in_mapping(basepath + "mapping.xml"); if (!in_materials || !in_mapping) return; auto material_io = Baikal::MaterialIo::CreateMaterialIoXML(); auto mats = material_io->LoadMaterials(basepath + "materials.xml"); auto mapping = material_io->LoadMaterialMapping(basepath + "mapping.xml"); material_io->ReplaceSceneMaterials(*scene, *mats, mapping); } void LoadLights(std::string const& light_file, Scene1::Ptr scene) { if (light_file.empty()) { return; } tinyxml2::XMLDocument doc; doc.LoadFile(light_file.c_str()); auto root = doc.FirstChildElement("light_list"); if (!root) { throw std::runtime_error("Failed to open lights set file."); } auto elem = root->FirstChildElement("light"); while (elem) { Light::Ptr light; std::string type = elem->Attribute("type"); if (type == "point") { light = PointLight::Create(); } else if (type == "spot") { auto spot = SpotLight::Create(); RadeonRays::float2 cone_shape(elem->FloatAttribute("csx"), elem->FloatAttribute("csy")); spot->SetConeShape(cone_shape); light = spot; } else if (type == "direct") { light = DirectionalLight::Create(); } else if (type == "ibl") { auto image_io = ImageIo::CreateImageIo(); auto tex = image_io->LoadImage(elem->Attribute("tex")); auto ibl = ImageBasedLight::Create(); ibl->SetTexture(tex); ibl->SetMultiplier(elem->FloatAttribute("mul")); light = ibl; } else { throw std::runtime_error(std::string("Unknown light type: ") + type); } RadeonRays::float3 rad; light->SetPosition({ elem->FloatAttribute("posx"), elem->FloatAttribute("posy"), elem->FloatAttribute("posz")}); light->SetDirection({ elem->FloatAttribute("dirx"), elem->FloatAttribute("diry"), elem->FloatAttribute("dirz")}); light->SetEmittedRadiance({ elem->FloatAttribute("radx"), elem->FloatAttribute("rady"), elem->FloatAttribute("radz")}); scene->AttachLight(light); elem = elem->NextSiblingElement("light"); } } } Scene1::Ptr LoadScene(Baikal::AppSettings const& settings) { #ifdef WIN32 std::string basepath = settings.path + "\\"; #else std::string basepath = settings.path + "/"; #endif std::string filename = basepath + settings.modelname; auto scene = Baikal::SceneIo::LoadScene(filename, basepath); if (scene == nullptr) { throw std::runtime_error("LoadScene(...): cannot create scene"); } LoadMaterials(basepath, scene); LoadLights(settings.light_file, scene); return scene; }<|endoftext|>
<commit_before>/* This file is part of Strigi Desktop Search * * Copyright (C) 2007 Jos van den Oever <jos@vandenoever.info> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "diranalyzer.h" #include "indexwriter.h" #include "indexmanager.h" #include "indexreader.h" #include "filelister.h" #include "analysisresult.h" #include "strigi_thread.h" #include "fileinputstream.h" #include <map> #include <iostream> #include <sys/stat.h> using namespace Strigi; using namespace std; class DirAnalyzer::Private { public: FileLister lister; IndexManager& manager; AnalyzerConfiguration& config; StreamAnalyzer analyzer; map<string, time_t> dbfiles; STRIGI_MUTEX_DEFINE(updateMutex); AnalysisCaller* caller; Private(IndexManager& m, AnalyzerConfiguration& c) :lister(&c), manager(m), config(c), analyzer(c) { STRIGI_MUTEX_INIT(&updateMutex); analyzer.setIndexWriter(*manager.indexWriter()); } ~Private() { STRIGI_MUTEX_DESTROY(&updateMutex); } int analyzeDir(const string& dir, int nthreads, AnalysisCaller* caller, const string& lastToSkip); int updateDirs(const vector<string>& dir, int nthreads, AnalysisCaller* caller); void analyze(StreamAnalyzer*); void update(StreamAnalyzer*); }; struct DA { StreamAnalyzer* streamanalyzer; DirAnalyzer::Private* diranalyzer; }; void* analyzeInThread(void* d) { DA* a = static_cast<DA*>(d); a->diranalyzer->analyze(a->streamanalyzer); delete a; STRIGI_THREAD_EXIT(0); } void* updateInThread(void* d) { DA* a = static_cast<DA*>(d); a->diranalyzer->update(a->streamanalyzer); delete a; STRIGI_THREAD_EXIT(0); } DirAnalyzer::DirAnalyzer(IndexManager& manager, AnalyzerConfiguration& conf) :p(new Private(manager, conf)) { } DirAnalyzer::~DirAnalyzer() { delete p; } void DirAnalyzer::Private::analyze(StreamAnalyzer* analyzer) { try { string path; time_t mtime; int r = lister.nextFile(path, mtime); while (r >= 0 && (caller == 0 || caller->continueAnalysis())) { if (r > 0) { AnalysisResult analysisresult(path, mtime, *manager.indexWriter(), *analyzer); FileInputStream file(path.c_str()); if (file.status() == Ok) { analysisresult.index(&file); } else { analysisresult.index(0); } } r = lister.nextFile(path, mtime); } } catch(...) { fprintf(stderr, "Unknown error\n"); } } void DirAnalyzer::Private::update(StreamAnalyzer* analyzer) { vector<string> toDelete(1); try { string path; time_t mtime; // loop over all files that exist in the index int r = lister.nextFile(path, mtime); while (r >= 0 && (caller == 0 || caller->continueAnalysis())) { if (r > 0) { // check if this file is new or not STRIGI_MUTEX_LOCK(&updateMutex); map<string, time_t>::iterator i = dbfiles.find(path); bool newfile = i == dbfiles.end(); bool updatedfile = !newfile && i->second != mtime; // if the file is update we delete it in this loop // if it is new, it should not be in the list anyway // otherwise we should _not_ delete it and remove it from the // to be deleted list if (updatedfile || !newfile) { dbfiles.erase(i); } STRIGI_MUTEX_UNLOCK(&updateMutex); // if the file has not yet been indexed or if the mtime has // changed, index it if (updatedfile) { toDelete[0].assign(path); manager.indexWriter()->deleteEntries(toDelete); } if (newfile || updatedfile) { AnalysisResult analysisresult(path, mtime, *manager.indexWriter(), *analyzer); FileInputStream file(path.c_str()); if (file.status() == Ok) { analysisresult.index(&file); } else { analysisresult.index(0); } } } r = lister.nextFile(path, mtime); } } catch(...) { fprintf(stderr, "Unknown error\n"); } } int DirAnalyzer::analyzeDir(const string& dir, int nthreads, AnalysisCaller* c, const string& lastToSkip) { return p->analyzeDir(dir, nthreads, c, lastToSkip); } int DirAnalyzer::Private::analyzeDir(const string& dir, int nthreads, AnalysisCaller* c, const string& lastToSkip) { caller = c; // check if the path exists and if it is a file or a directory struct stat s; int retval = stat(dir.c_str(), &s); time_t mtime = (retval == -1) ?0 :s.st_mtime; if (retval == -1 || S_ISREG(s.st_mode)) { { // at the end of this block the analysisresult is deleted and indexed AnalysisResult analysisresult(dir, mtime, *manager.indexWriter(), analyzer); FileInputStream file(dir.c_str()); if (file.status() == Ok) { retval = analysisresult.index(&file); } else { retval = analysisresult.index(0); } } manager.indexWriter()->commit(); return retval; } lister.startListing(dir); if (lastToSkip.length()) { lister.skipTillAfter(lastToSkip); } if (nthreads < 1) nthreads = 1; vector<StreamAnalyzer*> analyzers(nthreads); analyzers[0] = &analyzer; for (int i=1; i<nthreads; ++i) { analyzers[i] = new StreamAnalyzer(config); analyzers[i]->setIndexWriter(*manager.indexWriter()); } vector<STRIGI_THREAD_TYPE> threads; threads.resize(nthreads-1); for (int i=1; i<nthreads; i++) { DA* da = new DA(); da->diranalyzer = this; da->streamanalyzer = analyzers[i]; STRIGI_THREAD_CREATE(&threads[i-1], analyzeInThread, da); } analyze(analyzers[0]); for (int i=1; i<nthreads; i++) { STRIGI_THREAD_JOIN(threads[i-1]); delete analyzers[i]; } manager.indexWriter()->commit(); return 0; } int DirAnalyzer::updateDir(const string& dir, int nthreads, AnalysisCaller* caller){ vector<string> dirs; dirs.push_back(dir); return p->updateDirs(dirs, nthreads, caller); } int DirAnalyzer::Private::updateDirs(const vector<string>& dirs, int nthreads, AnalysisCaller* c) { IndexReader* reader = manager.indexReader(); if (reader == 0) return -1; caller = c; // retrieve the complete list of files dbfiles = reader->files(0); // create the streamanalyzers if (nthreads < 1) nthreads = 1; vector<StreamAnalyzer*> analyzers(nthreads); analyzers[0] = &analyzer; for (int i=1; i<nthreads; ++i) { analyzers[i] = new StreamAnalyzer(config); analyzers[i]->setIndexWriter(*manager.indexWriter()); } vector<STRIGI_THREAD_TYPE> threads; threads.resize(nthreads-1); // loop over all directories that should be updated for (vector<string>::const_iterator d =dirs.begin(); d != dirs.end(); ++d) { lister.startListing(*d); for (int i=1; i<nthreads; i++) { DA* da = new DA(); da->diranalyzer = this; da->streamanalyzer = analyzers[i]; STRIGI_THREAD_CREATE(&threads[i-1], updateInThread, da); } update(analyzers[0]); for (int i=1; i<nthreads; i++) { STRIGI_THREAD_JOIN(threads[i-1]); } } // clean up the analyzers for (int i=1; i<nthreads; i++) { delete analyzers[i]; } // remove the files that were not encountered from the index vector<string> todelete(1); map<string,time_t>::iterator it = dbfiles.begin(); while (it != dbfiles.end()) { todelete[0].assign(it->first); manager.indexWriter()->deleteEntries(todelete); ++it; } dbfiles.clear(); return 0; } int DirAnalyzer::updateDirs(const std::vector<std::string>& dirs, int nthreads, AnalysisCaller* caller) { return p->updateDirs(dirs, nthreads, caller); } <commit_msg>Warnings--; be explicit about linkage.<commit_after>/* This file is part of Strigi Desktop Search * * Copyright (C) 2007 Jos van den Oever <jos@vandenoever.info> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "diranalyzer.h" #include "indexwriter.h" #include "indexmanager.h" #include "indexreader.h" #include "filelister.h" #include "analysisresult.h" #include "strigi_thread.h" #include "fileinputstream.h" #include <map> #include <iostream> #include <sys/stat.h> using namespace Strigi; using namespace std; class DirAnalyzer::Private { public: FileLister lister; IndexManager& manager; AnalyzerConfiguration& config; StreamAnalyzer analyzer; map<string, time_t> dbfiles; STRIGI_MUTEX_DEFINE(updateMutex); AnalysisCaller* caller; Private(IndexManager& m, AnalyzerConfiguration& c) :lister(&c), manager(m), config(c), analyzer(c) { STRIGI_MUTEX_INIT(&updateMutex); analyzer.setIndexWriter(*manager.indexWriter()); } ~Private() { STRIGI_MUTEX_DESTROY(&updateMutex); } int analyzeDir(const string& dir, int nthreads, AnalysisCaller* caller, const string& lastToSkip); int updateDirs(const vector<string>& dir, int nthreads, AnalysisCaller* caller); void analyze(StreamAnalyzer*); void update(StreamAnalyzer*); }; struct DA { StreamAnalyzer* streamanalyzer; DirAnalyzer::Private* diranalyzer; }; extern "C" // Linkage for functions passed to pthread_create matters { void* analyzeInThread(void* d) { DA* a = static_cast<DA*>(d); a->diranalyzer->analyze(a->streamanalyzer); delete a; STRIGI_THREAD_EXIT(0); return 0; // Return bogus value } void* updateInThread(void* d) { DA* a = static_cast<DA*>(d); a->diranalyzer->update(a->streamanalyzer); delete a; STRIGI_THREAD_EXIT(0); return 0; // Return bogus value } } DirAnalyzer::DirAnalyzer(IndexManager& manager, AnalyzerConfiguration& conf) :p(new Private(manager, conf)) { } DirAnalyzer::~DirAnalyzer() { delete p; } void DirAnalyzer::Private::analyze(StreamAnalyzer* analyzer) { try { string path; time_t mtime; int r = lister.nextFile(path, mtime); while (r >= 0 && (caller == 0 || caller->continueAnalysis())) { if (r > 0) { AnalysisResult analysisresult(path, mtime, *manager.indexWriter(), *analyzer); FileInputStream file(path.c_str()); if (file.status() == Ok) { analysisresult.index(&file); } else { analysisresult.index(0); } } r = lister.nextFile(path, mtime); } } catch(...) { fprintf(stderr, "Unknown error\n"); } } void DirAnalyzer::Private::update(StreamAnalyzer* analyzer) { vector<string> toDelete(1); try { string path; time_t mtime; // loop over all files that exist in the index int r = lister.nextFile(path, mtime); while (r >= 0 && (caller == 0 || caller->continueAnalysis())) { if (r > 0) { // check if this file is new or not STRIGI_MUTEX_LOCK(&updateMutex); map<string, time_t>::iterator i = dbfiles.find(path); bool newfile = i == dbfiles.end(); bool updatedfile = !newfile && i->second != mtime; // if the file is update we delete it in this loop // if it is new, it should not be in the list anyway // otherwise we should _not_ delete it and remove it from the // to be deleted list if (updatedfile || !newfile) { dbfiles.erase(i); } STRIGI_MUTEX_UNLOCK(&updateMutex); // if the file has not yet been indexed or if the mtime has // changed, index it if (updatedfile) { toDelete[0].assign(path); manager.indexWriter()->deleteEntries(toDelete); } if (newfile || updatedfile) { AnalysisResult analysisresult(path, mtime, *manager.indexWriter(), *analyzer); FileInputStream file(path.c_str()); if (file.status() == Ok) { analysisresult.index(&file); } else { analysisresult.index(0); } } } r = lister.nextFile(path, mtime); } } catch(...) { fprintf(stderr, "Unknown error\n"); } } int DirAnalyzer::analyzeDir(const string& dir, int nthreads, AnalysisCaller* c, const string& lastToSkip) { return p->analyzeDir(dir, nthreads, c, lastToSkip); } int DirAnalyzer::Private::analyzeDir(const string& dir, int nthreads, AnalysisCaller* c, const string& lastToSkip) { caller = c; // check if the path exists and if it is a file or a directory struct stat s; int retval = stat(dir.c_str(), &s); time_t mtime = (retval == -1) ?0 :s.st_mtime; if (retval == -1 || S_ISREG(s.st_mode)) { { // at the end of this block the analysisresult is deleted and indexed AnalysisResult analysisresult(dir, mtime, *manager.indexWriter(), analyzer); FileInputStream file(dir.c_str()); if (file.status() == Ok) { retval = analysisresult.index(&file); } else { retval = analysisresult.index(0); } } manager.indexWriter()->commit(); return retval; } lister.startListing(dir); if (lastToSkip.length()) { lister.skipTillAfter(lastToSkip); } if (nthreads < 1) nthreads = 1; vector<StreamAnalyzer*> analyzers(nthreads); analyzers[0] = &analyzer; for (int i=1; i<nthreads; ++i) { analyzers[i] = new StreamAnalyzer(config); analyzers[i]->setIndexWriter(*manager.indexWriter()); } vector<STRIGI_THREAD_TYPE> threads; threads.resize(nthreads-1); for (int i=1; i<nthreads; i++) { DA* da = new DA(); da->diranalyzer = this; da->streamanalyzer = analyzers[i]; STRIGI_THREAD_CREATE(&threads[i-1], analyzeInThread, da); } analyze(analyzers[0]); for (int i=1; i<nthreads; i++) { STRIGI_THREAD_JOIN(threads[i-1]); delete analyzers[i]; } manager.indexWriter()->commit(); return 0; } int DirAnalyzer::updateDir(const string& dir, int nthreads, AnalysisCaller* caller){ vector<string> dirs; dirs.push_back(dir); return p->updateDirs(dirs, nthreads, caller); } int DirAnalyzer::Private::updateDirs(const vector<string>& dirs, int nthreads, AnalysisCaller* c) { IndexReader* reader = manager.indexReader(); if (reader == 0) return -1; caller = c; // retrieve the complete list of files dbfiles = reader->files(0); // create the streamanalyzers if (nthreads < 1) nthreads = 1; vector<StreamAnalyzer*> analyzers(nthreads); analyzers[0] = &analyzer; for (int i=1; i<nthreads; ++i) { analyzers[i] = new StreamAnalyzer(config); analyzers[i]->setIndexWriter(*manager.indexWriter()); } vector<STRIGI_THREAD_TYPE> threads; threads.resize(nthreads-1); // loop over all directories that should be updated for (vector<string>::const_iterator d =dirs.begin(); d != dirs.end(); ++d) { lister.startListing(*d); for (int i=1; i<nthreads; i++) { DA* da = new DA(); da->diranalyzer = this; da->streamanalyzer = analyzers[i]; STRIGI_THREAD_CREATE(&threads[i-1], updateInThread, da); } update(analyzers[0]); for (int i=1; i<nthreads; i++) { STRIGI_THREAD_JOIN(threads[i-1]); } } // clean up the analyzers for (int i=1; i<nthreads; i++) { delete analyzers[i]; } // remove the files that were not encountered from the index vector<string> todelete(1); map<string,time_t>::iterator it = dbfiles.begin(); while (it != dbfiles.end()) { todelete[0].assign(it->first); manager.indexWriter()->deleteEntries(todelete); ++it; } dbfiles.clear(); return 0; } int DirAnalyzer::updateDirs(const std::vector<std::string>& dirs, int nthreads, AnalysisCaller* caller) { return p->updateDirs(dirs, nthreads, caller); } <|endoftext|>
<commit_before>#include "stdafx.h" #include "Writer.h" Writer::Writer() { Filing* file = new Filing(); file->Startup(); string path; //setup converter using convert_type = codecvt_utf8<wchar_t>; wstring_convert<convert_type, wchar_t> converter; //use converter (.to_bytes: wstr->str, .from_bytes: str->wstr) path = converter.to_bytes(*file->LogDirectoryPath); path.append("\\"); string* now = new string(this->GetTime()); path.append(*now); path.append(".txt"); this->Log.open(path, fstream::out); if (!Log) { throw new exception("Can't access file!"); } else { string message = "Log has initialized successfully"; this->WriteLine(&message); } ToDelete->push_back(file); ToDelete->push_back(now); } Writer::~Writer() { this->Log.close(); ToDelete->push_back(this->Last); } //0 = Red //1 = Yellow //2 = Green //3 = Default/Grey void Writer::WriteLine(string *Str) { if (Str != NULL && Str->size() > 0) { cout << this->GetTime(); cout << *Str; cout << "\r\n"; cout.flush(); } else { string a = "Someone attempted to write a null or empty string to the console!"; this->WriteLine(&a); } } void Writer::WriteLine(const char* Str) { delete this->Msg; Msg = new string(Str); this->WriteLine(this->Msg); } void Writer::LogLine(string *Str) { this->Last = new string(""); this->Last->append(this->GetTime()); this->Last->append(": "); this->Last->append(Str->c_str()); this->Last->append("\r\n"); this->Log << this->Last->substr(0, this->Last->size()); this->Log.flush(); } const char * Writer::GetTime() { string* Formatted = new string("["); time_t rawtime; tm* timeinfo; char buffer[80]; time(&rawtime); timeinfo = std::localtime(&rawtime); strftime(buffer, 80, "%Y-%m-%d-%H-%M-%S", timeinfo); Formatted->append(buffer); Formatted->append("]: "); ToDelete->push_back(Formatted); ToDelete->push_back(timeinfo); const char* Ret = Formatted->c_str(); return Ret; }<commit_msg>Fixed the logger.<commit_after>#include "stdafx.h" #include "Writer.h" Writer::Writer() { Filing* file = new Filing(); file->Startup(); string path; //setup converter using convert_type = codecvt_utf8<wchar_t>; wstring_convert<convert_type, wchar_t> converter; //use converter (.to_bytes: wstr->str, .from_bytes: str->wstr) path = converter.to_bytes(*file->LogDirectoryPath); path.append("\\"); string* now = new string(this->GetTime()); path.append(*now); path.pop_back(); path.pop_back(); path.append(".txt"); this->Log.open(path, fstream::out); if (!Log) { throw new exception("Can't access file!"); } else { string message = "Log has initialized successfully"; this->WriteLine(&message); } ToDelete->push_back(file); ToDelete->push_back(now); } Writer::~Writer() { this->Log.close(); ToDelete->push_back(this->Last); } //0 = Red //1 = Yellow //2 = Green //3 = Default/Grey void Writer::WriteLine(string *Str) { if (Str != NULL && Str->size() > 0) { cout << this->GetTime(); cout << *Str; cout << "\r\n"; cout.flush(); this->LogLine(Str); } else { string a = "Someone attempted to write a null or empty string to the console!"; this->WriteLine(&a); } } void Writer::WriteLine(const char* Str) { delete this->Msg; Msg = new string(Str); this->WriteLine(this->Msg); } void Writer::LogLine(string *Str) { this->Log << this->GetTime(); this->Log << *Str; this->Log << "\r\n"; this->Log.flush(); } const char * Writer::GetTime() { string* Formatted = new string("["); time_t rawtime; tm* timeinfo; char buffer[80]; time(&rawtime); timeinfo = std::localtime(&rawtime); strftime(buffer, 80, "%Y-%m-%d-%H-%M-%S", timeinfo); Formatted->append(buffer); Formatted->append("]: "); ToDelete->push_back(Formatted); ToDelete->push_back(timeinfo); const char* Ret = Formatted->c_str(); return Ret; }<|endoftext|>
<commit_before>// $Id$ /* -------------------------------------------------------------------------- CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-11 Bradley M. Bell CppAD is distributed under multiple licenses. This distribution is under the terms of the Common Public License Version 1.0. A copy of this license is included in the COPYING file of this distribution. Please visit http://www.coin-or.org/CppAD/ for information on other licenses. -------------------------------------------------------------------------- */ /* $begin pthread_simple_ad.cpp$$ $spell Cygwin pthread pthreads CppAD $$ $section Simple Pthread AD: Example and Test$$ $index pthread, simple AD$$ $index AD, simple pthread$$ $index simple, AD pthread$$ $index thread, pthread simple AD$$ $head Purpose$$ This example demonstrates how CppAD can be used with multiple pthreads. $head Discussion$$ The function $code arc_tan$$ below is an implementation of the inverse tangent function where the $cref/operation sequence/glossary/Operation/Sequence/$$ depends on the argument values. Hence the function needs to be re-taped for different argument values. The $cref/atan2/$$ function uses $cref/CondExp/$$ operations to avoid the need to re-tape. $head pthread_exit Bug in Cygwin$$ $index bug, cygwin pthread_exit$$ $index cygwin, bug in pthread_exit$$ $index pthread_exit, bug in cygwin$$ There is a bug in $code pthread_exit$$, using cygwin 5.1 and g++ version 4.3.4, whereby calling $code pthread_exit$$ is not the same as returning from the corresponding routine. To be specific, destructors for the vectors are not called and a memory leaks result. Search for $code pthread_exit$$ in the source code below to see how to demonstrate this bug. $head Source Code$$ $code $verbatim%multi_thread/pthread/simple_ad.cpp%0%// BEGIN PROGRAM%// END PROGRAM%1%$$ $$ $end ------------------------------------------------------------------------------ */ // BEGIN PROGRAM # include <pthread.h> # include <cppad/cppad.hpp> # include "../arc_tan.hpp" # define NUMBER_THREADS 4 # define DEMONSTRATE_BUG_IN_CYGWIN 0 namespace { // =================================================================== // General purpose code for linking CppAD to pthreads // ------------------------------------------------------------------- // alternative name for NUMBER_THREADS size_t number_threads = NUMBER_THREADS; // The master thread switches the value of this variable static bool multiple_threads_may_be_active = false; // Barrier used to wait for all thread identifiers to be set pthread_barrier_t wait_for_thread_id; // general purpose vector with information for each thread typedef struct { // pthread unique identifier for thread that uses this struct pthread_t thread_id; // cppad unique identifier for thread that uses this struct size_t thread_index; // true if no error for this thread, false otherwise. bool ok; } thread_info_t; thread_info_t thread_vector[NUMBER_THREADS]; // --------------------------------------------------------------------- // in_parallel() bool in_parallel(void) { return multiple_threads_may_be_active; } // --------------------------------------------------------------------- // thread_num() size_t thread_num(void) { // pthread unique identifier for this thread pthread_t thread_this = pthread_self(); // convert thread_this to the corresponding thread index size_t index = 0; for(index = 0; index < number_threads; index++) { // pthread unique identifier for this index pthread_t thread_compare = thread_vector[index].thread_id; // check for a match if( pthread_equal(thread_this, thread_compare) ) return index; } // no match error (thread_this is not in thread_vector). assert(false); return number_threads; } // ==================================================================== // code for specific problem we are solving // -------------------------------------------------------------------- using CppAD::AD; // vector with specific information for each thread typedef struct { // angle for this work double theta; // False if error related to this work, true otherwise. bool ok; } work_info_t; work_info_t work_vector[NUMBER_THREADS]; // -------------------------------------------------------------------- // function that does the work for each thread void* thread_work(void* thread_info_vptr) { using CppAD::NearEqual; // start as true bool ok = true; // ---------------------------------------------------------------- // Setup for this thread // general purpose information for this thread thread_info_t* thread_info = static_cast<thread_info_t*>(thread_info_vptr); // index to problem specific information for this thread size_t index = thread_info->thread_index; // Set pthread unique identifier for this thread thread_vector[index].thread_id = pthread_self(); // Wait for other threads to do the same. int rc = pthread_barrier_wait(&wait_for_thread_id); ok &= (rc == 0 || rc == PTHREAD_BARRIER_SERIAL_THREAD); // ---------------------------------------------------------------- // Work for this thread // (note that work[index] is only used by this thread) // CppAD::vector uses the CppAD fast multi-threading allocator CppAD::vector< AD<double> > Theta(1), Z(1); Theta[0] = work_vector[index].theta; Independent(Theta); AD<double> x = cos(Theta[0]); AD<double> y = sin(Theta[0]); Z[0] = arc_tan( x, y ); CppAD::ADFun<double> f(Theta, Z); // Check function value corresponds to the identity // (must get a lock before changing thread_info). double eps = 10. * CppAD::epsilon<double>(); ok &= NearEqual(Z[0], Theta[0], eps, eps); // Check derivative value corresponds to the identity. CppAD::vector<double> d_theta(1), d_z(1); d_theta[0] = 1.; d_z = f.Forward(1, d_theta); ok &= NearEqual(d_z[0], 1., eps, eps); // pass back ok information for this thread work_vector[index].ok = ok; // It this is not the master thread, then terminate it. # if DEMONSTRATE_BUG_IN_CYGWIN if( ! pthread_equal( thread_info->thread_id, thread_vector[0].thread_id) ) { void* no_status = 0; pthread_exit(no_status); } # endif // return null pointer return 0; } } // This test routine is only called by the master thread (index = 0). bool simple_ad(void) { bool all_ok = true; using CppAD::thread_alloc; // Check that no memory is in use or avialable at start // (using thread_alloc in sequential mode) size_t index; for(index = 0; index < number_threads; index++) { all_ok &= thread_alloc::inuse(index) == 0; all_ok &= thread_alloc::available(index) == 0; } // initialize the thread_vector and work_vector int rc; double pi = 4. * atan(1.); for(index = 0; index < number_threads; index++) { // thread_id (initialze all as same as master thread) thread_vector[index].thread_id = pthread_self(); // thread_index thread_vector[index].thread_index = index; // ok thread_vector[index].ok = true; work_vector[index].ok = false; // theta work_vector[index].theta = index * pi / number_threads; } // Setup for using AD<double> in parallel mode thread_alloc::parallel_setup(number_threads, in_parallel, thread_num); CppAD::parallel_ad<double>(); // Now change in_parallel() to return true. multiple_threads_may_be_active = true; // initialize barrier as waiting for number_threads pthread_barrierattr_t *no_barrierattr = 0; rc = pthread_barrier_init( &wait_for_thread_id, no_barrierattr, number_threads); all_ok &= (rc == 0); // structure used to cread the threads pthread_t thread[NUMBER_THREADS]; pthread_attr_t attr; void* thread_info_vptr; // rc = pthread_attr_init(&attr); all_ok &= (rc == 0); rc = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); all_ok &= (rc == 0); // This master thread is already running, we need to create // number_threads - 1 more threads for(index = 1; index < number_threads; index++) { // Create the thread with thread_num equal to index thread_info_vptr = static_cast<void*> ( &(thread_vector[index]) ); rc = pthread_create( &thread[index] , &attr , thread_work , thread_info_vptr ); all_ok &= (rc == 0); } // Now, while other threads are working, do work in master thread also thread_info_vptr = static_cast<void*> ( &(thread_vector[0]) ); thread_work(thread_info_vptr); // now wait for the other threads to finish for(index = 1; index < number_threads; index++) { void* no_status = 0; rc = pthread_join(thread[index], &no_status); all_ok &= (rc == 0); } // Tell thread_alloc that we are in sequential execution mode. multiple_threads_may_be_active = false; // Summarize results. for(index = 0; index < number_threads; index++) { all_ok &= thread_vector[index].ok; all_ok &= work_vector[index].ok; } // Free up the pthread resources that are no longer in use. rc = pthread_attr_destroy(&attr); all_ok &= (rc == 0); rc = pthread_barrier_destroy(&wait_for_thread_id); all_ok &= (rc == 0); // Check that no memory currently in use, and free avialable memory. for(index = 0; index < number_threads; index++) { all_ok &= thread_alloc::inuse(index) == 0; thread_alloc::free_available(index); } // return memory allocator to single threading mode number_threads = 1; thread_alloc::parallel_setup(number_threads, in_parallel, thread_num); return all_ok; } // END PROGRAM <commit_msg>preparing to split out set_up_ad.cpp<commit_after>// $Id$ /* -------------------------------------------------------------------------- CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-11 Bradley M. Bell CppAD is distributed under multiple licenses. This distribution is under the terms of the Common Public License Version 1.0. A copy of this license is included in the COPYING file of this distribution. Please visit http://www.coin-or.org/CppAD/ for information on other licenses. -------------------------------------------------------------------------- */ /* $begin pthread_simple_ad.cpp$$ $spell Cygwin pthread pthreads CppAD $$ $section Simple Pthread AD: Example and Test$$ $index pthread, simple AD$$ $index AD, simple pthread$$ $index simple, AD pthread$$ $index thread, pthread simple AD$$ $head Purpose$$ This example demonstrates how CppAD can be used with multiple pthreads. $head Discussion$$ The function $code arc_tan$$ below is an implementation of the inverse tangent function where the $cref/operation sequence/glossary/Operation/Sequence/$$ depends on the argument values. Hence the function needs to be re-taped for different argument values. The $cref/atan2/$$ function uses $cref/CondExp/$$ operations to avoid the need to re-tape. $head pthread_exit Bug in Cygwin$$ $index bug, cygwin pthread_exit$$ $index cygwin, bug in pthread_exit$$ $index pthread_exit, bug in cygwin$$ There is a bug in $code pthread_exit$$, using cygwin 5.1 and g++ version 4.3.4, whereby calling $code pthread_exit$$ is not the same as returning from the corresponding routine. To be specific, destructors for the vectors are not called and a memory leaks result. Search for $code pthread_exit$$ in the source code below to see how to demonstrate this bug. $head Source Code$$ $code $verbatim%multi_thread/pthread/simple_ad.cpp%0%// BEGIN PROGRAM%// END PROGRAM%1%$$ $$ $end ------------------------------------------------------------------------------ */ // BEGIN PROGRAM # include <pthread.h> # include <cppad/cppad.hpp> # include "../arc_tan.hpp" # define NUMBER_THREADS 4 # define DEMONSTRATE_BUG_IN_CYGWIN 0 namespace { // =================================================================== // General purpose code for linking CppAD to pthreads // ------------------------------------------------------------------- size_t num_threads_ = 1; // Barrier used to wait for all thread identifiers to be set pthread_barrier_t wait_for_pthread_id; // general purpose vector with information for each thread typedef struct { // pthread unique identifier for thread that uses this struct pthread_t pthread_id; // cppad unique identifier for thread that uses this struct size_t thread_num; // have any operations on this thread failed bool ok; } thread_info_t; thread_info_t thread_vector[NUMBER_THREADS]; // --------------------------------------------------------------------- // in_parallel() bool in_parallel(void) { return num_threads_ > 1; } // --------------------------------------------------------------------- // thread_number() size_t thread_number(void) { // pthread unique identifier for this thread pthread_t thread_this = pthread_self(); // convert thread_this to the corresponding thread_num size_t thread_num = 0; for(thread_num = 0; thread_num < num_threads_; thread_num++) { // pthread unique identifier for this thread_num pthread_t thread_compare = thread_vector[thread_num].pthread_id; // check for a match if( pthread_equal(thread_this, thread_compare) ) return thread_num; } // no match error (thread_this is not in thread_vector). assert(false); return num_threads_; } // ==================================================================== // code for specific problem we are solving // -------------------------------------------------------------------- using CppAD::AD; // vector with specific information for each thread typedef struct { // angle for this work double theta; // False if error related to this work, true otherwise. bool ok; } work_info_t; work_info_t work_vector[NUMBER_THREADS]; // -------------------------------------------------------------------- // function that does the work for each thread void* thread_work(void* thread_info_vptr) { using CppAD::NearEqual; // start as true bool ok = true; // ---------------------------------------------------------------- // Setup for this thread // general purpose information for this thread thread_info_t* thread_info = static_cast<thread_info_t*>(thread_info_vptr); // thread_num for this thread size_t thread_num = thread_info->thread_num; // Set pthread unique identifier for this thread thread_vector[thread_num].pthread_id = pthread_self(); // Wait for other threads to do the same. int rc = pthread_barrier_wait(&wait_for_pthread_id); thread_vector[thread_num].ok &= (rc == 0 || rc == PTHREAD_BARRIER_SERIAL_THREAD); // ---------------------------------------------------------------- // Work for this thread // (note that work[thread_num] is only used by this thread) // CppAD::vector uses the CppAD fast multi-threading allocator CppAD::vector< AD<double> > Theta(1), Z(1); Theta[0] = work_vector[thread_num].theta; Independent(Theta); AD<double> x = cos(Theta[0]); AD<double> y = sin(Theta[0]); Z[0] = arc_tan( x, y ); CppAD::ADFun<double> f(Theta, Z); // Check function value corresponds to the identity // (must get a lock before changing thread_info). double eps = 10. * CppAD::epsilon<double>(); ok &= NearEqual(Z[0], Theta[0], eps, eps); // Check derivative value corresponds to the identity. CppAD::vector<double> d_theta(1), d_z(1); d_theta[0] = 1.; d_z = f.Forward(1, d_theta); ok &= NearEqual(d_z[0], 1., eps, eps); // pass back ok information for this thread work_vector[thread_num].ok = ok; // It this is not the master thread, then terminate it. # if DEMONSTRATE_BUG_IN_CYGWIN if( ! pthread_equal( thread_info->pthread_id, thread_vector[0].pthread_id) ) { void* no_status = 0; pthread_exit(no_status); } # endif // return null pointer return 0; } } // This test routine is only called by the master thread (thread_num = 0). bool simple_ad(void) { bool all_ok = true; using CppAD::thread_alloc; size_t num_threads = NUMBER_THREADS; // Check that no memory is in use or avialable at start // (using thread_alloc in sequential mode) size_t thread_num; for(thread_num = 0; thread_num < num_threads; thread_num++) { all_ok &= thread_alloc::inuse(thread_num) == 0; all_ok &= thread_alloc::available(thread_num) == 0; } // initialize the thread_vector and work_vector int rc; double pi = 4. * atan(1.); for(thread_num = 0; thread_num < num_threads; thread_num++) { // pthread_id (initialze all as same as master thread) thread_vector[thread_num].pthread_id = pthread_self(); // thread_num thread_vector[thread_num].thread_num = thread_num; thread_vector[thread_num].ok = true; work_vector[thread_num].ok = false; // theta work_vector[thread_num].theta = thread_num * pi / num_threads; } // Setup for using AD<double> in parallel mode thread_alloc::parallel_setup(num_threads, in_parallel, thread_number); CppAD::parallel_ad<double>(); // Now change in_parallel() to return true. num_threads_ = 1; // initialize barrier as waiting for num_threads pthread_barrierattr_t *no_barrierattr = 0; rc = pthread_barrier_init( &wait_for_pthread_id, no_barrierattr, num_threads); all_ok &= (rc == 0); // structure used to cread the threads pthread_t thread[NUMBER_THREADS]; pthread_attr_t attr; void* thread_info_vptr; // rc = pthread_attr_init(&attr); all_ok &= (rc == 0); rc = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); all_ok &= (rc == 0); // This master thread is already running, we need to create // num_threads - 1 more threads for(thread_num = 1; thread_num < num_threads; thread_num++) { // Create the thread with thread_num equal to thread_num thread_info_vptr = static_cast<void*> (&(thread_vector[thread_num])); rc = pthread_create( &thread[thread_num] , &attr , thread_work , thread_info_vptr ); all_ok &= (rc == 0); } // Now, while other threads are working, do work in master thread also thread_info_vptr = static_cast<void*> ( &(thread_vector[0]) ); thread_work(thread_info_vptr); // now wait for the other threads to finish for(thread_num = 1; thread_num < num_threads; thread_num++) { void* no_status = 0; rc = pthread_join(thread[thread_num], &no_status); all_ok &= (rc == 0); } // Tell thread_alloc that we are in sequential execution mode. num_threads_ = 1; // Summarize results. for(thread_num = 0; thread_num < num_threads; thread_num++) { all_ok &= thread_vector[thread_num].ok; all_ok &= work_vector[thread_num].ok; } // Free up the pthread resources that are no longer in use. rc = pthread_attr_destroy(&attr); all_ok &= (rc == 0); rc = pthread_barrier_destroy(&wait_for_pthread_id); all_ok &= (rc == 0); // Check that no memory currently in use, and free avialable memory. for(thread_num = 0; thread_num < num_threads; thread_num++) { all_ok &= thread_alloc::inuse(thread_num) == 0; thread_alloc::free_available(thread_num); } // return memory allocator to single threading mode num_threads = 1; thread_alloc::parallel_setup(num_threads, in_parallel, thread_number); return all_ok; } // END PROGRAM <|endoftext|>
<commit_before>/* * * Copyright 2016 gRPC authors. * * 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. * */ /** \file Verify that status ordering rules are obeyed. \ref doc/status_ordering.md */ #include "test/core/end2end/end2end_tests.h" #include <stdio.h> #include <string.h> #include <grpc/byte_buffer.h> #include <grpc/support/alloc.h> #include <grpc/support/log.h> #include <grpc/support/time.h> #include "test/core/end2end/cq_verifier.h" static void* tag(intptr_t t) { return (void*)t; } static grpc_end2end_test_fixture begin_test(grpc_end2end_test_config config, const char* test_name, grpc_channel_args* client_args, grpc_channel_args* server_args, bool request_status_early) { grpc_end2end_test_fixture f; gpr_log(GPR_INFO, "Running test: %s/%s/request_status_early=%s", test_name, config.name, request_status_early ? "true" : "false"); f = config.create_fixture(client_args, server_args); config.init_server(&f, server_args); config.init_client(&f, client_args); return f; } static gpr_timespec n_seconds_from_now(int n) { return grpc_timeout_seconds_to_deadline(n); } static gpr_timespec five_seconds_from_now(void) { return n_seconds_from_now(5); } static void drain_cq(grpc_completion_queue* cq) { grpc_event ev; do { ev = grpc_completion_queue_next(cq, five_seconds_from_now(), nullptr); } while (ev.type != GRPC_QUEUE_SHUTDOWN); } static void shutdown_server(grpc_end2end_test_fixture* f) { if (!f->server) return; grpc_server_shutdown_and_notify(f->server, f->shutdown_cq, tag(1000)); GPR_ASSERT(grpc_completion_queue_pluck(f->shutdown_cq, tag(1000), grpc_timeout_seconds_to_deadline(5), nullptr) .type == GRPC_OP_COMPLETE); grpc_server_destroy(f->server); f->server = nullptr; } static void shutdown_client(grpc_end2end_test_fixture* f) { if (!f->client) return; grpc_channel_destroy(f->client); f->client = nullptr; } static void end_test(grpc_end2end_test_fixture* f) { shutdown_server(f); shutdown_client(f); grpc_completion_queue_shutdown(f->cq); drain_cq(f->cq); grpc_completion_queue_destroy(f->cq); grpc_completion_queue_destroy(f->shutdown_cq); } /* Client sends a request with payload, server reads then returns status. */ static void test(grpc_end2end_test_config config, bool request_status_early) { grpc_call* c; grpc_call* s; grpc_slice response_payload1_slice = grpc_slice_from_copied_string("hello"); grpc_byte_buffer* response_payload1 = grpc_raw_byte_buffer_create(&response_payload1_slice, 1); grpc_slice response_payload2_slice = grpc_slice_from_copied_string("world"); grpc_byte_buffer* response_payload2 = grpc_raw_byte_buffer_create(&response_payload2_slice, 1); grpc_end2end_test_fixture f = begin_test(config, "streaming_error_response", nullptr, nullptr, request_status_early); cq_verifier* cqv = cq_verifier_create(f.cq); grpc_op ops[6]; grpc_op* op; grpc_metadata_array initial_metadata_recv; grpc_metadata_array trailing_metadata_recv; grpc_metadata_array request_metadata_recv; grpc_byte_buffer* response_payload1_recv = nullptr; grpc_byte_buffer* response_payload2_recv = nullptr; grpc_call_details call_details; grpc_status_code status = GRPC_STATUS_OK; grpc_call_error error; grpc_slice details; int was_cancelled = 2; gpr_timespec deadline = five_seconds_from_now(); c = grpc_channel_create_call(f.client, nullptr, GRPC_PROPAGATE_DEFAULTS, f.cq, grpc_slice_from_static_string("/foo"), nullptr, deadline, nullptr); GPR_ASSERT(c); grpc_metadata_array_init(&initial_metadata_recv); grpc_metadata_array_init(&trailing_metadata_recv); grpc_metadata_array_init(&request_metadata_recv); grpc_call_details_init(&call_details); memset(ops, 0, sizeof(ops)); op = ops; op->op = GRPC_OP_SEND_INITIAL_METADATA; op->data.send_initial_metadata.count = 0; op++; op->op = GRPC_OP_SEND_CLOSE_FROM_CLIENT; op++; op->op = GRPC_OP_RECV_INITIAL_METADATA; op->data.recv_initial_metadata.recv_initial_metadata = &initial_metadata_recv; op++; op->op = GRPC_OP_RECV_MESSAGE; op->data.recv_message.recv_message = &response_payload1_recv; op++; if (request_status_early) { op->op = GRPC_OP_RECV_STATUS_ON_CLIENT; op->data.recv_status_on_client.trailing_metadata = &trailing_metadata_recv; op->data.recv_status_on_client.status = &status; op->data.recv_status_on_client.status_details = &details; op++; } error = grpc_call_start_batch(c, ops, static_cast<size_t>(op - ops), tag(1), nullptr); GPR_ASSERT(GRPC_CALL_OK == error); GPR_ASSERT(GRPC_CALL_OK == grpc_server_request_call( f.server, &s, &call_details, &request_metadata_recv, f.cq, f.cq, tag(101))); CQ_EXPECT_COMPLETION(cqv, tag(101), 1); cq_verify(cqv); memset(ops, 0, sizeof(ops)); op = ops; op->op = GRPC_OP_SEND_INITIAL_METADATA; op->data.send_initial_metadata.count = 0; op++; op->op = GRPC_OP_SEND_MESSAGE; op->data.send_message.send_message = response_payload1; op++; error = grpc_call_start_batch(s, ops, static_cast<size_t>(op - ops), tag(102), nullptr); GPR_ASSERT(GRPC_CALL_OK == error); CQ_EXPECT_COMPLETION(cqv, tag(102), 1); if (!request_status_early) { CQ_EXPECT_COMPLETION(cqv, tag(1), 1); } cq_verify(cqv); memset(ops, 0, sizeof(ops)); op = ops; op->op = GRPC_OP_SEND_MESSAGE; op->data.send_message.send_message = response_payload2; op++; error = grpc_call_start_batch(s, ops, static_cast<size_t>(op - ops), tag(103), nullptr); GPR_ASSERT(GRPC_CALL_OK == error); CQ_EXPECT_COMPLETION(cqv, tag(103), 1); if (!request_status_early) { memset(ops, 0, sizeof(ops)); op = ops; op->op = GRPC_OP_RECV_MESSAGE; op->data.recv_message.recv_message = &response_payload2_recv; op++; error = grpc_call_start_batch(c, ops, static_cast<size_t>(op - ops), tag(2), nullptr); GPR_ASSERT(GRPC_CALL_OK == error); CQ_EXPECT_COMPLETION(cqv, tag(2), 1); cq_verify(cqv); } memset(ops, 0, sizeof(ops)); op = ops; op->op = GRPC_OP_RECV_CLOSE_ON_SERVER; op->data.recv_close_on_server.cancelled = &was_cancelled; op++; op->op = GRPC_OP_SEND_STATUS_FROM_SERVER; op->data.send_status_from_server.trailing_metadata_count = 0; op->data.send_status_from_server.status = GRPC_STATUS_FAILED_PRECONDITION; grpc_slice status_details = grpc_slice_from_static_string("xyz"); op->data.send_status_from_server.status_details = &status_details; op++; error = grpc_call_start_batch(s, ops, static_cast<size_t>(op - ops), tag(104), nullptr); GPR_ASSERT(GRPC_CALL_OK == error); CQ_EXPECT_COMPLETION(cqv, tag(104), 1); if (request_status_early) { CQ_EXPECT_COMPLETION(cqv, tag(1), 1); } cq_verify(cqv); if (!request_status_early) { memset(ops, 0, sizeof(ops)); op = ops; op->op = GRPC_OP_RECV_STATUS_ON_CLIENT; op->data.recv_status_on_client.trailing_metadata = &trailing_metadata_recv; op->data.recv_status_on_client.status = &status; op->data.recv_status_on_client.status_details = &details; op++; error = grpc_call_start_batch(c, ops, static_cast<size_t>(op - ops), tag(3), nullptr); GPR_ASSERT(GRPC_CALL_OK == error); CQ_EXPECT_COMPLETION(cqv, tag(3), 1); cq_verify(cqv); GPR_ASSERT(response_payload1_recv != nullptr); GPR_ASSERT(response_payload2_recv != nullptr); } GPR_ASSERT(status == GRPC_STATUS_FAILED_PRECONDITION); GPR_ASSERT(0 == grpc_slice_str_cmp(details, "xyz")); GPR_ASSERT(0 == grpc_slice_str_cmp(call_details.method, "/foo")); GPR_ASSERT(was_cancelled == 1); grpc_slice_unref(details); grpc_metadata_array_destroy(&initial_metadata_recv); grpc_metadata_array_destroy(&trailing_metadata_recv); grpc_metadata_array_destroy(&request_metadata_recv); grpc_call_details_destroy(&call_details); grpc_call_unref(c); grpc_call_unref(s); cq_verifier_destroy(cqv); grpc_byte_buffer_destroy(response_payload1); grpc_byte_buffer_destroy(response_payload2); grpc_byte_buffer_destroy(response_payload1_recv); grpc_byte_buffer_destroy(response_payload2_recv); end_test(&f); config.tear_down_data(&f); } void streaming_error_response(grpc_end2end_test_config config) { test(config, false); test(config, true); } void streaming_error_response_pre_init(void) {} <commit_msg>Added another test case for status ordering<commit_after>/* * * Copyright 2016 gRPC authors. * * 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. * */ /** \file Verify that status ordering rules are obeyed. \ref doc/status_ordering.md */ #include "test/core/end2end/end2end_tests.h" #include <stdio.h> #include <string.h> #include <grpc/byte_buffer.h> #include <grpc/support/alloc.h> #include <grpc/support/log.h> #include <grpc/support/time.h> #include "test/core/end2end/cq_verifier.h" static void* tag(intptr_t t) { return (void*)t; } static grpc_end2end_test_fixture begin_test(grpc_end2end_test_config config, const char* test_name, grpc_channel_args* client_args, grpc_channel_args* server_args, bool request_status_early) { grpc_end2end_test_fixture f; gpr_log(GPR_INFO, "Running test: %s/%s/request_status_early=%s", test_name, config.name, request_status_early ? "true" : "false"); f = config.create_fixture(client_args, server_args); config.init_server(&f, server_args); config.init_client(&f, client_args); return f; } static gpr_timespec n_seconds_from_now(int n) { return grpc_timeout_seconds_to_deadline(n); } static gpr_timespec five_seconds_from_now(void) { return n_seconds_from_now(5); } static void drain_cq(grpc_completion_queue* cq) { grpc_event ev; do { ev = grpc_completion_queue_next(cq, five_seconds_from_now(), nullptr); } while (ev.type != GRPC_QUEUE_SHUTDOWN); } static void shutdown_server(grpc_end2end_test_fixture* f) { if (!f->server) return; grpc_server_shutdown_and_notify(f->server, f->shutdown_cq, tag(1000)); GPR_ASSERT(grpc_completion_queue_pluck(f->shutdown_cq, tag(1000), grpc_timeout_seconds_to_deadline(5), nullptr) .type == GRPC_OP_COMPLETE); grpc_server_destroy(f->server); f->server = nullptr; } static void shutdown_client(grpc_end2end_test_fixture* f) { if (!f->client) return; grpc_channel_destroy(f->client); f->client = nullptr; } static void end_test(grpc_end2end_test_fixture* f) { shutdown_server(f); shutdown_client(f); grpc_completion_queue_shutdown(f->cq); drain_cq(f->cq); grpc_completion_queue_destroy(f->cq); grpc_completion_queue_destroy(f->shutdown_cq); } /* Client sends a request with payload, server reads then returns status. */ static void test(grpc_end2end_test_config config, bool request_status_early, bool recv_message_separately) { grpc_call* c; grpc_call* s; grpc_slice response_payload1_slice = grpc_slice_from_copied_string("hello"); grpc_byte_buffer* response_payload1 = grpc_raw_byte_buffer_create(&response_payload1_slice, 1); grpc_slice response_payload2_slice = grpc_slice_from_copied_string("world"); grpc_byte_buffer* response_payload2 = grpc_raw_byte_buffer_create(&response_payload2_slice, 1); grpc_end2end_test_fixture f = begin_test(config, "streaming_error_response", nullptr, nullptr, request_status_early); cq_verifier* cqv = cq_verifier_create(f.cq); grpc_op ops[6]; grpc_op* op; grpc_metadata_array initial_metadata_recv; grpc_metadata_array trailing_metadata_recv; grpc_metadata_array request_metadata_recv; grpc_byte_buffer* response_payload1_recv = nullptr; grpc_byte_buffer* response_payload2_recv = nullptr; grpc_call_details call_details; grpc_status_code status = GRPC_STATUS_OK; grpc_call_error error; grpc_slice details; int was_cancelled = 2; gpr_timespec deadline = five_seconds_from_now(); GPR_ASSERT(!recv_message_separately || request_status_early); c = grpc_channel_create_call(f.client, nullptr, GRPC_PROPAGATE_DEFAULTS, f.cq, grpc_slice_from_static_string("/foo"), nullptr, deadline, nullptr); GPR_ASSERT(c); grpc_metadata_array_init(&initial_metadata_recv); grpc_metadata_array_init(&trailing_metadata_recv); grpc_metadata_array_init(&request_metadata_recv); grpc_call_details_init(&call_details); memset(ops, 0, sizeof(ops)); op = ops; op->op = GRPC_OP_SEND_INITIAL_METADATA; op->data.send_initial_metadata.count = 0; op++; op->op = GRPC_OP_SEND_CLOSE_FROM_CLIENT; op++; op->op = GRPC_OP_RECV_INITIAL_METADATA; op->data.recv_initial_metadata.recv_initial_metadata = &initial_metadata_recv; op++; if (!recv_message_separately) { op->op = GRPC_OP_RECV_MESSAGE; op->data.recv_message.recv_message = &response_payload1_recv; op++; } if (request_status_early) { op->op = GRPC_OP_RECV_STATUS_ON_CLIENT; op->data.recv_status_on_client.trailing_metadata = &trailing_metadata_recv; op->data.recv_status_on_client.status = &status; op->data.recv_status_on_client.status_details = &details; op++; } error = grpc_call_start_batch(c, ops, static_cast<size_t>(op - ops), tag(1), nullptr); GPR_ASSERT(GRPC_CALL_OK == error); GPR_ASSERT(GRPC_CALL_OK == grpc_server_request_call( f.server, &s, &call_details, &request_metadata_recv, f.cq, f.cq, tag(101))); CQ_EXPECT_COMPLETION(cqv, tag(101), 1); cq_verify(cqv); memset(ops, 0, sizeof(ops)); op = ops; op->op = GRPC_OP_SEND_INITIAL_METADATA; op->data.send_initial_metadata.count = 0; op++; op->op = GRPC_OP_SEND_MESSAGE; op->data.send_message.send_message = response_payload1; op++; error = grpc_call_start_batch(s, ops, static_cast<size_t>(op - ops), tag(102), nullptr); GPR_ASSERT(GRPC_CALL_OK == error); if (recv_message_separately) { memset(ops, 0, sizeof(ops)); op = ops; op->op = GRPC_OP_RECV_MESSAGE; op->data.recv_message.recv_message = &response_payload1_recv; op++; error = grpc_call_start_batch(c, ops, static_cast<size_t>(op - ops), tag(4), nullptr); GPR_ASSERT(GRPC_CALL_OK == error); } CQ_EXPECT_COMPLETION(cqv, tag(102), 1); if (!request_status_early) { CQ_EXPECT_COMPLETION(cqv, tag(1), 1); } if (recv_message_separately) { CQ_EXPECT_COMPLETION(cqv, tag(4), 1); } cq_verify(cqv); memset(ops, 0, sizeof(ops)); op = ops; op->op = GRPC_OP_SEND_MESSAGE; op->data.send_message.send_message = response_payload2; op++; error = grpc_call_start_batch(s, ops, static_cast<size_t>(op - ops), tag(103), nullptr); GPR_ASSERT(GRPC_CALL_OK == error); CQ_EXPECT_COMPLETION(cqv, tag(103), 1); if (!request_status_early) { memset(ops, 0, sizeof(ops)); op = ops; op->op = GRPC_OP_RECV_MESSAGE; op->data.recv_message.recv_message = &response_payload2_recv; op++; error = grpc_call_start_batch(c, ops, static_cast<size_t>(op - ops), tag(2), nullptr); GPR_ASSERT(GRPC_CALL_OK == error); CQ_EXPECT_COMPLETION(cqv, tag(2), 1); cq_verify(cqv); } memset(ops, 0, sizeof(ops)); op = ops; op->op = GRPC_OP_RECV_CLOSE_ON_SERVER; op->data.recv_close_on_server.cancelled = &was_cancelled; op++; op->op = GRPC_OP_SEND_STATUS_FROM_SERVER; op->data.send_status_from_server.trailing_metadata_count = 0; op->data.send_status_from_server.status = GRPC_STATUS_FAILED_PRECONDITION; grpc_slice status_details = grpc_slice_from_static_string("xyz"); op->data.send_status_from_server.status_details = &status_details; op++; error = grpc_call_start_batch(s, ops, static_cast<size_t>(op - ops), tag(104), nullptr); GPR_ASSERT(GRPC_CALL_OK == error); CQ_EXPECT_COMPLETION(cqv, tag(104), 1); if (request_status_early) { CQ_EXPECT_COMPLETION(cqv, tag(1), 1); } cq_verify(cqv); if (!request_status_early) { memset(ops, 0, sizeof(ops)); op = ops; op->op = GRPC_OP_RECV_STATUS_ON_CLIENT; op->data.recv_status_on_client.trailing_metadata = &trailing_metadata_recv; op->data.recv_status_on_client.status = &status; op->data.recv_status_on_client.status_details = &details; op++; error = grpc_call_start_batch(c, ops, static_cast<size_t>(op - ops), tag(3), nullptr); GPR_ASSERT(GRPC_CALL_OK == error); CQ_EXPECT_COMPLETION(cqv, tag(3), 1); cq_verify(cqv); GPR_ASSERT(response_payload1_recv != nullptr); GPR_ASSERT(response_payload2_recv != nullptr); } GPR_ASSERT(status == GRPC_STATUS_FAILED_PRECONDITION); GPR_ASSERT(0 == grpc_slice_str_cmp(details, "xyz")); GPR_ASSERT(0 == grpc_slice_str_cmp(call_details.method, "/foo")); GPR_ASSERT(was_cancelled == 1); grpc_slice_unref(details); grpc_metadata_array_destroy(&initial_metadata_recv); grpc_metadata_array_destroy(&trailing_metadata_recv); grpc_metadata_array_destroy(&request_metadata_recv); grpc_call_details_destroy(&call_details); grpc_call_unref(c); grpc_call_unref(s); cq_verifier_destroy(cqv); grpc_byte_buffer_destroy(response_payload1); grpc_byte_buffer_destroy(response_payload2); grpc_byte_buffer_destroy(response_payload1_recv); grpc_byte_buffer_destroy(response_payload2_recv); end_test(&f); config.tear_down_data(&f); } void streaming_error_response(grpc_end2end_test_config config) { test(config, false, false); test(config, true, false); test(config, true, true); } void streaming_error_response_pre_init(void) {} <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: edtspell.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: obo $ $Date: 2006-10-12 11:40:35 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _EDTSPELL_HXX #define _EDTSPELL_HXX #include <svxbox.hxx> #include <svxenum.hxx> #include <splwrap.hxx> #include <svxacorr.hxx> #ifndef _COM_SUN_STAR_UNO_REFERENCE_H_ #include <com/sun/star/uno/Reference.h> #endif #ifndef INCLUDED_SVXDLLAPI_H #include "svx/svxdllapi.h" #endif namespace com { namespace sun { namespace star { namespace linguistic2 { class XSpellChecker1; }}}} class EditView; class ImpEditEngine; class ContentNode; class EditSpellWrapper : public SvxSpellWrapper { private: EditView* pEditView; void CheckSpellTo(); protected: virtual void SpellStart( SvxSpellArea eArea ); virtual BOOL SpellContinue(); // Bereich pruefen virtual void ReplaceAll( const String &rNewText, INT16 nLanguage ); virtual void SpellEnd(); // virtual BOOL (); virtual BOOL SpellMore(); virtual BOOL HasOtherCnt(); virtual void ScrollArea(); virtual void ChangeWord( const String& rNewWord, const USHORT nLang ); virtual void ChangeThesWord( const String& rNewWord ); // virtual void ChangeAll( const String& rNewWord ); virtual void AutoCorrect( const String& rOldWord, const String& rNewWord ); // virtual String GetCurrentWord() const; public: EditSpellWrapper( Window* pWin, ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XSpellChecker1 > &xChecker, BOOL bIsStart, BOOL bIsAllRight, EditView* pView ); }; struct WrongRange { USHORT nStart; USHORT nEnd; WrongRange( USHORT nS, USHORT nE ) { nStart = nS; nEnd = nE; } }; SV_DECL_VARARR( WrongRanges, WrongRange, 4, 4 ) #define NOT_INVALID 0xFFFF class WrongList : private WrongRanges { private: USHORT nInvalidStart; USHORT nInvalidEnd; BOOL DbgIsBuggy() const; public: WrongList(); ~WrongList(); BOOL IsInvalid() const { return nInvalidStart != NOT_INVALID; } void SetValid() { nInvalidStart = NOT_INVALID; nInvalidEnd = 0; } void MarkInvalid( USHORT nS, USHORT nE ) { if ( ( nInvalidStart == NOT_INVALID ) || ( nInvalidStart > nS ) ) nInvalidStart = nS; if ( nInvalidEnd < nE ) nInvalidEnd = nE; } USHORT Count() const { return WrongRanges::Count(); } // Wenn man weiss was man tut: WrongRange& GetObject( USHORT n ) const { return WrongRanges::GetObject( n ); } void InsertWrong( const WrongRange& rWrong, USHORT nPos ); USHORT GetInvalidStart() const { return nInvalidStart; } USHORT& GetInvalidStart() { return nInvalidStart; } USHORT GetInvalidEnd() const { return nInvalidEnd; } USHORT& GetInvalidEnd() { return nInvalidEnd; } void TextInserted( USHORT nPos, USHORT nChars, BOOL bPosIsSep ); void TextDeleted( USHORT nPos, USHORT nChars ); void ResetRanges() { Remove( 0, Count() ); } BOOL HasWrongs() const { return Count() != 0; } void InsertWrong( USHORT nStart, USHORT nEnd, BOOL bClearRange ); BOOL NextWrong( USHORT& rnStart, USHORT& rnEnd ) const; BOOL HasWrong( USHORT nStart, USHORT nEnd ) const; BOOL HasAnyWrong( USHORT nStart, USHORT nEnd ) const; void ClearWrongs( USHORT nStart, USHORT nEnd, const ContentNode* pNode ); void MarkWrongsInvalid(); WrongList* Clone() const; }; inline void WrongList::InsertWrong( const WrongRange& rWrong, USHORT nPos ) { WrongRanges::Insert( rWrong, nPos ); #ifdef DBG_UTIL DBG_ASSERT( !DbgIsBuggy(), "Insert: WrongList kaputt!" ); #endif } class SVX_DLLPUBLIC EdtAutoCorrDoc : public SvxAutoCorrDoc { ImpEditEngine* pImpEE; ContentNode* pCurNode; USHORT nCursor; BOOL bAllowUndoAction; BOOL bUndoAction; protected: void ImplStartUndoAction(); public: EdtAutoCorrDoc( ImpEditEngine* pImpEE, ContentNode* pCurNode, USHORT nCrsr, xub_Unicode cIns ); ~EdtAutoCorrDoc(); virtual BOOL Delete( USHORT nStt, USHORT nEnd ); virtual BOOL Insert( USHORT nPos, const String& rTxt ); virtual BOOL Replace( USHORT nPos, const String& rTxt ); virtual BOOL SetAttr( USHORT nStt, USHORT nEnd, USHORT nSlotId, SfxPoolItem& ); virtual BOOL SetINetAttr( USHORT nStt, USHORT nEnd, const String& rURL ); virtual BOOL HasSymbolChars( USHORT nStt, USHORT nEnd ); virtual const String* GetPrevPara( BOOL bAtNormalPos ); virtual BOOL ChgAutoCorrWord( USHORT& rSttPos, USHORT nEndPos, SvxAutoCorrect& rACorrect, const String** ppPara ); virtual LanguageType GetLanguage( USHORT nPos, BOOL bPrevPara = FALSE ) const; USHORT GetCursor() const { return nCursor; } }; #endif // EDTSPELL <commit_msg>INTEGRATION: CWS aw024 (1.5.196); FILE MERGED 2006/11/10 02:47:30 aw 1.5.196.3: RESYNC: (1.6-1.7); FILE MERGED 2005/09/17 23:49:07 aw 1.5.196.2: RESYNC: (1.5-1.6); FILE MERGED 2005/05/19 12:29:29 aw 1.5.196.1: #i39529#<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: edtspell.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: ihi $ $Date: 2006-11-14 12:36:26 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _EDTSPELL_HXX #define _EDTSPELL_HXX #include <svxbox.hxx> #include <svxenum.hxx> #include <splwrap.hxx> #include <svxacorr.hxx> #ifndef _COM_SUN_STAR_UNO_REFERENCE_H_ #include <com/sun/star/uno/Reference.h> #endif #ifndef INCLUDED_SVXDLLAPI_H #include "svx/svxdllapi.h" #endif namespace com { namespace sun { namespace star { namespace linguistic2 { class XSpellChecker1; }}}} class EditView; class ImpEditEngine; class ContentNode; class EditSpellWrapper : public SvxSpellWrapper { private: EditView* pEditView; void CheckSpellTo(); protected: virtual void SpellStart( SvxSpellArea eArea ); virtual BOOL SpellContinue(); // Bereich pruefen virtual void ReplaceAll( const String &rNewText, INT16 nLanguage ); virtual void SpellEnd(); virtual BOOL SpellMore(); virtual BOOL HasOtherCnt(); virtual void ScrollArea(); virtual void ChangeWord( const String& rNewWord, const USHORT nLang ); virtual void ChangeThesWord( const String& rNewWord ); virtual void AutoCorrect( const String& rOldWord, const String& rNewWord ); public: EditSpellWrapper( Window* pWin, ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XSpellChecker1 > &xChecker, BOOL bIsStart, BOOL bIsAllRight, EditView* pView ); }; struct WrongRange { USHORT nStart; USHORT nEnd; WrongRange( USHORT nS, USHORT nE ) { nStart = nS; nEnd = nE; } }; SV_DECL_VARARR( WrongRanges, WrongRange, 4, 4 ) #define NOT_INVALID 0xFFFF class WrongList : private WrongRanges { private: USHORT nInvalidStart; USHORT nInvalidEnd; BOOL DbgIsBuggy() const; public: WrongList(); ~WrongList(); BOOL IsInvalid() const { return nInvalidStart != NOT_INVALID; } void SetValid() { nInvalidStart = NOT_INVALID; nInvalidEnd = 0; } void MarkInvalid( USHORT nS, USHORT nE ) { if ( ( nInvalidStart == NOT_INVALID ) || ( nInvalidStart > nS ) ) nInvalidStart = nS; if ( nInvalidEnd < nE ) nInvalidEnd = nE; } USHORT Count() const { return WrongRanges::Count(); } // Wenn man weiss was man tut: WrongRange& GetObject( USHORT n ) const { return WrongRanges::GetObject( n ); } void InsertWrong( const WrongRange& rWrong, USHORT nPos ); USHORT GetInvalidStart() const { return nInvalidStart; } USHORT& GetInvalidStart() { return nInvalidStart; } USHORT GetInvalidEnd() const { return nInvalidEnd; } USHORT& GetInvalidEnd() { return nInvalidEnd; } void TextInserted( USHORT nPos, USHORT nChars, BOOL bPosIsSep ); void TextDeleted( USHORT nPos, USHORT nChars ); void ResetRanges() { Remove( 0, Count() ); } BOOL HasWrongs() const { return Count() != 0; } void InsertWrong( USHORT nStart, USHORT nEnd, BOOL bClearRange ); BOOL NextWrong( USHORT& rnStart, USHORT& rnEnd ) const; BOOL HasWrong( USHORT nStart, USHORT nEnd ) const; BOOL HasAnyWrong( USHORT nStart, USHORT nEnd ) const; void ClearWrongs( USHORT nStart, USHORT nEnd, const ContentNode* pNode ); void MarkWrongsInvalid(); WrongList* Clone() const; }; inline void WrongList::InsertWrong( const WrongRange& rWrong, USHORT nPos ) { WrongRanges::Insert( rWrong, nPos ); #ifdef DBG_UTIL DBG_ASSERT( !DbgIsBuggy(), "Insert: WrongList kaputt!" ); #endif } class SVX_DLLPUBLIC EdtAutoCorrDoc : public SvxAutoCorrDoc { ImpEditEngine* pImpEE; ContentNode* pCurNode; USHORT nCursor; BOOL bAllowUndoAction; BOOL bUndoAction; protected: void ImplStartUndoAction(); public: EdtAutoCorrDoc( ImpEditEngine* pImpEE, ContentNode* pCurNode, USHORT nCrsr, xub_Unicode cIns ); ~EdtAutoCorrDoc(); virtual BOOL Delete( USHORT nStt, USHORT nEnd ); virtual BOOL Insert( USHORT nPos, const String& rTxt ); virtual BOOL Replace( USHORT nPos, const String& rTxt ); virtual BOOL SetAttr( USHORT nStt, USHORT nEnd, USHORT nSlotId, SfxPoolItem& ); virtual BOOL SetINetAttr( USHORT nStt, USHORT nEnd, const String& rURL ); virtual BOOL HasSymbolChars( USHORT nStt, USHORT nEnd ); virtual const String* GetPrevPara( BOOL bAtNormalPos ); virtual BOOL ChgAutoCorrWord( USHORT& rSttPos, USHORT nEndPos, SvxAutoCorrect& rACorrect, const String** ppPara ); virtual LanguageType GetLanguage( USHORT nPos, BOOL bPrevPara = FALSE ) const; USHORT GetCursor() const { return nCursor; } }; #endif // EDTSPELL <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: xmleohlp.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: rt $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _XMLEOHLP_HXX #define _XMLEOHLP_HXX #ifndef _CPPUHELPER_COMPBASE2_HXX_ #include <cppuhelper/compbase2.hxx> #endif #ifndef _OSL_MUTEX_HXX_ #include <osl/mutex.hxx> #endif #include <sot/storage.hxx> #include <map> #ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_ #include <com/sun/star/container/XNameContainer.hpp> #endif #ifndef _COM_SUN_STAR_DOCUMENT_XEMBEDDEDOBJECTRESOLVER_HPP_ #include <com/sun/star/document/XEmbeddedObjectResolver.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif // ----------------------------- // - SvXMLEmbeddedObjectHelper - // ----------------------------- enum SvXMLEmbeddedObjectHelperMode { EMBEDDEDOBJECTHELPER_MODE_READ = 0, EMBEDDEDOBJECTHELPER_MODE_WRITE = 1 }; // ----------------------------- // - SvXMLEmbeddedObjectHelper - // ----------------------------- class SfxObjectShell; class SvGlobalName; struct OUStringLess; class OutputStorageWrapper_Impl; class SvXMLEmbeddedObjectHelper : public ::cppu::WeakComponentImplHelper2< ::com::sun::star::document::XEmbeddedObjectResolver, ::com::sun::star::container::XNameAccess > { typedef ::std::map< ::rtl::OUString, OutputStorageWrapper_Impl*, OUStringLess > SvXMLEmbeddedObjectHelper_Impl; private: ::osl::Mutex maMutex; const ::rtl::OUString maReplacementGraphicsContainerStorageName; const ::rtl::OUString maReplacementGraphicsContainerStorageName60; ::rtl::OUString maCurContainerStorageName; com::sun::star::uno::Reference < com::sun::star::embed::XStorage > mxRootStorage; // package SfxObjectShell* mpDocPersist; com::sun::star::uno::Reference < com::sun::star::embed::XStorage > mxContainerStorage; // container sub package for // objects SvXMLEmbeddedObjectHelperMode meCreateMode; SvXMLEmbeddedObjectHelper_Impl *mpStreamMap; void* mpDummy2; sal_Bool ImplGetStorageNames( const ::rtl::OUString& rURLStr, ::rtl::OUString& rContainerStorageName, ::rtl::OUString& rObjectStorageName, sal_Bool bInternalToExternal, sal_Bool *pGraphicRepl=0 ) const; com::sun::star::uno::Reference < com::sun::star::embed::XStorage > ImplGetContainerStorage( const ::rtl::OUString& rStorageName ); String ImplGetUniqueName( SfxObjectShell*, const sal_Char* p ) const; sal_Bool ImplReadObject( const ::rtl::OUString& rContainerStorageName, ::rtl::OUString& rObjName, const SvGlobalName *pClassId, SvStream* pTemp ); ::rtl::OUString ImplInsertEmbeddedObjectURL( const ::rtl::OUString& rURLStr ); protected: SvXMLEmbeddedObjectHelper(); ~SvXMLEmbeddedObjectHelper(); void Init( const com::sun::star::uno::Reference < com::sun::star::embed::XStorage >&, SfxObjectShell& rDocPersist, SvXMLEmbeddedObjectHelperMode eCreateMode ); virtual void SAL_CALL disposing(); public: SvXMLEmbeddedObjectHelper( SfxObjectShell& rDocPersist, SvXMLEmbeddedObjectHelperMode eCreateMode ); static SvXMLEmbeddedObjectHelper* Create( const com::sun::star::uno::Reference < com::sun::star::embed::XStorage >&, SfxObjectShell& rDocPersist, SvXMLEmbeddedObjectHelperMode eCreateMode, sal_Bool bDirect = sal_True ); static SvXMLEmbeddedObjectHelper* Create( SfxObjectShell& rDocPersist, SvXMLEmbeddedObjectHelperMode eCreateMode ); static void Destroy( SvXMLEmbeddedObjectHelper* pSvXMLEmbeddedObjectHelper ); void Flush(); // XEmbeddedObjectResolver virtual ::rtl::OUString SAL_CALL resolveEmbeddedObjectURL( const ::rtl::OUString& aURL ) throw(::com::sun::star::uno::RuntimeException); // XNameAccess virtual ::com::sun::star::uno::Any SAL_CALL getByName( const ::rtl::OUString& aName ) throw (::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getElementNames( ) throw (::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL hasByName( const ::rtl::OUString& aName ) throw (::com::sun::star::uno::RuntimeException); // XNameAccess virtual ::com::sun::star::uno::Type SAL_CALL getElementType( ) throw (::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL hasElements( ) throw (::com::sun::star::uno::RuntimeException); }; #endif <commit_msg>INTEGRATION: CWS visibility01 (1.7.74); FILE MERGED 2005/01/12 07:43:40 mnicel 1.7.74.2: RESYNC: (1.7-1.8); FILE MERGED 2004/12/06 08:11:04 mnicel 1.7.74.1: Part of symbol visibility markup - #i35758#<commit_after>/************************************************************************* * * $RCSfile: xmleohlp.hxx,v $ * * $Revision: 1.9 $ * * last change: $Author: kz $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _XMLEOHLP_HXX #define _XMLEOHLP_HXX #ifndef _CPPUHELPER_COMPBASE2_HXX_ #include <cppuhelper/compbase2.hxx> #endif #ifndef _OSL_MUTEX_HXX_ #include <osl/mutex.hxx> #endif #include <sot/storage.hxx> #include <map> #ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_ #include <com/sun/star/container/XNameContainer.hpp> #endif #ifndef _COM_SUN_STAR_DOCUMENT_XEMBEDDEDOBJECTRESOLVER_HPP_ #include <com/sun/star/document/XEmbeddedObjectResolver.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #ifndef INCLUDED_SVXDLLAPI_H #include "svx/svxdllapi.h" #endif // ----------------------------- // - SvXMLEmbeddedObjectHelper - // ----------------------------- enum SvXMLEmbeddedObjectHelperMode { EMBEDDEDOBJECTHELPER_MODE_READ = 0, EMBEDDEDOBJECTHELPER_MODE_WRITE = 1 }; // ----------------------------- // - SvXMLEmbeddedObjectHelper - // ----------------------------- class SfxObjectShell; class SvGlobalName; struct OUStringLess; class OutputStorageWrapper_Impl; class SVX_DLLPUBLIC SvXMLEmbeddedObjectHelper : public ::cppu::WeakComponentImplHelper2< ::com::sun::star::document::XEmbeddedObjectResolver, ::com::sun::star::container::XNameAccess > { typedef ::std::map< ::rtl::OUString, OutputStorageWrapper_Impl*, OUStringLess > SvXMLEmbeddedObjectHelper_Impl; private: ::osl::Mutex maMutex; const ::rtl::OUString maReplacementGraphicsContainerStorageName; const ::rtl::OUString maReplacementGraphicsContainerStorageName60; ::rtl::OUString maCurContainerStorageName; com::sun::star::uno::Reference < com::sun::star::embed::XStorage > mxRootStorage; // package SfxObjectShell* mpDocPersist; com::sun::star::uno::Reference < com::sun::star::embed::XStorage > mxContainerStorage; // container sub package for // objects SvXMLEmbeddedObjectHelperMode meCreateMode; SvXMLEmbeddedObjectHelper_Impl *mpStreamMap; void* mpDummy2; SVX_DLLPRIVATE sal_Bool ImplGetStorageNames( const ::rtl::OUString& rURLStr, ::rtl::OUString& rContainerStorageName, ::rtl::OUString& rObjectStorageName, sal_Bool bInternalToExternal, sal_Bool *pGraphicRepl=0 ) const; SVX_DLLPRIVATE com::sun::star::uno::Reference < com::sun::star::embed::XStorage > ImplGetContainerStorage( const ::rtl::OUString& rStorageName ); SVX_DLLPRIVATE String ImplGetUniqueName( SfxObjectShell*, const sal_Char* p ) const; SVX_DLLPRIVATE sal_Bool ImplReadObject( const ::rtl::OUString& rContainerStorageName, ::rtl::OUString& rObjName, const SvGlobalName *pClassId, SvStream* pTemp ); SVX_DLLPRIVATE ::rtl::OUString ImplInsertEmbeddedObjectURL( const ::rtl::OUString& rURLStr ); protected: SvXMLEmbeddedObjectHelper(); ~SvXMLEmbeddedObjectHelper(); void Init( const com::sun::star::uno::Reference < com::sun::star::embed::XStorage >&, SfxObjectShell& rDocPersist, SvXMLEmbeddedObjectHelperMode eCreateMode ); virtual void SAL_CALL disposing(); public: SvXMLEmbeddedObjectHelper( SfxObjectShell& rDocPersist, SvXMLEmbeddedObjectHelperMode eCreateMode ); static SvXMLEmbeddedObjectHelper* Create( const com::sun::star::uno::Reference < com::sun::star::embed::XStorage >&, SfxObjectShell& rDocPersist, SvXMLEmbeddedObjectHelperMode eCreateMode, sal_Bool bDirect = sal_True ); static SvXMLEmbeddedObjectHelper* Create( SfxObjectShell& rDocPersist, SvXMLEmbeddedObjectHelperMode eCreateMode ); static void Destroy( SvXMLEmbeddedObjectHelper* pSvXMLEmbeddedObjectHelper ); void Flush(); // XEmbeddedObjectResolver virtual ::rtl::OUString SAL_CALL resolveEmbeddedObjectURL( const ::rtl::OUString& aURL ) throw(::com::sun::star::uno::RuntimeException); // XNameAccess virtual ::com::sun::star::uno::Any SAL_CALL getByName( const ::rtl::OUString& aName ) throw (::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getElementNames( ) throw (::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL hasByName( const ::rtl::OUString& aName ) throw (::com::sun::star::uno::RuntimeException); // XNameAccess virtual ::com::sun::star::uno::Type SAL_CALL getElementType( ) throw (::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL hasElements( ) throw (::com::sun::star::uno::RuntimeException); }; #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: printdata.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: hr $ $Date: 2006-08-14 15:29:41 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SW_PRINTDATA_HXX #define _SW_PRINTDATA_HXX #ifndef _SAL_TYPES_H_ #include <sal/types.h> #endif #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif struct SwPrintData { sal_Bool bPrintGraphic, bPrintTable, bPrintDraw, bPrintControl, bPrintPageBackground, bPrintBlackFont, bPrintLeftPage, bPrintRightPage, bPrintReverse, bPrintProspect, bPrintSingleJobs, bPaperFromSetup, // --> FME 2005-12-13 #b6354161# Print empty pages bPrintEmptyPages, // <-- // #i56195# no field update while printing mail merge documents bUpdateFieldsInPrinting, bModified; sal_Int16 nPrintPostIts; rtl::OUString sFaxName; SwPrintData() { bPrintGraphic = bPrintTable = bPrintDraw = bPrintControl = bPrintLeftPage = bPrintRightPage = bPrintPageBackground = bPrintEmptyPages = bUpdateFieldsInPrinting = sal_True; bPaperFromSetup = bPrintReverse = bPrintProspect = bPrintSingleJobs = bModified = bPrintBlackFont = sal_False; nPrintPostIts = 0; } sal_Bool operator==(const SwPrintData& rData)const { return bPrintGraphic == rData.bPrintGraphic && bPrintTable == rData.bPrintTable && bPrintDraw == rData.bPrintDraw && bPrintControl == rData.bPrintControl && bPrintPageBackground== rData.bPrintPageBackground&& bPrintBlackFont == rData.bPrintBlackFont && bPrintLeftPage == rData.bPrintLeftPage && bPrintRightPage == rData.bPrintRightPage && bPrintReverse == rData.bPrintReverse && bPrintProspect == rData.bPrintProspect && bPrintSingleJobs == rData.bPrintSingleJobs && bPaperFromSetup == rData.bPaperFromSetup && bPrintEmptyPages == rData.bPrintEmptyPages && bUpdateFieldsInPrinting == rData.bUpdateFieldsInPrinting && nPrintPostIts == rData.nPrintPostIts && sFaxName == rData.sFaxName; } sal_Bool IsPrintGraphic() const { return bPrintGraphic; } sal_Bool IsPrintTable() const { return bPrintTable; } sal_Bool IsPrintDraw() const { return bPrintDraw; } sal_Bool IsPrintControl() const { return bPrintControl; } sal_Bool IsPrintLeftPage() const { return bPrintLeftPage; } sal_Bool IsPrintRightPage() const { return bPrintRightPage; } sal_Bool IsPrintReverse() const { return bPrintReverse; } sal_Bool IsPaperFromSetup() const { return bPaperFromSetup; } sal_Bool IsPrintEmptyPages() const{ return bPrintEmptyPages; } sal_Bool IsPrintProspect() const { return bPrintProspect; } sal_Bool IsPrintPageBackground() const { return bPrintPageBackground; } sal_Bool IsPrintBlackFont() const { return bPrintBlackFont;} sal_Bool IsPrintSingleJobs() const { return bPrintSingleJobs;} sal_Int16 GetPrintPostIts() const { return nPrintPostIts; } const rtl::OUString GetFaxName() const{return sFaxName;} void SetPrintGraphic ( sal_Bool b ) { doSetModified(); bPrintGraphic = b;} void SetPrintTable ( sal_Bool b ) { doSetModified(); bPrintTable = b;} void SetPrintDraw ( sal_Bool b ) { doSetModified(); bPrintDraw = b;} void SetPrintControl ( sal_Bool b ) { doSetModified(); bPrintControl = b; } void SetPrintLeftPage ( sal_Bool b ) { doSetModified(); bPrintLeftPage = b;} void SetPrintRightPage( sal_Bool b ) { doSetModified(); bPrintRightPage = b;} void SetPrintReverse ( sal_Bool b ) { doSetModified(); bPrintReverse = b;} void SetPaperFromSetup( sal_Bool b ) { doSetModified(); bPaperFromSetup = b;} void SetPrintEmptyPages(sal_Bool b ) { doSetModified(); bPrintEmptyPages = b;} void SetPrintPostIts ( sal_Int16 n){ doSetModified(); nPrintPostIts = n; } void SetPrintProspect ( sal_Bool b ) { doSetModified(); bPrintProspect = b; } void SetPrintPageBackground(sal_Bool b){ doSetModified(); bPrintPageBackground = b;} void SetPrintBlackFont(sal_Bool b){ doSetModified(); bPrintBlackFont = b;} void SetPrintSingleJobs(sal_Bool b){ doSetModified(); bPrintSingleJobs = b;} void SetFaxName(const rtl::OUString& rSet){sFaxName = rSet;} virtual void doSetModified () { bModified = sal_True;} }; #endif //_SW_PRINTDATA_HXX <commit_msg>INTEGRATION: CWS os93 (1.7.220); FILE MERGED 2007/02/09 10:49:23 os 1.7.220.1: #i30518# brochure printing in RTL mode<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: printdata.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: rt $ $Date: 2007-04-03 13:46:03 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SW_PRINTDATA_HXX #define _SW_PRINTDATA_HXX #ifndef _SAL_TYPES_H_ #include <sal/types.h> #endif #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif struct SwPrintData { sal_Bool bPrintGraphic, bPrintTable, bPrintDraw, bPrintControl, bPrintPageBackground, bPrintBlackFont, bPrintLeftPage, bPrintRightPage, bPrintReverse, bPrintProspect, bPrintProspect_RTL, bPrintSingleJobs, bPaperFromSetup, // --> FME 2005-12-13 #b6354161# Print empty pages bPrintEmptyPages, // <-- // #i56195# no field update while printing mail merge documents bUpdateFieldsInPrinting, bModified; sal_Int16 nPrintPostIts; rtl::OUString sFaxName; SwPrintData() { bPrintGraphic = bPrintTable = bPrintDraw = bPrintControl = bPrintLeftPage = bPrintRightPage = bPrintPageBackground = bPrintEmptyPages = bUpdateFieldsInPrinting = sal_True; bPaperFromSetup = bPrintReverse = bPrintProspect = bPrintProspect_RTL = bPrintSingleJobs = bModified = bPrintBlackFont = sal_False; nPrintPostIts = 0; } sal_Bool operator==(const SwPrintData& rData)const { return bPrintGraphic == rData.bPrintGraphic && bPrintTable == rData.bPrintTable && bPrintDraw == rData.bPrintDraw && bPrintControl == rData.bPrintControl && bPrintPageBackground== rData.bPrintPageBackground&& bPrintBlackFont == rData.bPrintBlackFont && bPrintLeftPage == rData.bPrintLeftPage && bPrintRightPage == rData.bPrintRightPage && bPrintReverse == rData.bPrintReverse && bPrintProspect == rData.bPrintProspect && bPrintProspect_RTL == rData.bPrintProspect_RTL && bPrintSingleJobs == rData.bPrintSingleJobs && bPaperFromSetup == rData.bPaperFromSetup && bPrintEmptyPages == rData.bPrintEmptyPages && bUpdateFieldsInPrinting == rData.bUpdateFieldsInPrinting && nPrintPostIts == rData.nPrintPostIts && sFaxName == rData.sFaxName; } sal_Bool IsPrintGraphic() const { return bPrintGraphic; } sal_Bool IsPrintTable() const { return bPrintTable; } sal_Bool IsPrintDraw() const { return bPrintDraw; } sal_Bool IsPrintControl() const { return bPrintControl; } sal_Bool IsPrintLeftPage() const { return bPrintLeftPage; } sal_Bool IsPrintRightPage() const { return bPrintRightPage; } sal_Bool IsPrintReverse() const { return bPrintReverse; } sal_Bool IsPaperFromSetup() const { return bPaperFromSetup; } sal_Bool IsPrintEmptyPages() const{ return bPrintEmptyPages; } sal_Bool IsPrintProspect() const { return bPrintProspect; } sal_Bool IsPrintProspect_RTL() const { return bPrintProspect_RTL; } sal_Bool IsPrintPageBackground() const { return bPrintPageBackground; } sal_Bool IsPrintBlackFont() const { return bPrintBlackFont;} sal_Bool IsPrintSingleJobs() const { return bPrintSingleJobs;} sal_Int16 GetPrintPostIts() const { return nPrintPostIts; } const rtl::OUString GetFaxName() const{return sFaxName;} void SetPrintGraphic ( sal_Bool b ) { doSetModified(); bPrintGraphic = b;} void SetPrintTable ( sal_Bool b ) { doSetModified(); bPrintTable = b;} void SetPrintDraw ( sal_Bool b ) { doSetModified(); bPrintDraw = b;} void SetPrintControl ( sal_Bool b ) { doSetModified(); bPrintControl = b; } void SetPrintLeftPage ( sal_Bool b ) { doSetModified(); bPrintLeftPage = b;} void SetPrintRightPage( sal_Bool b ) { doSetModified(); bPrintRightPage = b;} void SetPrintReverse ( sal_Bool b ) { doSetModified(); bPrintReverse = b;} void SetPaperFromSetup( sal_Bool b ) { doSetModified(); bPaperFromSetup = b;} void SetPrintEmptyPages(sal_Bool b ) { doSetModified(); bPrintEmptyPages = b;} void SetPrintPostIts ( sal_Int16 n){ doSetModified(); nPrintPostIts = n; } void SetPrintProspect ( sal_Bool b ) { doSetModified(); bPrintProspect = b; } void SetPrintPageBackground(sal_Bool b){ doSetModified(); bPrintPageBackground = b;} void SetPrintBlackFont(sal_Bool b){ doSetModified(); bPrintBlackFont = b;} void SetPrintSingleJobs(sal_Bool b){ doSetModified(); bPrintSingleJobs = b;} void SetFaxName(const rtl::OUString& rSet){sFaxName = rSet;} virtual void doSetModified () { bModified = sal_True;} }; #endif //_SW_PRINTDATA_HXX <|endoftext|>
<commit_before>/* SWARM Copyright (C) 2012-2021 Torbjorn Rognes and Frederic Mahe This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Contact: Torbjorn Rognes <torognes@ifi.uio.no>, Department of Informatics, University of Oslo, PO Box 1080 Blindern, NO-0316 Oslo, Norway */ #include "swarm.h" int64_t SCORELIMIT_8; int64_t SCORELIMIT_16; unsigned char * score_matrix_8 = nullptr; unsigned short * score_matrix_16 = nullptr; int64_t * score_matrix_63 = nullptr; void score_matrix_read(); #if 0 /* never used */ void score_matrix_dump() { fprintf(logfile, " "); for(auto i = 0; i < 16; i++) fprintf(logfile, "%2d", i); fprintf(logfile, "\n"); fprintf(logfile, " "); for(auto i = 0; i < 16; i++) fprintf(logfile, " %c", sym_nt[i]); fprintf(logfile, "\n"); for(auto i = 0; i < 16; i++) { fprintf(logfile, "%2d %c ", i, sym_nt[i]); for(auto j = 0; j < 16; j++) { fprintf(logfile, "%2" PRId64, score_matrix_63[(i<<5) + j]); } fprintf(logfile, "\n"); } } #endif void score_matrix_read() { constexpr int cells {32}; constexpr long long int one_thousand {1000}; constexpr unsigned int multiplier {5}; long long int sc {0}; long long int hi {-one_thousand}; long long int lo {one_thousand}; score_matrix_8 = static_cast<unsigned char *>(xmalloc(cells * cells * sizeof(char))); score_matrix_16 = static_cast<unsigned short *>(xmalloc(cells * cells * sizeof(short))); score_matrix_63 = static_cast<int64_t *>(xmalloc(cells * cells * sizeof(int64_t))); for(auto a = 0; a < cells / 2; a++) { for(auto b = 0; b < cells / 2; b++) { sc = ((a == b) && (a > 0) && (b > 0)) ? 0 : penalty_mismatch; // sc = (a==b) ? matchscore : mismatchscore; if (sc < lo) { lo = sc; } if (sc > hi) { hi = sc; } score_matrix_63[(a << multiplier) + b] = sc; } } SCORELIMIT_8 = UINT8_MAX + 1 - hi; SCORELIMIT_16 = UINT16_MAX + 1 - hi; for(auto a = 0; a < cells; a++) { for(auto b = 0; b < cells; b++) { sc = score_matrix_63[(a << multiplier) + b]; score_matrix_8[(a << multiplier) + b] = static_cast<unsigned char>(sc); score_matrix_16[(a << multiplier) + b] = static_cast<unsigned short>(sc); } } } void score_matrix_init() { score_matrix_read(); // score_matrix_dump(); } void score_matrix_free() { xfree(score_matrix_8); score_matrix_8 = nullptr; xfree(score_matrix_16); score_matrix_16 = nullptr; xfree(score_matrix_63); score_matrix_63 = nullptr; } <commit_msg>SCORELIMIT: only used in score_matrix_read(), reduce scope<commit_after>/* SWARM Copyright (C) 2012-2021 Torbjorn Rognes and Frederic Mahe This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Contact: Torbjorn Rognes <torognes@ifi.uio.no>, Department of Informatics, University of Oslo, PO Box 1080 Blindern, NO-0316 Oslo, Norway */ #include "swarm.h" unsigned char * score_matrix_8 = nullptr; unsigned short * score_matrix_16 = nullptr; int64_t * score_matrix_63 = nullptr; void score_matrix_read(); #if 0 /* never used */ void score_matrix_dump() { fprintf(logfile, " "); for(auto i = 0; i < 16; i++) fprintf(logfile, "%2d", i); fprintf(logfile, "\n"); fprintf(logfile, " "); for(auto i = 0; i < 16; i++) fprintf(logfile, " %c", sym_nt[i]); fprintf(logfile, "\n"); for(auto i = 0; i < 16; i++) { fprintf(logfile, "%2d %c ", i, sym_nt[i]); for(auto j = 0; j < 16; j++) { fprintf(logfile, "%2" PRId64, score_matrix_63[(i<<5) + j]); } fprintf(logfile, "\n"); } } #endif void score_matrix_read() { constexpr int cells {32}; constexpr long long int one_thousand {1000}; constexpr unsigned int multiplier {5}; long long int sc {0}; long long int hi {-one_thousand}; long long int lo {one_thousand}; int64_t SCORELIMIT_8; int64_t SCORELIMIT_16; score_matrix_8 = static_cast<unsigned char *>(xmalloc(cells * cells * sizeof(char))); score_matrix_16 = static_cast<unsigned short *>(xmalloc(cells * cells * sizeof(short))); score_matrix_63 = static_cast<int64_t *>(xmalloc(cells * cells * sizeof(int64_t))); for(auto a = 0; a < cells / 2; a++) { for(auto b = 0; b < cells / 2; b++) { sc = ((a == b) && (a > 0) && (b > 0)) ? 0 : penalty_mismatch; // sc = (a==b) ? matchscore : mismatchscore; if (sc < lo) { lo = sc; } if (sc > hi) { hi = sc; } score_matrix_63[(a << multiplier) + b] = sc; } } SCORELIMIT_8 = UINT8_MAX + 1 - hi; SCORELIMIT_16 = UINT16_MAX + 1 - hi; for(auto a = 0; a < cells; a++) { for(auto b = 0; b < cells; b++) { sc = score_matrix_63[(a << multiplier) + b]; score_matrix_8[(a << multiplier) + b] = static_cast<unsigned char>(sc); score_matrix_16[(a << multiplier) + b] = static_cast<unsigned short>(sc); } } } void score_matrix_init() { score_matrix_read(); // score_matrix_dump(); } void score_matrix_free() { xfree(score_matrix_8); score_matrix_8 = nullptr; xfree(score_matrix_16); score_matrix_16 = nullptr; xfree(score_matrix_63); score_matrix_63 = nullptr; } <|endoftext|>
<commit_before>#ifndef CELL_AUTOMATA_ISING_SPIN_BASE #define CELL_AUTOMATA_ISING_SPIN_BASE #include <array> template<typename value_T, std::size_t partner_Num> class Spin_base { public: using state_type = value_T; using base_pointer = Spin_base*; using const_base_pointer = const Spin_base*; using partners_list_type = std::array<const_base_pointer, partner_Num>; Spin_base(state_type s):state(s){} virtual void step() = 0; virtual void set_partners(const partners_list_type&) = 0; state_type get() const { return state; } void set(state_type s) { state = s; return; } protected: state_type state; partners_list_type partners; }; #endif /* CELL_AUTOMATA_ISING_SPIN */ <commit_msg>add virtual func reset_state().<commit_after>#ifndef CELL_AUTOMATA_ISING_SPIN_BASE #define CELL_AUTOMATA_ISING_SPIN_BASE #include <array> template<typename value_T, std::size_t partner_Num> class Spin_base { public: using state_type = value_T; using base_pointer = Spin_base*; using const_base_pointer = const Spin_base*; using partners_list_type = std::array<const_base_pointer, partner_Num>; Spin_base(state_type s):state(s){} virtual void step() = 0; virtual void set_partners(const partners_list_type&) = 0; virtual void reset_state() = 0; state_type get() const { return state; } void set(state_type s) { state = s; return; } protected: state_type state; partners_list_type partners; }; #endif /* CELL_AUTOMATA_ISING_SPIN */ <|endoftext|>
<commit_before>// Copyright (c) 2008 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. // Performs basic inspection of the disk cache files with minimal disruption // to the actual files (they still may change if an error is detected on the // files). #include <stdio.h> #include <string> #include "base/file_util.h" #include "base/message_loop.h" #include "net/base/file_stream.h" #include "net/disk_cache/block_files.h" #include "net/disk_cache/disk_format.h" #include "net/disk_cache/mapped_file.h" #include "net/disk_cache/storage_block.h" namespace { const wchar_t kIndexName[] = L"index"; const wchar_t kDataPrefix[] = L"data_"; // Reads the |header_size| bytes from the beginning of file |name|. bool ReadHeader(const std::wstring name, char* header, int header_size) { net::FileStream file; file.Open(name, base::PLATFORM_FILE_OPEN | base::PLATFORM_FILE_READ); if (!file.IsOpen()) { printf("Unable to open file %ls\n", name.c_str()); return false; } int read = file.Read(header, header_size, NULL); if (read != header_size) { printf("Unable to read file %ls\n", name.c_str()); return false; } return true; } int GetMajorVersionFromFile(const std::wstring name) { disk_cache::IndexHeader header; if (!ReadHeader(name, reinterpret_cast<char*>(&header), sizeof(header))) return 0; return header.version >> 16; } // Dumps the contents of the Index-file header. void DumpIndexHeader(const std::wstring name) { disk_cache::IndexHeader header; if (!ReadHeader(name, reinterpret_cast<char*>(&header), sizeof(header))) return; printf("Index file:\n"); printf("magic: %x\n", header.magic); printf("version: %d.%d\n", header.version >> 16, header.version & 0xffff); printf("entries: %d\n", header.num_entries); printf("total bytes: %d\n", header.num_bytes); printf("last file number: %d\n", header.last_file); printf("current id: %d\n", header.this_id); printf("table length: %d\n", header.table_len); printf("last crash: %d\n", header.crash); printf("experiment: %d\n", header.experiment); for (int i = 0; i < 5; i++) { printf("head %d: 0x%x\n", i, header.lru.heads[i]); printf("tail %d: 0x%x\n", i, header.lru.tails[i]); } printf("transaction: 0x%x\n", header.lru.transaction); printf("operation: %d\n", header.lru.operation); printf("operation list: %d\n", header.lru.operation_list); printf("-------------------------\n\n"); } // Dumps the contents of a block-file header. void DumpBlockHeader(const std::wstring name) { disk_cache::BlockFileHeader header; if (!ReadHeader(name, reinterpret_cast<char*>(&header), sizeof(header))) return; std::wstring file_name = file_util::GetFilenameFromPath(name); printf("Block file: %ls\n", file_name.c_str()); printf("magic: %x\n", header.magic); printf("version: %d.%d\n", header.version >> 16, header.version & 0xffff); printf("file id: %d\n", header.this_file); printf("next file id: %d\n", header.next_file); printf("entry size: %d\n", header.entry_size); printf("current entries: %d\n", header.num_entries); printf("max entries: %d\n", header.max_entries); printf("updating: %d\n", header.updating); printf("empty sz 1: %d\n", header.empty[0]); printf("empty sz 2: %d\n", header.empty[1]); printf("empty sz 3: %d\n", header.empty[2]); printf("empty sz 4: %d\n", header.empty[3]); printf("user 0: 0x%x\n", header.user[0]); printf("user 1: 0x%x\n", header.user[1]); printf("user 2: 0x%x\n", header.user[2]); printf("user 3: 0x%x\n", header.user[3]); printf("-------------------------\n\n"); } // Simple class that interacts with the set of cache files. class CacheDumper { public: explicit CacheDumper(const std::wstring path) : path_(path), block_files_(path), index_(NULL) {} bool Init(); // Reads an entry from disk. Return false when all entries have been already // returned. bool GetEntry(disk_cache::EntryStore* entry); // Loads a specific block from the block files. bool LoadEntry(disk_cache::CacheAddr addr, disk_cache::EntryStore* entry); bool LoadRankings(disk_cache::CacheAddr addr, disk_cache::RankingsNode* rankings); private: std::wstring path_; disk_cache::BlockFiles block_files_; scoped_refptr<disk_cache::MappedFile> index_file_; disk_cache::Index* index_; int current_hash_; disk_cache::CacheAddr next_addr_; DISALLOW_COPY_AND_ASSIGN(CacheDumper); }; bool CacheDumper::Init() { if (!block_files_.Init(false)) { printf("Unable to init block files\n"); return false; } std::wstring index_name(path_); file_util::AppendToPath(&index_name, kIndexName); index_file_ = new disk_cache::MappedFile; index_ = reinterpret_cast<disk_cache::Index*>(index_file_->Init(index_name, 0)); if (!index_) { printf("Unable to map index\n"); return false; } current_hash_ = 0; next_addr_ = 0; return true; } bool CacheDumper::GetEntry(disk_cache::EntryStore* entry) { if (next_addr_) { if (LoadEntry(next_addr_, entry)) { next_addr_ = entry->next; if (!next_addr_) current_hash_++; return true; } else { printf("Unable to load entry at address 0x%x\n", next_addr_); next_addr_ = 0; current_hash_++; } } for (int i = current_hash_; i < index_->header.table_len; i++) { // Yes, we'll crash if the table is shorter than expected, but only after // dumping every entry that we can find. if (index_->table[i]) { current_hash_ = i; if (LoadEntry(index_->table[i], entry)) { next_addr_ = entry->next; if (!next_addr_) current_hash_++; return true; } else { printf("Unable to load entry at address 0x%x\n", index_->table[i]); } } } return false; } bool CacheDumper::LoadEntry(disk_cache::CacheAddr addr, disk_cache::EntryStore* entry) { disk_cache::Addr address(addr); disk_cache::MappedFile* file = block_files_.GetFile(address); if (!file) return false; disk_cache::CacheEntryBlock entry_block(file, address); if (!entry_block.Load()) return false; memcpy(entry, entry_block.Data(), sizeof(*entry)); printf("Entry at 0x%x\n", addr); return true; } bool CacheDumper::LoadRankings(disk_cache::CacheAddr addr, disk_cache::RankingsNode* rankings) { disk_cache::Addr address(addr); disk_cache::MappedFile* file = block_files_.GetFile(address); if (!file) return false; disk_cache::CacheRankingsBlock rank_block(file, address); if (!rank_block.Load()) return false; memcpy(rankings, rank_block.Data(), sizeof(*rankings)); printf("Rankings at 0x%x\n", addr); return true; } void DumpEntry(const disk_cache::EntryStore& entry) { std::string key; if (!entry.long_key) { key = entry.key; if (key.size() > 50) key.resize(50); } printf("hash: 0x%x\n", entry.hash); printf("next entry: 0x%x\n", entry.next); printf("rankings: 0x%x\n", entry.rankings_node); printf("key length: %d\n", entry.key_len); printf("key: \"%s\"\n", key.c_str()); printf("key addr: 0x%x\n", entry.long_key); printf("reuse count: %d\n", entry.reuse_count); printf("refetch count: %d\n", entry.refetch_count); printf("state: %d\n", entry.state); for (int i = 0; i < 4; i++) { printf("data size %d: %d\n", i, entry.data_size[i]); printf("data addr %d: 0x%x\n", i, entry.data_addr[i]); } printf("----------\n\n"); } void DumpRankings(const disk_cache::RankingsNode& rankings) { printf("next: 0x%x\n", rankings.next); printf("prev: 0x%x\n", rankings.prev); printf("entry: 0x%x\n", rankings.contents); printf("dirty: %d\n", rankings.dirty); printf("pointer: 0x%x\n", rankings.pointer); printf("----------\n\n"); } } // namespace. // ----------------------------------------------------------------------- int GetMajorVersion(const std::wstring input_path) { std::wstring index_name(input_path); file_util::AppendToPath(&index_name, kIndexName); int version = GetMajorVersionFromFile(index_name); if (!version) return 0; std::wstring data_name(input_path); file_util::AppendToPath(&data_name, L"data_0"); if (version != GetMajorVersionFromFile(data_name)) return 0; data_name = input_path; file_util::AppendToPath(&data_name, L"data_1"); if (version != GetMajorVersionFromFile(data_name)) return 0; return version; } // Dumps the headers of all files. int DumpHeaders(const std::wstring input_path) { std::wstring index_name(input_path); file_util::AppendToPath(&index_name, kIndexName); DumpIndexHeader(index_name); std::wstring pattern(kDataPrefix); pattern.append(L"*"); file_util::FileEnumerator iter(FilePath::FromWStringHack(input_path), false, file_util::FileEnumerator::FILES, pattern); for (std::wstring file = iter.Next().ToWStringHack(); !file.empty(); file = iter.Next().ToWStringHack()) { DumpBlockHeader(file); } return 0; } // Dumps all entries from the cache. int DumpContents(const std::wstring input_path) { DumpHeaders(input_path); // We need a message loop, although we really don't run any task. MessageLoop loop(MessageLoop::TYPE_IO); CacheDumper dumper(input_path); if (!dumper.Init()) return -1; disk_cache::EntryStore entry; while (dumper.GetEntry(&entry)) { DumpEntry(entry); disk_cache::RankingsNode rankings; if (dumper.LoadRankings(entry.rankings_node, &rankings)) DumpRankings(rankings); } printf("Done.\n"); return 0; } <commit_msg>Fix compile error in dump_files (didn't catch the error since dump_cache isn't in chrome.sln).<commit_after>// Copyright (c) 2008 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. // Performs basic inspection of the disk cache files with minimal disruption // to the actual files (they still may change if an error is detected on the // files). #include <stdio.h> #include <string> #include "base/file_util.h" #include "base/message_loop.h" #include "net/base/file_stream.h" #include "net/disk_cache/block_files.h" #include "net/disk_cache/disk_format.h" #include "net/disk_cache/mapped_file.h" #include "net/disk_cache/storage_block.h" namespace { const wchar_t kIndexName[] = L"index"; const wchar_t kDataPrefix[] = L"data_"; // Reads the |header_size| bytes from the beginning of file |name|. bool ReadHeader(const std::wstring name, char* header, int header_size) { net::FileStream file; file.Open(FilePath::FromWStringHack(name), base::PLATFORM_FILE_OPEN | base::PLATFORM_FILE_READ); if (!file.IsOpen()) { printf("Unable to open file %ls\n", name.c_str()); return false; } int read = file.Read(header, header_size, NULL); if (read != header_size) { printf("Unable to read file %ls\n", name.c_str()); return false; } return true; } int GetMajorVersionFromFile(const std::wstring name) { disk_cache::IndexHeader header; if (!ReadHeader(name, reinterpret_cast<char*>(&header), sizeof(header))) return 0; return header.version >> 16; } // Dumps the contents of the Index-file header. void DumpIndexHeader(const std::wstring name) { disk_cache::IndexHeader header; if (!ReadHeader(name, reinterpret_cast<char*>(&header), sizeof(header))) return; printf("Index file:\n"); printf("magic: %x\n", header.magic); printf("version: %d.%d\n", header.version >> 16, header.version & 0xffff); printf("entries: %d\n", header.num_entries); printf("total bytes: %d\n", header.num_bytes); printf("last file number: %d\n", header.last_file); printf("current id: %d\n", header.this_id); printf("table length: %d\n", header.table_len); printf("last crash: %d\n", header.crash); printf("experiment: %d\n", header.experiment); for (int i = 0; i < 5; i++) { printf("head %d: 0x%x\n", i, header.lru.heads[i]); printf("tail %d: 0x%x\n", i, header.lru.tails[i]); } printf("transaction: 0x%x\n", header.lru.transaction); printf("operation: %d\n", header.lru.operation); printf("operation list: %d\n", header.lru.operation_list); printf("-------------------------\n\n"); } // Dumps the contents of a block-file header. void DumpBlockHeader(const std::wstring name) { disk_cache::BlockFileHeader header; if (!ReadHeader(name, reinterpret_cast<char*>(&header), sizeof(header))) return; std::wstring file_name = file_util::GetFilenameFromPath(name); printf("Block file: %ls\n", file_name.c_str()); printf("magic: %x\n", header.magic); printf("version: %d.%d\n", header.version >> 16, header.version & 0xffff); printf("file id: %d\n", header.this_file); printf("next file id: %d\n", header.next_file); printf("entry size: %d\n", header.entry_size); printf("current entries: %d\n", header.num_entries); printf("max entries: %d\n", header.max_entries); printf("updating: %d\n", header.updating); printf("empty sz 1: %d\n", header.empty[0]); printf("empty sz 2: %d\n", header.empty[1]); printf("empty sz 3: %d\n", header.empty[2]); printf("empty sz 4: %d\n", header.empty[3]); printf("user 0: 0x%x\n", header.user[0]); printf("user 1: 0x%x\n", header.user[1]); printf("user 2: 0x%x\n", header.user[2]); printf("user 3: 0x%x\n", header.user[3]); printf("-------------------------\n\n"); } // Simple class that interacts with the set of cache files. class CacheDumper { public: explicit CacheDumper(const std::wstring path) : path_(path), block_files_(path), index_(NULL) {} bool Init(); // Reads an entry from disk. Return false when all entries have been already // returned. bool GetEntry(disk_cache::EntryStore* entry); // Loads a specific block from the block files. bool LoadEntry(disk_cache::CacheAddr addr, disk_cache::EntryStore* entry); bool LoadRankings(disk_cache::CacheAddr addr, disk_cache::RankingsNode* rankings); private: std::wstring path_; disk_cache::BlockFiles block_files_; scoped_refptr<disk_cache::MappedFile> index_file_; disk_cache::Index* index_; int current_hash_; disk_cache::CacheAddr next_addr_; DISALLOW_COPY_AND_ASSIGN(CacheDumper); }; bool CacheDumper::Init() { if (!block_files_.Init(false)) { printf("Unable to init block files\n"); return false; } std::wstring index_name(path_); file_util::AppendToPath(&index_name, kIndexName); index_file_ = new disk_cache::MappedFile; index_ = reinterpret_cast<disk_cache::Index*>(index_file_->Init(index_name, 0)); if (!index_) { printf("Unable to map index\n"); return false; } current_hash_ = 0; next_addr_ = 0; return true; } bool CacheDumper::GetEntry(disk_cache::EntryStore* entry) { if (next_addr_) { if (LoadEntry(next_addr_, entry)) { next_addr_ = entry->next; if (!next_addr_) current_hash_++; return true; } else { printf("Unable to load entry at address 0x%x\n", next_addr_); next_addr_ = 0; current_hash_++; } } for (int i = current_hash_; i < index_->header.table_len; i++) { // Yes, we'll crash if the table is shorter than expected, but only after // dumping every entry that we can find. if (index_->table[i]) { current_hash_ = i; if (LoadEntry(index_->table[i], entry)) { next_addr_ = entry->next; if (!next_addr_) current_hash_++; return true; } else { printf("Unable to load entry at address 0x%x\n", index_->table[i]); } } } return false; } bool CacheDumper::LoadEntry(disk_cache::CacheAddr addr, disk_cache::EntryStore* entry) { disk_cache::Addr address(addr); disk_cache::MappedFile* file = block_files_.GetFile(address); if (!file) return false; disk_cache::CacheEntryBlock entry_block(file, address); if (!entry_block.Load()) return false; memcpy(entry, entry_block.Data(), sizeof(*entry)); printf("Entry at 0x%x\n", addr); return true; } bool CacheDumper::LoadRankings(disk_cache::CacheAddr addr, disk_cache::RankingsNode* rankings) { disk_cache::Addr address(addr); disk_cache::MappedFile* file = block_files_.GetFile(address); if (!file) return false; disk_cache::CacheRankingsBlock rank_block(file, address); if (!rank_block.Load()) return false; memcpy(rankings, rank_block.Data(), sizeof(*rankings)); printf("Rankings at 0x%x\n", addr); return true; } void DumpEntry(const disk_cache::EntryStore& entry) { std::string key; if (!entry.long_key) { key = entry.key; if (key.size() > 50) key.resize(50); } printf("hash: 0x%x\n", entry.hash); printf("next entry: 0x%x\n", entry.next); printf("rankings: 0x%x\n", entry.rankings_node); printf("key length: %d\n", entry.key_len); printf("key: \"%s\"\n", key.c_str()); printf("key addr: 0x%x\n", entry.long_key); printf("reuse count: %d\n", entry.reuse_count); printf("refetch count: %d\n", entry.refetch_count); printf("state: %d\n", entry.state); for (int i = 0; i < 4; i++) { printf("data size %d: %d\n", i, entry.data_size[i]); printf("data addr %d: 0x%x\n", i, entry.data_addr[i]); } printf("----------\n\n"); } void DumpRankings(const disk_cache::RankingsNode& rankings) { printf("next: 0x%x\n", rankings.next); printf("prev: 0x%x\n", rankings.prev); printf("entry: 0x%x\n", rankings.contents); printf("dirty: %d\n", rankings.dirty); printf("pointer: 0x%x\n", rankings.pointer); printf("----------\n\n"); } } // namespace. // ----------------------------------------------------------------------- int GetMajorVersion(const std::wstring input_path) { std::wstring index_name(input_path); file_util::AppendToPath(&index_name, kIndexName); int version = GetMajorVersionFromFile(index_name); if (!version) return 0; std::wstring data_name(input_path); file_util::AppendToPath(&data_name, L"data_0"); if (version != GetMajorVersionFromFile(data_name)) return 0; data_name = input_path; file_util::AppendToPath(&data_name, L"data_1"); if (version != GetMajorVersionFromFile(data_name)) return 0; return version; } // Dumps the headers of all files. int DumpHeaders(const std::wstring input_path) { std::wstring index_name(input_path); file_util::AppendToPath(&index_name, kIndexName); DumpIndexHeader(index_name); std::wstring pattern(kDataPrefix); pattern.append(L"*"); file_util::FileEnumerator iter(FilePath::FromWStringHack(input_path), false, file_util::FileEnumerator::FILES, pattern); for (std::wstring file = iter.Next().ToWStringHack(); !file.empty(); file = iter.Next().ToWStringHack()) { DumpBlockHeader(file); } return 0; } // Dumps all entries from the cache. int DumpContents(const std::wstring input_path) { DumpHeaders(input_path); // We need a message loop, although we really don't run any task. MessageLoop loop(MessageLoop::TYPE_IO); CacheDumper dumper(input_path); if (!dumper.Init()) return -1; disk_cache::EntryStore entry; while (dumper.GetEntry(&entry)) { DumpEntry(entry); disk_cache::RankingsNode rankings; if (dumper.LoadRankings(entry.rankings_node, &rankings)) DumpRankings(rankings); } printf("Done.\n"); return 0; } <|endoftext|>
<commit_before>/** This is a tool shipped by 'Aleph - A Library for Exploring Persistent Homology'. Given a set of patches from a database of images, this tool performs the pre-processing steps of the corresponding point cloud. Mainly, a procedure from the paper *On the Local Behavior of Spaces of Natural Images* by Gunnar Carlsson et al. is followed. */ #include <aleph/containers/PointCloud.hh> #include <aleph/math/KahanSummation.hh> #include <algorithm> #include <iostream> #include <iterator> #include <string> #include <cmath> using DataType = float; using PointCloud = aleph::containers::PointCloud<DataType>; template <class T> T log( T x ) { if( x == T() ) return T(); else return std::log10( x ); } template <class InputIterator> DataType contrastNorm( InputIterator begin, InputIterator end ) { using T = typename std::iterator_traits<InputIterator>::value_type; std::vector<T> data( begin, end ); unsigned n = static_cast<unsigned>( std::sqrt( data.size() ) ); aleph::math::KahanSummation<T> difference = T(); for( unsigned i = 0; i < n; i++ ) { for( unsigned j = 0; j < n; j++ ) { auto index = n * i + j; if( j+1 < n ) difference += std::pow( data.at(index) - data.at(index+1), T(2) ); if( j >= 1 ) difference += std::pow( data.at(index) - data.at(index-1), T(2) ); if( i+1 < n ) difference += std::pow( data.at(index) - data.at(index+n), T(2) ); if( i-1 < n ) difference += std::pow( data.at(index) - data.at(index-n), T(2) ); } } return static_cast<DataType>( difference ); } int main( int argc, char** argv ) { if( argc <= 1 ) return -1; // Input ------------------------------------------------------------- // // This tool assumes that the input is already in the form of a point // cloud, containing the 'raw' image patches. std::string filename = argv[1]; std::cerr << "* Loading input point cloud..."; PointCloud pointCloud = aleph::containers::load<DataType>( filename ); std::cerr << "finished\n"; // Pre-processing ---------------------------------------------------- // // 1. Replace values by their logarithm // 2. Subtract mean // 3. Normalize by the contrast norm std::cerr << "* Pre-processing..."; using IndexType = decltype( pointCloud.size() ); PointCloud processedPointCloud = PointCloud( pointCloud.size(), pointCloud.dimension() ); std::vector<DataType> contrastNorms; contrastNorms.reserve( pointCloud.size() ); for( IndexType i = 0; i < pointCloud.size(); i++ ) { auto p = pointCloud[i]; std::transform( p.begin(), p.end(), p.begin(), [] ( DataType x ) { return log( x ); } ); auto mean = aleph::math::accumulate_kahan_sorted( p.begin(), p.end(), DataType() ); mean /= static_cast<DataType>( pointCloud.dimension() ); std::transform( p.begin(), p.end(), p.begin(), [&mean] ( DataType x ) { return x - mean; } ); auto norm = contrastNorm( p.begin(), p.end() ); contrastNorms.push_back( norm ); if( norm > DataType() ) { std::transform( p.begin(), p.end(), p.begin(), [&norm] ( DataType x ) { return x / norm; } ); } processedPointCloud.set( i, p.begin(), p.end() ); } std::cerr << "finished\n"; // Filter patches based on norm -------------------------------------- // // In the original paper, only the top 20% of the contrast norms are // being kept. This tool uses a configurable threshold. std::cerr << "* Filtering..."; { auto contrastNorms_ = contrastNorms; double contrastNormThreshold = 0.20; // TODO: make configurable std::sort( contrastNorms_.begin(), contrastNorms_.end() ); auto threshold = contrastNorms_.at( std::size_t( std::ceil( (1.0 - contrastNormThreshold) * double( contrastNorms.size() ) ) ) ); auto numRemainingPatches = std::count_if( contrastNorms.begin(), contrastNorms.end(), [&threshold] ( DataType norm ) { return norm >= threshold; } ); PointCloud filteredPointCloud( numRemainingPatches, pointCloud.dimension() ); IndexType j = 0; for( std::size_t i = 0; i < contrastNorms.size(); i++ ) { if( contrastNorms.at(i) >= threshold ) { auto p = processedPointCloud[i]; filteredPointCloud.set( j++, p.begin(), p.end() ); } } swap( processedPointCloud, filteredPointCloud ); } std::cerr << "finished\n"; // Further processing ------------------------------------------------ // // 1. Subtract the mean of the normalized vectors in order to make // different images better comparable. // // 2. Divide by the Euclidean norm of the vector to place them on // a high-dimensional sphere. std::cerr << "* Final processing and normalization..."; for( IndexType i = 0; i < pointCloud.size(); i++ ) { auto p = processedPointCloud[i]; auto mean = aleph::math::accumulate_kahan_sorted( p.begin(), p.end(), DataType() ); mean /= static_cast<DataType>( pointCloud.dimension() ); std::transform( p.begin(), p.end(), p.begin(), [&mean] ( DataType x ) { return x - mean; } ); auto norm = std::sqrt( std::inner_product( p.begin(), p.end(), p.begin(), 0 ) ); std::transform( p.begin(), p.end(), p.begin(), [&norm] ( DataType x ) { return x / norm; } ); } std::cerr << "finished\n"; } <commit_msg>Added output of processed point cloud<commit_after>/** This is a tool shipped by 'Aleph - A Library for Exploring Persistent Homology'. Given a set of patches from a database of images, this tool performs the pre-processing steps of the corresponding point cloud. Mainly, a procedure from the paper *On the Local Behavior of Spaces of Natural Images* by Gunnar Carlsson et al. is followed. */ #include <aleph/containers/PointCloud.hh> #include <aleph/math/KahanSummation.hh> #include <algorithm> #include <iostream> #include <iterator> #include <numeric> #include <string> #include <cmath> using DataType = float; using PointCloud = aleph::containers::PointCloud<DataType>; template <class T> T log( T x ) { if( x == T() ) return T(); else return std::log10( x ); } template <class InputIterator> DataType contrastNorm( InputIterator begin, InputIterator end ) { using T = typename std::iterator_traits<InputIterator>::value_type; std::vector<T> data( begin, end ); unsigned n = static_cast<unsigned>( std::sqrt( data.size() ) ); aleph::math::KahanSummation<T> difference = T(); for( unsigned i = 0; i < n; i++ ) { for( unsigned j = 0; j < n; j++ ) { auto index = n * i + j; if( j+1 < n ) difference += std::pow( data.at(index) - data.at(index+1), T(2) ); if( j >= 1 ) difference += std::pow( data.at(index) - data.at(index-1), T(2) ); if( i+1 < n ) difference += std::pow( data.at(index) - data.at(index+n), T(2) ); if( i-1 < n ) difference += std::pow( data.at(index) - data.at(index-n), T(2) ); } } return static_cast<DataType>( difference ); } int main( int argc, char** argv ) { if( argc <= 1 ) return -1; // Input ------------------------------------------------------------- // // This tool assumes that the input is already in the form of a point // cloud, containing the 'raw' image patches. std::string filename = argv[1]; std::cerr << "* Loading input point cloud..."; PointCloud pointCloud = aleph::containers::load<DataType>( filename ); std::cerr << "finished\n"; // Pre-processing ---------------------------------------------------- // // 1. Replace values by their logarithm // 2. Subtract mean // 3. Normalize by the contrast norm std::cerr << "* Pre-processing..."; using IndexType = decltype( pointCloud.size() ); PointCloud processedPointCloud = PointCloud( pointCloud.size(), pointCloud.dimension() ); std::vector<DataType> contrastNorms; contrastNorms.reserve( pointCloud.size() ); for( IndexType i = 0; i < pointCloud.size(); i++ ) { auto p = pointCloud[i]; std::transform( p.begin(), p.end(), p.begin(), [] ( DataType x ) { return log( x ); } ); auto mean = aleph::math::accumulate_kahan_sorted( p.begin(), p.end(), DataType() ); mean /= static_cast<DataType>( pointCloud.dimension() ); std::transform( p.begin(), p.end(), p.begin(), [&mean] ( DataType x ) { return x - mean; } ); auto norm = contrastNorm( p.begin(), p.end() ); contrastNorms.push_back( norm ); if( norm > DataType() ) { std::transform( p.begin(), p.end(), p.begin(), [&norm] ( DataType x ) { return x / norm; } ); } processedPointCloud.set( i, p.begin(), p.end() ); } std::cerr << "finished\n"; // Filter patches based on norm -------------------------------------- // // In the original paper, only the top 20% of the contrast norms are // being kept. This tool uses a configurable threshold. std::cerr << "* Filtering..."; { auto contrastNorms_ = contrastNorms; double contrastNormThreshold = 0.20; // TODO: make configurable std::sort( contrastNorms_.begin(), contrastNorms_.end() ); auto threshold = contrastNorms_.at( std::size_t( std::ceil( (1.0 - contrastNormThreshold) * double( contrastNorms.size() ) ) ) ); auto numRemainingPatches = std::count_if( contrastNorms.begin(), contrastNorms.end(), [&threshold] ( DataType norm ) { return norm >= threshold; } ); PointCloud filteredPointCloud( numRemainingPatches, pointCloud.dimension() ); IndexType j = 0; for( std::size_t i = 0; i < contrastNorms.size(); i++ ) { if( contrastNorms.at(i) >= threshold ) { auto p = processedPointCloud[i]; filteredPointCloud.set( j++, p.begin(), p.end() ); } } swap( processedPointCloud, filteredPointCloud ); } std::cerr << "finished\n"; // Further processing ------------------------------------------------ // // 1. Subtract the mean of the normalized vectors in order to make // different images better comparable. // // 2. Divide by the Euclidean norm of the vector to place them on // a high-dimensional sphere. std::cerr << "* Final processing and normalization..."; for( IndexType i = 0; i < pointCloud.size(); i++ ) { auto p = processedPointCloud[i]; auto mean = aleph::math::accumulate_kahan_sorted( p.begin(), p.end(), DataType() ); mean /= static_cast<DataType>( pointCloud.dimension() ); std::transform( p.begin(), p.end(), p.begin(), [&mean] ( DataType x ) { return x - mean; } ); auto norm = std::sqrt( std::inner_product( p.begin(), p.end(), p.begin(), 0 ) ); std::transform( p.begin(), p.end(), p.begin(), [&norm] ( DataType x ) { return x / norm; } ); processedPointCloud.set( i, p.begin(), p.end() ); } std::cerr << "finished\n"; // Output ------------------------------------------------------------ std::cerr << "* Processed point cloud has " << processedPointCloud.size() << " points\n"; std::cout << processedPointCloud << "\n"; } <|endoftext|>
<commit_before>#include "Math/Cartesian3D.h" #include "Math/Math_vectypes.hxx" #include "RandomNumberEngine.h" #include "benchmark/benchmark.h" #include <sstream> // FIXME: Reduce the boilerplate code of each benchmark. Maybe setting up a Benchmark Fixture will help. static void BM_Cartesian3D_Sanity(benchmark::State &state) { // Report if we forgot to turn on the explicit vectorisation in ROOT. if (sizeof(double) == sizeof(ROOT::Double_v) || sizeof(float) == sizeof(ROOT::Float_v)) state.SkipWithError("Explicit vectorisation is disabled!"); } BENCHMARK(BM_Cartesian3D_Sanity); static void BM_Cartesian3D_CreateEmpty(benchmark::State &state) { while (state.KeepRunning()) ROOT::Math::Cartesian3D<ROOT::Double_v> c; } BENCHMARK(BM_Cartesian3D_CreateEmpty); static void ComputeProcessedEntities(benchmark::State &state, size_t Size, double checksum) { const size_t items_processed = state.iterations() * state.range(0); state.SetItemsProcessed(items_processed); state.SetBytesProcessed(items_processed * Size); std::stringstream ss; ss << checksum; state.SetLabel(ss.str()); } template <typename T> static void BM_Cartesian3D_Theta(benchmark::State &state) { using namespace ROOT::Benchmark; // We want the same random numbers for a benchmark family. SetSeed(1); // Allocate N points constexpr size_t VecSize = TypeSize<T>::Get(); typename Data<T>::Vector Points(state.range(0) / VecSize); ROOT::Math::Cartesian3D<T> c; T checksum = T(); while (state.KeepRunning()) { checksum = T(); for (auto &p : Points) { c.SetCoordinates(p.X, p.Y, p.Z); checksum += c.Theta(); } } ComputeProcessedEntities(state, sizeof(T), VecTraits<T>::Sum(checksum)); } BENCHMARK_TEMPLATE(BM_Cartesian3D_Theta, double)->Range(8 << 10, 8 << 20); BENCHMARK_TEMPLATE(BM_Cartesian3D_Theta, ROOT::Double_v)->Range(8 << 10, 8 << 20); // BENCHMARK_TEMPLATE(BM_Cartesian3D_Theta, float)->Range(8 << 10, 8 << 20); // BENCHMARK_TEMPLATE(BM_Cartesian3D_Theta, ROOT::Float_v)->Range(8 << 10, 8 << 20); template <typename T> static void BM_Cartesian3D_Phi(benchmark::State &state) { using namespace ROOT::Benchmark; // We want the same random numbers for a benchmark family. SetSeed(2); // Allocate N points constexpr size_t VecSize = TypeSize<T>::Get(); typename Data<T>::Vector Points(state.range(0) / VecSize); ROOT::Math::Cartesian3D<T> c; T checksum = T(); while (state.KeepRunning()) { checksum = T(); for (auto &p : Points) { c.SetCoordinates(p.X, p.Y, p.Z); checksum += c.Phi(); } } ComputeProcessedEntities(state, sizeof(T), VecTraits<T>::Sum(checksum)); } BENCHMARK_TEMPLATE(BM_Cartesian3D_Phi, double)->Range(8 << 10, 8 << 20); BENCHMARK_TEMPLATE(BM_Cartesian3D_Phi, ROOT::Double_v)->Range(8 << 10, 8 << 20); // BENCHMARK_TEMPLATE(BM_Cartesian3D_Phi, float)->Range(8 << 10, 8 << 20); // BENCHMARK_TEMPLATE(BM_Cartesian3D_Phi, ROOT::Float_v)->Range(8 << 10, 8 << 20); template <typename T> static void BM_Cartesian3D_Mag2(benchmark::State &state) { using namespace ROOT::Benchmark; // We want the same random numbers for a benchmark family. SetSeed(3); // Allocate N points constexpr size_t VecSize = TypeSize<T>::Get(); typename Data<T>::Vector Points(state.range(0) / VecSize); ROOT::Math::Cartesian3D<T> c; T checksum = T(); while (state.KeepRunning()) { checksum = T(); for (auto &p : Points) { c.SetCoordinates(p.X, p.Y, p.Z); checksum += c.Mag2(); } } ComputeProcessedEntities(state, sizeof(T), VecTraits<T>::Sum(checksum)); } BENCHMARK_TEMPLATE(BM_Cartesian3D_Mag2, double)->Range(8 << 10, 8 << 20); BENCHMARK_TEMPLATE(BM_Cartesian3D_Mag2, ROOT::Double_v)->Range(8 << 10, 8 << 20); // BENCHMARK_TEMPLATE(BM_Cartesian3D_Mag2, float)->Range(8 << 10, 8 << 20); // BENCHMARK_TEMPLATE(BM_Cartesian3D_Mag2, ROOT::Float_v)->Range(8 << 10, 8 << 20); template <typename T> static void BM_Cartesian3D_Scale(benchmark::State &state) { using namespace ROOT::Benchmark; // We want the same random numbers for a benchmark family. SetSeed(4); // Allocate N points constexpr size_t VecSize = TypeSize<T>::Get(); typename Data<T>::Vector Points(state.range(0) / VecSize); ROOT::Math::Cartesian3D<T> c; T checksum = T(); while (state.KeepRunning()) { checksum = T(); for (auto &p : Points) { c.SetCoordinates(p.X, p.Y, p.Z); c.Scale(p.X); checksum += c.x() + c.y() + c.z(); } } ComputeProcessedEntities(state, sizeof(T), VecTraits<T>::Sum(checksum)); } BENCHMARK_TEMPLATE(BM_Cartesian3D_Scale, double)->Range(8 << 10, 8 << 20); BENCHMARK_TEMPLATE(BM_Cartesian3D_Scale, ROOT::Double_v)->Range(8 << 10, 8 << 20); // Define our main. BENCHMARK_MAIN(); <commit_msg>Revert "Benchmark Scale."<commit_after>#include "Math/Cartesian3D.h" #include "Math/Math_vectypes.hxx" #include "RandomNumberEngine.h" #include "benchmark/benchmark.h" #include <sstream> // FIXME: Reduce the boilerplate code of each benchmark. Maybe setting up a Benchmark Fixture will help. static void BM_Cartesian3D_Sanity(benchmark::State &state) { // Report if we forgot to turn on the explicit vectorisation in ROOT. if (sizeof(double) == sizeof(ROOT::Double_v) || sizeof(float) == sizeof(ROOT::Float_v)) state.SkipWithError("Explicit vectorisation is disabled!"); } BENCHMARK(BM_Cartesian3D_Sanity); static void BM_Cartesian3D_CreateEmpty(benchmark::State &state) { while (state.KeepRunning()) ROOT::Math::Cartesian3D<ROOT::Double_v> c; } BENCHMARK(BM_Cartesian3D_CreateEmpty); static void ComputeProcessedEntities(benchmark::State &state, size_t Size, double checksum) { const size_t items_processed = state.iterations() * state.range(0); state.SetItemsProcessed(items_processed); state.SetBytesProcessed(items_processed * Size); std::stringstream ss; ss << checksum; state.SetLabel(ss.str()); } template <typename T> static void BM_Cartesian3D_Theta(benchmark::State &state) { using namespace ROOT::Benchmark; // We want the same random numbers for a benchmark family. SetSeed(1); // Allocate N points constexpr size_t VecSize = TypeSize<T>::Get(); typename Data<T>::Vector Points(state.range(0) / VecSize); ROOT::Math::Cartesian3D<T> c; T checksum = T(); while (state.KeepRunning()) { checksum = T(); for (auto &p : Points) { c.SetCoordinates(p.X, p.Y, p.Z); checksum += c.Theta(); } } ComputeProcessedEntities(state, sizeof(T), VecTraits<T>::Sum(checksum)); } BENCHMARK_TEMPLATE(BM_Cartesian3D_Theta, double)->Range(8 << 10, 8 << 20); BENCHMARK_TEMPLATE(BM_Cartesian3D_Theta, ROOT::Double_v)->Range(8 << 10, 8 << 20); // BENCHMARK_TEMPLATE(BM_Cartesian3D_Theta, float)->Range(8 << 10, 8 << 20); // BENCHMARK_TEMPLATE(BM_Cartesian3D_Theta, ROOT::Float_v)->Range(8 << 10, 8 << 20); template <typename T> static void BM_Cartesian3D_Phi(benchmark::State &state) { using namespace ROOT::Benchmark; // We want the same random numbers for a benchmark family. SetSeed(2); // Allocate N points constexpr size_t VecSize = TypeSize<T>::Get(); typename Data<T>::Vector Points(state.range(0) / VecSize); ROOT::Math::Cartesian3D<T> c; T checksum = T(); while (state.KeepRunning()) { checksum = T(); for (auto &p : Points) { c.SetCoordinates(p.X, p.Y, p.Z); checksum += c.Phi(); } } ComputeProcessedEntities(state, sizeof(T), VecTraits<T>::Sum(checksum)); } BENCHMARK_TEMPLATE(BM_Cartesian3D_Phi, double)->Range(8 << 10, 8 << 20); BENCHMARK_TEMPLATE(BM_Cartesian3D_Phi, ROOT::Double_v)->Range(8 << 10, 8 << 20); // BENCHMARK_TEMPLATE(BM_Cartesian3D_Phi, float)->Range(8 << 10, 8 << 20); // BENCHMARK_TEMPLATE(BM_Cartesian3D_Phi, ROOT::Float_v)->Range(8 << 10, 8 << 20); template <typename T> static void BM_Cartesian3D_Mag2(benchmark::State &state) { using namespace ROOT::Benchmark; // We want the same random numbers for a benchmark family. SetSeed(3); // Allocate N points constexpr size_t VecSize = TypeSize<T>::Get(); typename Data<T>::Vector Points(state.range(0) / VecSize); ROOT::Math::Cartesian3D<T> c; T checksum = T(); while (state.KeepRunning()) { checksum = T(); for (auto &p : Points) { c.SetCoordinates(p.X, p.Y, p.Z); checksum += c.Mag2(); } } ComputeProcessedEntities(state, sizeof(T), VecTraits<T>::Sum(checksum)); } BENCHMARK_TEMPLATE(BM_Cartesian3D_Mag2, double)->Range(8 << 10, 8 << 20); BENCHMARK_TEMPLATE(BM_Cartesian3D_Mag2, ROOT::Double_v)->Range(8 << 10, 8 << 20); // BENCHMARK_TEMPLATE(BM_Cartesian3D_Mag2, float)->Range(8 << 10, 8 << 20); // BENCHMARK_TEMPLATE(BM_Cartesian3D_Mag2, ROOT::Float_v)->Range(8 << 10, 8 << 20); // Define our main. BENCHMARK_MAIN(); <|endoftext|>
<commit_before><commit_msg>initialize the OpenGL context as soon as possible<commit_after><|endoftext|>
<commit_before>#ifndef STUFF_GRID_HH_INCLUDED #define STUFF_GRID_HH_INCLUDED #include "math.hh" #include "misc.hh" #include "static_assert.hh" #include <dune/common/fvector.hh> #include <dune/grid/common/geometry.hh> #include <vector> #include <boost/format.hpp> namespace Stuff { /** * \brief calculates length of given intersection in world coordinates * \tparam IntersectionType * IntersectionType * \param[in] intersection * intersection * \return length of intersection **/ template < class IntersectionType > double getLenghtOfIntersection( const IntersectionType& intersection ) { typedef typename IntersectionType::Geometry IntersectionGeometryType; const IntersectionGeometryType& intersectionGeoemtry = intersection.intersectionGlobal(); return intersectionGeoemtry.volume(); } /** \brief grid statistic output to given stream \todo not require a space to be passed */ template < class GridPartType, class DiscreteFunctionSpaceType, class OutStream > void printGridInformation( GridPartType& gridPart, DiscreteFunctionSpaceType& space, OutStream& out ) { int numberOfEntities( 0 ); int numberOfIntersections( 0 ); int numberOfInnerIntersections( 0 ); int numberOfBoundaryIntersections( 0 ); double maxGridWidth( 0.0 ); typedef typename GridPartType::GridType GridType; typedef typename GridType::template Codim< 0 >::Entity EntityType; typedef typename GridPartType::template Codim< 0 >::IteratorType EntityIteratorType; typedef typename GridPartType::IntersectionIteratorType IntersectionIteratorType; EntityIteratorType entityItEndLog = space.end(); for ( EntityIteratorType entityItLog = space.begin(); entityItLog != entityItEndLog; ++entityItLog ) { const EntityType& entity = *entityItLog; // count entities ++numberOfEntities; // walk the intersections IntersectionIteratorType intItEnd = gridPart.iend( entity ); for ( IntersectionIteratorType intIt = gridPart.ibegin( entity ); intIt != intItEnd; ++intIt ) { // count intersections ++numberOfIntersections; maxGridWidth = std::max( Stuff::getLenghtOfIntersection( intIt ), maxGridWidth ); // if we are inside the grid if ( intIt.neighbor() && !intIt.boundary() ) { // count inner intersections ++numberOfInnerIntersections; } // if we are on the boundary of the grid if ( !intIt.neighbor() && intIt.boundary() ) { // count boundary intersections ++numberOfBoundaryIntersections; } } } out << "found " << numberOfEntities << " entities," << std::endl; out << "found " << numberOfIntersections << " intersections," << std::endl; out << " " << numberOfInnerIntersections << " intersections inside and" << std::endl; out << " " << numberOfBoundaryIntersections << " intersections on the boundary." << std::endl; out << " maxGridWidth is " << maxGridWidth << std::endl; } //! Base class for Gridwalk Functors that don't want to reimplement pre/postWalk struct GridwalkFunctorDefault { void preWalk() const{} void postWalk()const{} }; /** \brief lets you apply a Functor to each entity \todo not require a space to be passed \todo allow stacking of operators to save gridwalks \todo threadsafe maps (haha:P) */ template < class GridView, int codim = 0 > class GridWalk { private: typedef typename GridView::template Codim<0>::Iterator ElementIterator; typedef typename GridView::IntersectionIterator IntersectionIteratorType; typedef typename IntersectionIteratorType::EntityPointer EntityPointer; public: GridWalk ( const GridView& gp ) : gridView_( gp ) { unsigned int en_idx = 0; for (ElementIterator it = gridView_.template begin<0>(); it!=gridView_.template end<0>(); ++it,++en_idx) { entityIdxMap_.push_back( *it ); } } template < class Functor > void operator () ( Functor& f ) const { f.preWalk(); for (ElementIterator it = gridView_.template begin<0>(); it!=gridView_.template end<0>(); ++it) { const int ent_idx = getIdx( entityIdxMap_, *it ); f( *it, *it, ent_idx, ent_idx); IntersectionIteratorType intItEnd = gridView_.iend( *it ); for ( IntersectionIteratorType intIt = gridView_.ibegin( *it ); intIt != intItEnd; ++intIt ) { if ( !intIt.boundary() ) { const int neigh_idx = getIdx( entityIdxMap_, intIt.outside() ); f( *it, *intIt.outside(), ent_idx, neigh_idx); } } } f.postWalk(); } template < class Functor > void walkCodim0( Functor& f ) const { for (ElementIterator it = gridView_.template begin<0>(); it!=gridView_.template end<0>(); ++it) { const int ent_idx = getIdx( entityIdxMap_, *it ); f( *it, ent_idx ); } } private: const GridView& gridView_; typedef std::vector< EntityPointer > EntityIdxMap; EntityIdxMap entityIdxMap_; }; //! gets barycenter of given geometry in local coordinates template < class GeometryType > Dune::FieldVector< typename GeometryType::ctype, GeometryType::mydimension > getBarycenterLocal( const GeometryType& geometry ) { assert( geometry.corners() > 0 ); Dune::FieldVector< typename GeometryType::ctype, GeometryType::mydimension > center; for( int i = 0; i < geometry.corners(); ++i ) { center += geometry.local( geometry[i] ); } center /= geometry.corners(); return center; } //! gets barycenter of given geometry in global coordinates template < class GeometryType > Dune::FieldVector< typename GeometryType::ctype, GeometryType::coorddimension > getBarycenterGlobal( const GeometryType& geometry ) { assert( geometry.corners() > 0 ); Dune::FieldVector< typename GeometryType::ctype, GeometryType::coorddimension > center; for( int i = 0; i < geometry.corners(); ++i ) { center += geometry[i] ; } center /= geometry.corners(); return center; } template < class GridType > struct GridDimensions { typedef MinMaxAvg<typename GridType::ctype> MinMaxAvgType; typedef Dune::array< MinMaxAvgType, GridType::dimensionworld > CoordLimitsType; CoordLimitsType coord_limits; MinMaxAvgType entity_volume; struct GridDimensionsFunctor { CoordLimitsType& coord_limits_; MinMaxAvgType& entity_volume_; GridDimensionsFunctor( CoordLimitsType& c, MinMaxAvgType& e ):coord_limits_(c),entity_volume_(e){} template <class Entity> void operator() ( const Entity& ent, const int /*ent_idx*/ ) { typedef typename Entity::Geometry EntityGeometryType; typedef Dune::FieldVector< typename EntityGeometryType::ctype, EntityGeometryType::coorddimension> DomainType; const typename Entity::Geometry& geo = ent.geometry(); entity_volume_( geo.volume() ); for ( int i = 0; i < geo.corners(); ++i ) { const DomainType& corner( geo.corner( i ) ); for ( size_t k = 0; k < GridType::dimensionworld; ++k ) coord_limits_[k]( corner[k] ); } } }; double volumeRelation() const { return entity_volume.min() != 0.0 ? entity_volume.max() / entity_volume.min() : -1; } GridDimensions( const GridType& grid ) { typedef typename GridType::LeafGridView View; const View& view = grid.leafView(); GridDimensionsFunctor f( coord_limits, entity_volume ); GridWalk<View>( view ).walkCodim0( f ); } }; template <class Stream, class T> inline Stream& operator<< (Stream& s, const GridDimensions<T>& d ) { for ( size_t k = 0; k < T::dimensionworld; ++k ) { const typename GridDimensions<T>::MinMaxAvgType& mma = d.coord_limits[k]; s << boost::format( "x%d\tmin: %e\tavg: %e\tmax: %e\n" ) % k % mma.min() % mma.average() % mma.max(); } s << boost::format("Entity vol min: %e\tavg: %e\tmax: %e\tQout: %e") % d.entity_volume.min() % d.entity_volume.average() % d.entity_volume.max() % d.volumeRelation(); s << std::endl; return s; } template < class GridType > struct MaximumEntityVolumeRefineFunctor { MaximumEntityVolumeRefineFunctor ( GridType& grid, double volume, double factor ) :threshold_volume_( volume * factor ), grid_(grid) {} template <class Entity> void operator() ( const Entity& ent, const int /*ent_idx*/ ) { const double volume = ent.geometry().volume(); if ( volume > threshold_volume_ ) grid_.mark( 1, ent ); } const double threshold_volume_; GridType& grid_; }; //! refine entities until all have volume < size_factor * unrefined_minimum_volume template < class GridType > void EnforceMaximumEntityVolume( GridType& grid, const double size_factor ) { const GridDimensions<GridType> unrefined_dimensions( grid ); const double unrefined_min_volume = unrefined_dimensions.entity_volume.min(); typedef typename GridType::LeafGridView View; View view = grid.leafView(); MaximumEntityVolumeRefineFunctor<GridType> f( grid, unrefined_min_volume, size_factor ); while ( true ) { grid.preAdapt(); GridWalk<View>( view ).walkCodim0( f ); if ( !grid.adapt() ) break; grid.postAdapt(); std::cout << Stuff::GridDimensions<GridType>( grid ); } } template < int dim, class GridImp, template<int,int,class> class EntityImp > double geometryDiameter( const Dune::Entity< 0, dim, GridImp, EntityImp >& entity ) { static_assert(dim==2,"not implemented"); typedef Dune::Entity< 0, dim, GridImp, EntityImp > EntityType; typedef typename EntityType::LeafIntersectionIterator IntersectionIteratorType; IntersectionIteratorType end = entity.ileafend(); double factor = 1.0; for ( IntersectionIteratorType it = entity.ileafbegin(); it != end ; ++it ) { const typename IntersectionIteratorType::Intersection& intersection = *it; factor *= intersection.intersectionGlobal().volume(); } return factor/(2.0*entity.geometry().volume()); } }//end namespace #endif <commit_msg>[grid] prototype gemotrydiameter for 3D<commit_after>#ifndef STUFF_GRID_HH_INCLUDED #define STUFF_GRID_HH_INCLUDED #include "math.hh" #include "misc.hh" #include "static_assert.hh" #include <dune/common/fvector.hh> #include <dune/grid/common/geometry.hh> #include <vector> #include <boost/format.hpp> namespace Stuff { /** * \brief calculates length of given intersection in world coordinates * \tparam IntersectionType * IntersectionType * \param[in] intersection * intersection * \return length of intersection **/ template < class IntersectionType > double getLenghtOfIntersection( const IntersectionType& intersection ) { typedef typename IntersectionType::Geometry IntersectionGeometryType; const IntersectionGeometryType& intersectionGeoemtry = intersection.intersectionGlobal(); return intersectionGeoemtry.volume(); } /** \brief grid statistic output to given stream \todo not require a space to be passed */ template < class GridPartType, class DiscreteFunctionSpaceType, class OutStream > void printGridInformation( GridPartType& gridPart, DiscreteFunctionSpaceType& space, OutStream& out ) { int numberOfEntities( 0 ); int numberOfIntersections( 0 ); int numberOfInnerIntersections( 0 ); int numberOfBoundaryIntersections( 0 ); double maxGridWidth( 0.0 ); typedef typename GridPartType::GridType GridType; typedef typename GridType::template Codim< 0 >::Entity EntityType; typedef typename GridPartType::template Codim< 0 >::IteratorType EntityIteratorType; typedef typename GridPartType::IntersectionIteratorType IntersectionIteratorType; EntityIteratorType entityItEndLog = space.end(); for ( EntityIteratorType entityItLog = space.begin(); entityItLog != entityItEndLog; ++entityItLog ) { const EntityType& entity = *entityItLog; // count entities ++numberOfEntities; // walk the intersections IntersectionIteratorType intItEnd = gridPart.iend( entity ); for ( IntersectionIteratorType intIt = gridPart.ibegin( entity ); intIt != intItEnd; ++intIt ) { // count intersections ++numberOfIntersections; maxGridWidth = std::max( Stuff::getLenghtOfIntersection( intIt ), maxGridWidth ); // if we are inside the grid if ( intIt.neighbor() && !intIt.boundary() ) { // count inner intersections ++numberOfInnerIntersections; } // if we are on the boundary of the grid if ( !intIt.neighbor() && intIt.boundary() ) { // count boundary intersections ++numberOfBoundaryIntersections; } } } out << "found " << numberOfEntities << " entities," << std::endl; out << "found " << numberOfIntersections << " intersections," << std::endl; out << " " << numberOfInnerIntersections << " intersections inside and" << std::endl; out << " " << numberOfBoundaryIntersections << " intersections on the boundary." << std::endl; out << " maxGridWidth is " << maxGridWidth << std::endl; } //! Base class for Gridwalk Functors that don't want to reimplement pre/postWalk struct GridwalkFunctorDefault { void preWalk() const{} void postWalk()const{} }; /** \brief lets you apply a Functor to each entity \todo not require a space to be passed \todo allow stacking of operators to save gridwalks \todo threadsafe maps (haha:P) */ template < class GridView, int codim = 0 > class GridWalk { private: typedef typename GridView::template Codim<0>::Iterator ElementIterator; typedef typename GridView::IntersectionIterator IntersectionIteratorType; typedef typename IntersectionIteratorType::EntityPointer EntityPointer; public: GridWalk ( const GridView& gp ) : gridView_( gp ) { unsigned int en_idx = 0; for (ElementIterator it = gridView_.template begin<0>(); it!=gridView_.template end<0>(); ++it,++en_idx) { entityIdxMap_.push_back( *it ); } } template < class Functor > void operator () ( Functor& f ) const { f.preWalk(); for (ElementIterator it = gridView_.template begin<0>(); it!=gridView_.template end<0>(); ++it) { const int ent_idx = getIdx( entityIdxMap_, *it ); f( *it, *it, ent_idx, ent_idx); IntersectionIteratorType intItEnd = gridView_.iend( *it ); for ( IntersectionIteratorType intIt = gridView_.ibegin( *it ); intIt != intItEnd; ++intIt ) { if ( !intIt.boundary() ) { const int neigh_idx = getIdx( entityIdxMap_, intIt.outside() ); f( *it, *intIt.outside(), ent_idx, neigh_idx); } } } f.postWalk(); } template < class Functor > void walkCodim0( Functor& f ) const { for (ElementIterator it = gridView_.template begin<0>(); it!=gridView_.template end<0>(); ++it) { const int ent_idx = getIdx( entityIdxMap_, *it ); f( *it, ent_idx ); } } private: const GridView& gridView_; typedef std::vector< EntityPointer > EntityIdxMap; EntityIdxMap entityIdxMap_; }; //! gets barycenter of given geometry in local coordinates template < class GeometryType > Dune::FieldVector< typename GeometryType::ctype, GeometryType::mydimension > getBarycenterLocal( const GeometryType& geometry ) { assert( geometry.corners() > 0 ); Dune::FieldVector< typename GeometryType::ctype, GeometryType::mydimension > center; for( int i = 0; i < geometry.corners(); ++i ) { center += geometry.local( geometry[i] ); } center /= geometry.corners(); return center; } //! gets barycenter of given geometry in global coordinates template < class GeometryType > Dune::FieldVector< typename GeometryType::ctype, GeometryType::coorddimension > getBarycenterGlobal( const GeometryType& geometry ) { assert( geometry.corners() > 0 ); Dune::FieldVector< typename GeometryType::ctype, GeometryType::coorddimension > center; for( int i = 0; i < geometry.corners(); ++i ) { center += geometry[i] ; } center /= geometry.corners(); return center; } template < class GridType > struct GridDimensions { typedef MinMaxAvg<typename GridType::ctype> MinMaxAvgType; typedef Dune::array< MinMaxAvgType, GridType::dimensionworld > CoordLimitsType; CoordLimitsType coord_limits; MinMaxAvgType entity_volume; struct GridDimensionsFunctor { CoordLimitsType& coord_limits_; MinMaxAvgType& entity_volume_; GridDimensionsFunctor( CoordLimitsType& c, MinMaxAvgType& e ):coord_limits_(c),entity_volume_(e){} template <class Entity> void operator() ( const Entity& ent, const int /*ent_idx*/ ) { typedef typename Entity::Geometry EntityGeometryType; typedef Dune::FieldVector< typename EntityGeometryType::ctype, EntityGeometryType::coorddimension> DomainType; const typename Entity::Geometry& geo = ent.geometry(); entity_volume_( geo.volume() ); for ( int i = 0; i < geo.corners(); ++i ) { const DomainType& corner( geo.corner( i ) ); for ( size_t k = 0; k < GridType::dimensionworld; ++k ) coord_limits_[k]( corner[k] ); } } }; double volumeRelation() const { return entity_volume.min() != 0.0 ? entity_volume.max() / entity_volume.min() : -1; } GridDimensions( const GridType& grid ) { typedef typename GridType::LeafGridView View; const View& view = grid.leafView(); GridDimensionsFunctor f( coord_limits, entity_volume ); GridWalk<View>( view ).walkCodim0( f ); } }; template <class Stream, class T> inline Stream& operator<< (Stream& s, const GridDimensions<T>& d ) { for ( size_t k = 0; k < T::dimensionworld; ++k ) { const typename GridDimensions<T>::MinMaxAvgType& mma = d.coord_limits[k]; s << boost::format( "x%d\tmin: %e\tavg: %e\tmax: %e\n" ) % k % mma.min() % mma.average() % mma.max(); } s << boost::format("Entity vol min: %e\tavg: %e\tmax: %e\tQout: %e") % d.entity_volume.min() % d.entity_volume.average() % d.entity_volume.max() % d.volumeRelation(); s << std::endl; return s; } template < class GridType > struct MaximumEntityVolumeRefineFunctor { MaximumEntityVolumeRefineFunctor ( GridType& grid, double volume, double factor ) :threshold_volume_( volume * factor ), grid_(grid) {} template <class Entity> void operator() ( const Entity& ent, const int /*ent_idx*/ ) { const double volume = ent.geometry().volume(); if ( volume > threshold_volume_ ) grid_.mark( 1, ent ); } const double threshold_volume_; GridType& grid_; }; //! refine entities until all have volume < size_factor * unrefined_minimum_volume template < class GridType > void EnforceMaximumEntityVolume( GridType& grid, const double size_factor ) { const GridDimensions<GridType> unrefined_dimensions( grid ); const double unrefined_min_volume = unrefined_dimensions.entity_volume.min(); typedef typename GridType::LeafGridView View; View view = grid.leafView(); MaximumEntityVolumeRefineFunctor<GridType> f( grid, unrefined_min_volume, size_factor ); while ( true ) { grid.preAdapt(); GridWalk<View>( view ).walkCodim0( f ); if ( !grid.adapt() ) break; grid.postAdapt(); std::cout << Stuff::GridDimensions<GridType>( grid ); } } template < class GridImp, template<int,int,class> class EntityImp > double geometryDiameter( const Dune::Entity< 0, 2, GridImp, EntityImp >& entity ) { typedef Dune::Entity< 0, 2, GridImp, EntityImp > EntityType; typedef typename EntityType::LeafIntersectionIterator IntersectionIteratorType; IntersectionIteratorType end = entity.ileafend(); double factor = 1.0; for ( IntersectionIteratorType it = entity.ileafbegin(); it != end ; ++it ) { const typename IntersectionIteratorType::Intersection& intersection = *it; factor *= intersection.intersectionGlobal().volume(); } return factor/(2.0*entity.geometry().volume()); } template < class GridImp, template<int,int,class> class EntityImp > double geometryDiameter( const Dune::Entity< 0, 3, GridImp, EntityImp >& entity ) { DUNE_THROW( Dune::Exception, "copypasta from 2D" ); typedef Dune::Entity< 0, 3, GridImp, EntityImp > EntityType; typedef typename EntityType::LeafIntersectionIterator IntersectionIteratorType; IntersectionIteratorType end = entity.ileafend(); double factor = 1.0; for ( IntersectionIteratorType it = entity.ileafbegin(); it != end ; ++it ) { const typename IntersectionIteratorType::Intersection& intersection = *it; factor *= intersection.intersectionGlobal().volume(); } return factor/(2.0*entity.geometry().volume()); } }//end namespace #endif <|endoftext|>
<commit_before>/* flappy.cc --- ncurses flappy bird clone * This is free and unencumbered software released into the public domain. * c++ -std=c++11 flappy.cc -lncurses -lm -o flappy */ #include <algorithm> #include <thread> #include <deque> #include <ctime> #include <cmath> #include <ncurses.h> struct Display { Display(int width = 40, int height = 20) : height{height}, width{width} { initscr(); raw(); timeout(0); noecho(); curs_set(0); keypad(stdscr, TRUE); erase(); } ~Display() { endwin(); } void erase() { ::erase(); for (int y = 0; y < height; y++) { mvaddch(y, 0, '|'); mvaddch(y, width - 1, '|'); } for (int x = 0; x < width; x++) { mvaddch(0, x, '-'); mvaddch(height - 1, x, '-'); } mvaddch(0, 0, '/'); mvaddch(height - 1, 0, '\\'); mvaddch(0, width - 1, '\\'); mvaddch(height - 1, width - 1, '/'); } void refresh() { ::refresh(); } const int height, width; int block_getch() { refresh(); timeout(-1); int c = getch(); timeout(0); return c; } }; struct World { World(Display *display) : display{display} { for (int x = 1; x < display->width - 1; x++) { walls.push_back(0); } } std::deque<int> walls; Display *display; int steps = 0; constexpr static int kRate = 2, kVGap = 2, kHGap = 10; int rand_wall() { int h = display->height; return (rand() % h / 2) + h / 4; } void step() { steps++; if (steps % kRate == 0) { walls.pop_front(); if ((steps % (kRate * kHGap)) == 0) { walls.push_back(rand_wall()); } else { walls.push_back(0); } } } void draw() { for (int i = 0; i < walls.size(); i++) { int wall = walls[i]; if (wall != 0) { for (int y = 1; y < display->height - 1; y++) { if (y < wall - kVGap || y > wall + kVGap) { mvaddch(y, i + 1, '*'); } } } } mvprintw(display->height, 0, "Score: %d", score()); } int score() { return std::max(0, steps / (kRate * kHGap) - 2); } }; struct Bird { Bird(Display *display) : y{display->height / 2.0}, display{display} {} double y, dy = 0; Display *display; void gravity() { dy += 0.1; y += dy; } void poke() { dy = -0.8; } void draw() { draw('@'); } void draw(int c) { int h = std::round(y); h = std::max(1, std::min(h, display->height - 2)); mvaddch(h, display->width / 2, c); } bool is_alive(World &world) { if (y <= 0 || y >= display->height) { return false; } int wall = world.walls[display->width / 2 - 1]; if (wall != 0) { return y > wall - World::kVGap && y < wall + World::kVGap; } return true; } }; struct Game { Game(Display *display) : display{display}, bird{display}, world{display} {} Display *display; Bird bird; World world; bool run() { while (bird.is_alive(world)) { int c = getch(); if (c == 'q') { return false; } else if (c != ERR) { while (getch() != ERR) ; // clear repeat buffer bird.poke(); } display->erase(); world.step(); world.draw(); bird.gravity(); bird.draw(); display->refresh(); std::this_thread::sleep_for(std::chrono::milliseconds{67}); } bird.draw('X'); display->refresh(); return true; } }; int main() { srand(std::time(NULL)); Display display; while (true) { Game game{&display}; if (!game.run()) { return 0; } mvprintw(display.height + 1, 0, "Game over!"); mvprintw(display.height + 2, 0, "Press 'q' to quit, 'r' to retry."); int c; while ((c = display.block_getch()) != 'r') { if (c == 'q' || c == ERR) { return 0; } } } return 0; } <commit_msg>Add intro message.<commit_after>/* flappy.cc --- ncurses flappy bird clone * This is free and unencumbered software released into the public domain. * c++ -std=c++11 flappy.cc -lncurses -lm -o flappy */ #include <algorithm> #include <thread> #include <deque> #include <ctime> #include <cmath> #include <cstring> #include <ncurses.h> struct Display { Display(int width = 40, int height = 20) : height{height}, width{width} { initscr(); raw(); timeout(0); noecho(); curs_set(0); keypad(stdscr, TRUE); erase(); } ~Display() { endwin(); } void erase() { ::erase(); for (int y = 0; y < height; y++) { mvaddch(y, 0, '|'); mvaddch(y, width - 1, '|'); } for (int x = 0; x < width; x++) { mvaddch(0, x, '-'); mvaddch(height - 1, x, '-'); } mvaddch(0, 0, '/'); mvaddch(height - 1, 0, '\\'); mvaddch(0, width - 1, '\\'); mvaddch(height - 1, width - 1, '/'); } void refresh() { ::refresh(); } const int height, width; int block_getch() { refresh(); timeout(-1); int c = getch(); timeout(0); return c; } }; struct World { World(Display *display) : display{display} { for (int x = 1; x < display->width - 1; x++) { walls.push_back(0); } } std::deque<int> walls; Display *display; int steps = 0; constexpr static int kRate = 2, kVGap = 2, kHGap = 10; int rand_wall() { int h = display->height; return (rand() % h / 2) + h / 4; } void step() { steps++; if (steps % kRate == 0) { walls.pop_front(); if ((steps % (kRate * kHGap)) == 0) { walls.push_back(rand_wall()); } else { walls.push_back(0); } } } void draw() { for (int i = 0; i < walls.size(); i++) { int wall = walls[i]; if (wall != 0) { for (int y = 1; y < display->height - 1; y++) { if (y < wall - kVGap || y > wall + kVGap) { mvaddch(y, i + 1, '*'); } } } } mvprintw(display->height, 0, "Score: %d", score()); } int score() { return std::max(0, steps / (kRate * kHGap) - 2); } }; struct Bird { Bird(Display *display) : y{display->height / 2.0}, display{display} {} const double kImpulse = -0.8, kGravity = 0.1; double y, dy = kImpulse; Display *display; void gravity() { dy += kGravity; y += dy; } void poke() { dy = kImpulse; } void draw() { draw('@'); } void draw(int c) { int h = std::round(y); h = std::max(1, std::min(h, display->height - 2)); mvaddch(h, display->width / 2, c); } bool is_alive(World &world) { if (y <= 0 || y >= display->height) { return false; } int wall = world.walls[display->width / 2 - 1]; if (wall != 0) { return y > wall - World::kVGap && y < wall + World::kVGap; } return true; } }; struct Game { Game(Display *display) : display{display}, bird{display}, world{display} {} Display *display; Bird bird; World world; bool run() { display->erase(); const char *intro = "[Press any key to hop upwards]"; mvprintw(display->height / 2 - 2, display->width / 2 - std::strlen(intro) / 2, intro); bird.draw(); display->block_getch(); while (bird.is_alive(world)) { int c = getch(); if (c == 'q') { return false; } else if (c != ERR) { while (getch() != ERR) ; // clear repeat buffer bird.poke(); } display->erase(); world.step(); world.draw(); bird.gravity(); bird.draw(); display->refresh(); std::this_thread::sleep_for(std::chrono::milliseconds{67}); } bird.draw('X'); display->refresh(); return true; } }; int main() { srand(std::time(NULL)); Display display; while (true) { Game game{&display}; if (!game.run()) { return 0; } mvprintw(display.height + 1, 0, "Game over!"); mvprintw(display.height + 2, 0, "Press 'q' to quit, 'r' to retry."); int c; while ((c = display.block_getch()) != 'r') { if (c == 'q' || c == ERR) { return 0; } } } return 0; } <|endoftext|>
<commit_before>/* Copyright 2015 Stanford University * * 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 "legion_terra_partitions.h" #include "arrays.h" #include "legion.h" #include "legion_c_util.h" #include "legion_utilities.h" #include "lowlevel.h" #include "utilities.h" using namespace LegionRuntime; using namespace LegionRuntime::HighLevel; #ifdef SHARED_LOWLEVEL #define USE_LEGION_CROSS_PRODUCT 1 #else // General LLR can't handle new partion API yet. #define USE_LEGION_CROSS_PRODUCT 0 #endif #ifndef USE_TLS // Mac OS X and GCC <= 4.6 do not support C++11 thread_local. #if defined(__MACH__) || (defined(__GNUC__) && (__GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ <= 6))) #define USE_TLS 0 #else #define USE_TLS 1 #endif #endif struct CachedIndexIterator { public: CachedIndexIterator(HighLevelRuntime *rt, Context ctx, IndexSpace is, bool gl) : runtime(rt), context(ctx), space(is), index(0), cached(false), global(gl) { } bool has_next() { if (!cached) cache(); return index < spans.size(); } ptr_t next_span(size_t *count) { if (!cached) cache(); if (index >= spans.size()) { *count = 0; return ptr_t::nil(); } std::pair<ptr_t, size_t> span = spans[index++]; *count = span.second; return span.first; } void reset() { index = 0; } private: void cache() { assert(!cached); if (global) { #if !USE_TLS AutoLock guard(global_lock); #endif std::map<IndexSpace, std::vector<std::pair<ptr_t, size_t> > >::iterator it = global_cache.find(space); if (it != global_cache.end()) { spans = it->second; cached = true; return; } } IndexIterator it(runtime, context, space); while (it.has_next()) { size_t count = 0; ptr_t start = it.next_span(count); assert(count && !start.is_null()); spans.push_back(std::pair<ptr_t, size_t>(start, count)); } if (global) { #if USE_TLS global_cache[space] = spans; #else AutoLock guard(global_lock); if (!global_cache.count(space)) { global_cache[space] = spans; } #endif } cached = true; } private: HighLevelRuntime *runtime; Context context; IndexSpace space; std::vector<std::pair<ptr_t, size_t> > spans; size_t index; bool cached; bool global; private: #if USE_TLS static thread_local std::map<IndexSpace, std::vector<std::pair<ptr_t, size_t> > > global_cache; #else static std::map<IndexSpace, std::vector<std::pair<ptr_t, size_t> > > global_cache; static ImmovableLock global_lock; #endif }; #if USE_TLS thread_local std::map<IndexSpace, std::vector<std::pair<ptr_t, size_t> > > CachedIndexIterator::global_cache; #else std::map<IndexSpace, std::vector<std::pair<ptr_t, size_t> > > CachedIndexIterator::global_cache; ImmovableLock CachedIndexIterator::global_lock(true); #endif class TerraCObjectWrapper { public: #define NEW_OPAQUE_WRAPPER(T_, T) \ static T_ wrap(T t) { \ T_ t_; \ t_.impl = static_cast<void *>(t); \ return t_; \ } \ static const T_ wrap_const(const T t) { \ T_ t_; \ t_.impl = const_cast<void *>(static_cast<const void *>(t)); \ return t_; \ } \ static T unwrap(T_ t_) { \ return static_cast<T>(t_.impl); \ } \ static const T unwrap_const(const T_ t_) { \ return static_cast<const T>(t_.impl); \ } NEW_OPAQUE_WRAPPER(legion_terra_cached_index_iterator_t, CachedIndexIterator *); #undef NEW_OPAQUE_WRAPPER }; legion_terra_index_cross_product_t legion_terra_index_cross_product_create(legion_runtime_t runtime_, legion_context_t ctx_, legion_index_partition_t lhs_, legion_index_partition_t rhs_) { HighLevelRuntime *runtime = CObjectWrapper::unwrap(runtime_); Context ctx = CObjectWrapper::unwrap(ctx_); IndexPartition lhs = CObjectWrapper::unwrap(lhs_); IndexPartition rhs = CObjectWrapper::unwrap(rhs_); legion_terra_index_cross_product_t prod; prod.partition = CObjectWrapper::wrap(lhs); prod.other = CObjectWrapper::wrap(rhs); #if USE_LEGION_CROSS_PRODUCT std::map<DomainPoint, IndexPartition> handles; runtime->create_cross_product_partitions( ctx, lhs, rhs, handles, (runtime->is_index_partition_disjoint(ctx, rhs) ? DISJOINT_KIND : ALIASED_KIND), runtime->get_index_partition_color(ctx, rhs), true); #else // FIXME: Validate: same index tree Domain lhs_colors = runtime->get_index_partition_color_space(ctx, lhs); Domain rhs_colors = runtime->get_index_partition_color_space(ctx, rhs); for (Domain::DomainPointIterator lhs_dp(lhs_colors); lhs_dp; lhs_dp++) { Color lhs_color = lhs_dp.p.get_point<1>()[0]; IndexSpace lhs_space = runtime->get_index_subspace(ctx, lhs, lhs_color); std::set<ptr_t> lhs_points; for (IndexIterator lhs_it(runtime, ctx, lhs_space); lhs_it.has_next();) { lhs_points.insert(lhs_it.next()); } Coloring lhs_coloring; for (Domain::DomainPointIterator rhs_dp(rhs_colors); rhs_dp; rhs_dp++) { Color rhs_color = rhs_dp.p.get_point<1>()[0]; IndexSpace rhs_space = runtime->get_index_subspace(ctx, rhs, rhs_color); // Ensure the color exists. lhs_coloring[rhs_color]; for (IndexIterator rhs_it(runtime, ctx, rhs_space); rhs_it.has_next();) { ptr_t rhs_ptr = rhs_it.next(); if (lhs_points.count(rhs_ptr)) { lhs_coloring[rhs_color].points.insert(rhs_ptr); } } } runtime->create_index_partition( ctx, lhs_space, lhs_coloring, runtime->is_index_partition_disjoint(ctx, rhs), runtime->get_index_partition_color(ctx, rhs)); } #endif return prod; } legion_index_partition_t legion_terra_index_cross_product_get_partition( legion_terra_index_cross_product_t prod) { return prod.partition; } legion_index_partition_t legion_terra_index_cross_product_get_subpartition_by_color( legion_runtime_t runtime_, legion_context_t ctx_, legion_terra_index_cross_product_t prod, legion_color_t color) { HighLevelRuntime *runtime = CObjectWrapper::unwrap(runtime_); Context ctx = CObjectWrapper::unwrap(ctx_); IndexPartition partition = CObjectWrapper::unwrap(prod.partition); IndexPartition other = CObjectWrapper::unwrap(prod.other); IndexSpace is = runtime->get_index_subspace(ctx, partition, color); IndexPartition ip = runtime->get_index_partition( ctx, is, runtime->get_index_partition_color(ctx, other)); return CObjectWrapper::wrap(ip); } legion_terra_cached_index_iterator_t legion_terra_cached_index_iterator_create( legion_runtime_t runtime_, legion_context_t ctx_, legion_index_space_t handle_) { HighLevelRuntime *runtime = CObjectWrapper::unwrap(runtime_); Context ctx = CObjectWrapper::unwrap(ctx_); IndexSpace handle = CObjectWrapper::unwrap(handle_); CachedIndexIterator *result = new CachedIndexIterator(runtime, ctx, handle, true); return TerraCObjectWrapper::wrap(result); } void legion_terra_cached_index_iterator_destroy( legion_terra_cached_index_iterator_t handle_) { CachedIndexIterator *handle = TerraCObjectWrapper::unwrap(handle_); delete handle; } bool legion_terra_cached_index_iterator_has_next( legion_terra_cached_index_iterator_t handle_) { CachedIndexIterator *handle = TerraCObjectWrapper::unwrap(handle_); return handle->has_next(); } legion_ptr_t legion_terra_cached_index_iterator_next_span( legion_terra_cached_index_iterator_t handle_, size_t *count, size_t req_count /* must be -1 */) { assert(req_count == size_t(-1)); CachedIndexIterator *handle = TerraCObjectWrapper::unwrap(handle_); ptr_t result = handle->next_span(count); return CObjectWrapper::wrap(result); } void legion_terra_cached_index_iterator_reset( legion_terra_cached_index_iterator_t handle_) { CachedIndexIterator *handle = TerraCObjectWrapper::unwrap(handle_); handle->reset(); } <commit_msg>bindings: Enable builds without C++11.<commit_after>/* Copyright 2015 Stanford University * * 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 "legion_terra_partitions.h" #include "arrays.h" #include "legion.h" #include "legion_c_util.h" #include "legion_utilities.h" #include "lowlevel.h" #include "utilities.h" using namespace LegionRuntime; using namespace LegionRuntime::HighLevel; #ifdef SHARED_LOWLEVEL #define USE_LEGION_CROSS_PRODUCT 1 #else // General LLR can't handle new partion API yet. #define USE_LEGION_CROSS_PRODUCT 0 #endif #ifndef USE_TLS // Mac OS X and GCC <= 4.6 do not support C++11 thread_local. #if __cplusplus < 201103L || defined(__MACH__) || (defined(__GNUC__) && (__GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ <= 6))) #define USE_TLS 0 #else #define USE_TLS 1 #endif #endif struct CachedIndexIterator { public: CachedIndexIterator(HighLevelRuntime *rt, Context ctx, IndexSpace is, bool gl) : runtime(rt), context(ctx), space(is), index(0), cached(false), global(gl) { } bool has_next() { if (!cached) cache(); return index < spans.size(); } ptr_t next_span(size_t *count) { if (!cached) cache(); if (index >= spans.size()) { *count = 0; return ptr_t::nil(); } std::pair<ptr_t, size_t> span = spans[index++]; *count = span.second; return span.first; } void reset() { index = 0; } private: void cache() { assert(!cached); if (global) { #if !USE_TLS AutoLock guard(global_lock); #endif std::map<IndexSpace, std::vector<std::pair<ptr_t, size_t> > >::iterator it = global_cache.find(space); if (it != global_cache.end()) { spans = it->second; cached = true; return; } } IndexIterator it(runtime, context, space); while (it.has_next()) { size_t count = 0; ptr_t start = it.next_span(count); assert(count && !start.is_null()); spans.push_back(std::pair<ptr_t, size_t>(start, count)); } if (global) { #if USE_TLS global_cache[space] = spans; #else AutoLock guard(global_lock); if (!global_cache.count(space)) { global_cache[space] = spans; } #endif } cached = true; } private: HighLevelRuntime *runtime; Context context; IndexSpace space; std::vector<std::pair<ptr_t, size_t> > spans; size_t index; bool cached; bool global; private: #if USE_TLS static thread_local std::map<IndexSpace, std::vector<std::pair<ptr_t, size_t> > > global_cache; #else static std::map<IndexSpace, std::vector<std::pair<ptr_t, size_t> > > global_cache; static ImmovableLock global_lock; #endif }; #if USE_TLS thread_local std::map<IndexSpace, std::vector<std::pair<ptr_t, size_t> > > CachedIndexIterator::global_cache; #else std::map<IndexSpace, std::vector<std::pair<ptr_t, size_t> > > CachedIndexIterator::global_cache; ImmovableLock CachedIndexIterator::global_lock(true); #endif class TerraCObjectWrapper { public: #define NEW_OPAQUE_WRAPPER(T_, T) \ static T_ wrap(T t) { \ T_ t_; \ t_.impl = static_cast<void *>(t); \ return t_; \ } \ static const T_ wrap_const(const T t) { \ T_ t_; \ t_.impl = const_cast<void *>(static_cast<const void *>(t)); \ return t_; \ } \ static T unwrap(T_ t_) { \ return static_cast<T>(t_.impl); \ } \ static const T unwrap_const(const T_ t_) { \ return static_cast<const T>(t_.impl); \ } NEW_OPAQUE_WRAPPER(legion_terra_cached_index_iterator_t, CachedIndexIterator *); #undef NEW_OPAQUE_WRAPPER }; legion_terra_index_cross_product_t legion_terra_index_cross_product_create(legion_runtime_t runtime_, legion_context_t ctx_, legion_index_partition_t lhs_, legion_index_partition_t rhs_) { HighLevelRuntime *runtime = CObjectWrapper::unwrap(runtime_); Context ctx = CObjectWrapper::unwrap(ctx_); IndexPartition lhs = CObjectWrapper::unwrap(lhs_); IndexPartition rhs = CObjectWrapper::unwrap(rhs_); legion_terra_index_cross_product_t prod; prod.partition = CObjectWrapper::wrap(lhs); prod.other = CObjectWrapper::wrap(rhs); #if USE_LEGION_CROSS_PRODUCT std::map<DomainPoint, IndexPartition> handles; runtime->create_cross_product_partitions( ctx, lhs, rhs, handles, (runtime->is_index_partition_disjoint(ctx, rhs) ? DISJOINT_KIND : ALIASED_KIND), runtime->get_index_partition_color(ctx, rhs), true); #else // FIXME: Validate: same index tree Domain lhs_colors = runtime->get_index_partition_color_space(ctx, lhs); Domain rhs_colors = runtime->get_index_partition_color_space(ctx, rhs); for (Domain::DomainPointIterator lhs_dp(lhs_colors); lhs_dp; lhs_dp++) { Color lhs_color = lhs_dp.p.get_point<1>()[0]; IndexSpace lhs_space = runtime->get_index_subspace(ctx, lhs, lhs_color); std::set<ptr_t> lhs_points; for (IndexIterator lhs_it(runtime, ctx, lhs_space); lhs_it.has_next();) { lhs_points.insert(lhs_it.next()); } Coloring lhs_coloring; for (Domain::DomainPointIterator rhs_dp(rhs_colors); rhs_dp; rhs_dp++) { Color rhs_color = rhs_dp.p.get_point<1>()[0]; IndexSpace rhs_space = runtime->get_index_subspace(ctx, rhs, rhs_color); // Ensure the color exists. lhs_coloring[rhs_color]; for (IndexIterator rhs_it(runtime, ctx, rhs_space); rhs_it.has_next();) { ptr_t rhs_ptr = rhs_it.next(); if (lhs_points.count(rhs_ptr)) { lhs_coloring[rhs_color].points.insert(rhs_ptr); } } } runtime->create_index_partition( ctx, lhs_space, lhs_coloring, runtime->is_index_partition_disjoint(ctx, rhs), runtime->get_index_partition_color(ctx, rhs)); } #endif return prod; } legion_index_partition_t legion_terra_index_cross_product_get_partition( legion_terra_index_cross_product_t prod) { return prod.partition; } legion_index_partition_t legion_terra_index_cross_product_get_subpartition_by_color( legion_runtime_t runtime_, legion_context_t ctx_, legion_terra_index_cross_product_t prod, legion_color_t color) { HighLevelRuntime *runtime = CObjectWrapper::unwrap(runtime_); Context ctx = CObjectWrapper::unwrap(ctx_); IndexPartition partition = CObjectWrapper::unwrap(prod.partition); IndexPartition other = CObjectWrapper::unwrap(prod.other); IndexSpace is = runtime->get_index_subspace(ctx, partition, color); IndexPartition ip = runtime->get_index_partition( ctx, is, runtime->get_index_partition_color(ctx, other)); return CObjectWrapper::wrap(ip); } legion_terra_cached_index_iterator_t legion_terra_cached_index_iterator_create( legion_runtime_t runtime_, legion_context_t ctx_, legion_index_space_t handle_) { HighLevelRuntime *runtime = CObjectWrapper::unwrap(runtime_); Context ctx = CObjectWrapper::unwrap(ctx_); IndexSpace handle = CObjectWrapper::unwrap(handle_); CachedIndexIterator *result = new CachedIndexIterator(runtime, ctx, handle, true); return TerraCObjectWrapper::wrap(result); } void legion_terra_cached_index_iterator_destroy( legion_terra_cached_index_iterator_t handle_) { CachedIndexIterator *handle = TerraCObjectWrapper::unwrap(handle_); delete handle; } bool legion_terra_cached_index_iterator_has_next( legion_terra_cached_index_iterator_t handle_) { CachedIndexIterator *handle = TerraCObjectWrapper::unwrap(handle_); return handle->has_next(); } legion_ptr_t legion_terra_cached_index_iterator_next_span( legion_terra_cached_index_iterator_t handle_, size_t *count, size_t req_count /* must be -1 */) { assert(req_count == size_t(-1)); CachedIndexIterator *handle = TerraCObjectWrapper::unwrap(handle_); ptr_t result = handle->next_span(count); return CObjectWrapper::wrap(result); } void legion_terra_cached_index_iterator_reset( legion_terra_cached_index_iterator_t handle_) { CachedIndexIterator *handle = TerraCObjectWrapper::unwrap(handle_); handle->reset(); } <|endoftext|>
<commit_before>#include "msl/msl.h" #define BOOST_RESULT_OF_USE_DECLTYPE #define BOOST_SPIRIT_USE_PHOENIX_V3 #include <boost/config/warning_disable.hpp> #include <boost/spirit/include/qi.hpp> #include <boost/spirit/include/phoenix_core.hpp> #include <boost/spirit/include/phoenix_operator.hpp> #include <boost/spirit/include/qi_char_class.hpp> #include <boost/make_shared.hpp> #include <boost/fusion/include/std_pair.hpp> #include <boost/spirit/repository/include/qi_confix.hpp> namespace msl { template<typename T, Value::Type my_type> class TemplatedValue : public Value { public: using base_type = TemplatedValue<T, my_type>; TemplatedValue() : { _type = my_type; } TemplatedValue(const T& t) : _value(t) { _type = my_type; } TemplatedValue(T&& t) : _value(std::move(t)) { _type = my_type; } protected: T _value; }; template<typename T, Value::Type my_type> class NamedTemplatedValue : public Value { public: using base_type = NamedTemplatedValue<T, my_type>; NamedTemplatedValue() : { _type = my_type; } NamedTemplatedValue(const std::string& name, const MapType& attr, const T& t) : _attributes(attr), _value(t), _name(name) { _type = my_type; } NamedTemplatedValue(const std::string& name, MapType&& attr, T&& t) : _attributes(std::move(attr)), _value(std::move(t)), _name(name) { _type = my_type; } const std::string& name() override { return _name; }; const MapType& attributes() override { return _attributes; } protected: MapType _attributes; T _value; std::string _name; }; class BoolValue : public TemplatedValue<bool, Value::Type::Boolean> { public: using base_type::TemplatedValue; bool asBool() override { return _value; } }; class StringValue : public TemplatedValue<std::string, Value::Type::String> { public: using base_type::TemplatedValue; const std::string& asString() override { return _value; } }; class FloatValue : public TemplatedValue<float, Value::Type::Float> { public: using base_type::TemplatedValue; float asFloat() override { return _value; } }; class PercentValue : public TemplatedValue<float, Value::Type::Percent> { public: using base_type::TemplatedValue; float asFloat() override { return _value; } }; class ArrayValue : public TemplatedValue<Value::ArrayType, Value::Type::Array> { public: using base_type::TemplatedValue; const ArrayType& asArray() override { return _value; } }; class MapValue : public TemplatedValue<Value::MapType, Value::Type::Map> { public: using base_type::TemplatedValue; const MapType& asMap() override { return _value; } }; class NamedArrayValue : public NamedTemplatedValue<Value::ArrayType, Value::Type::Array> { public: using base_type::NamedTemplatedValue; const ArrayType& asArray() override { return _value; } }; class NamedMapValue : public NamedTemplatedValue<Value::MapType, Value::Type::Map> { public: using base_type::NamedTemplatedValue; const MapType& asMap() override { return _value; } }; class NamedNullValue : public Value { public: NamedNullValue(const std::string& name, const MapType& attr) : _attributes(attr), _name(name) { } const std::string& name() override { return _name; }; const MapType& attributes() override { return _attributes; } protected: MapType _attributes; std::string _name; }; } namespace client { namespace qi = boost::spirit::qi; namespace ascii = boost::spirit::ascii; /////////////////////////////////////////////////////////////////////////////// // The skipper grammar /////////////////////////////////////////////////////////////////////////////// template <typename Iterator> struct skipper : qi::grammar<Iterator> { skipper() : skipper::base_type(start) { qi::char_type char_; ascii::space_type space; start = space // tab/space/cr/lf | "/*" >> *(char_ - "*/") >> "*/" // C-style comments | "//" >> *(char_ - eol) >> eol // C++-style comments ; } qi::rule<Iterator> start; }; using namespace boost::spirit; template <typename Iterator> struct msl_grammar : qi::grammar<Iterator, msl::Value::pointer(), skipper<Iterator>> { using standard_rule = qi::rule<Iterator, msl::Value::pointer(), skipper<Iterator>>; template<typename Type> auto createAttrSynthesizer() { return [](auto&& f, auto &c) { using namespace boost::fusion; at_c<0>(c.attributes) = std::make_shared<Type>(std::move(f)); }; } template<typename Type> auto createAttrSynthesizerForNamed() { return [](auto&& f, auto &c) { using namespace boost::fusion; at_c<0>(c.attributes) = std::make_shared<Type>(at_c<0>(f), at_c<1>(f), at_c<2>(f)); }; } auto createAttrSynthesizerForNamedNull() { return [](auto&& f, auto &c) { using namespace boost::fusion; at_c<0>(c.attributes) = std::make_shared<msl::NamedNullValue>(at_c<0>(f), at_c<1>(f)); }; } msl_grammar() : msl_grammar::base_type(msl) { using namespace msl; using qi::lit; using qi::rule; using qi::float_; using qi::_1; using qi::phrase_parse; using ascii::space; using ascii::char_; using ascii::alpha; using ascii::string; using namespace qi::labels; using namespace boost::fusion; //null { auto rule_null_f = [](auto&& f, auto &c) { at_c<0>(c.attributes) = std::make_shared<Value>(); }; rule_null = lit("null")[rule_null_f]; } //bool { auto rule_true_f = [](auto&& f, auto &c) {at_c<0>(c.attributes) = std::make_shared<BoolValue>(true); }; auto rule_false_f = [](auto&& f, auto &c) {at_c<0>(c.attributes) = std::make_shared<BoolValue>(false); }; rule_bool = lit("true")[rule_true_f] | lit("false")[rule_false_f]; } //float { auto percent = [](auto&& f, auto &c) { at_c<0>(c.attributes) = std::make_shared<PercentValue>(f / 100.0f); }; rule_float = (float_ >> '%')[percent] | float_[createAttrSynthesizer<FloatValue>()]; } //string { quoted_string %= lexeme['"' >> *(char_ - '"') >> '"']; simple_string %= (alpha | char_('&')) >> *(char_(R"foo(a-zA-Z0-9\.\-\(\)\\\/\_)foo")); rule_string = (quoted_string | simple_string)[createAttrSynthesizer<StringValue>()]; } //array { rule_varray %= '[' >> *(rule_value >> -lit(',')) >> ']'; rule_array = rule_varray[createAttrSynthesizer<ArrayValue>()]; } //map { rule_vmap %= qi::lit("{") >> *(rule_value >> qi::lit(":") >> rule_value >> -lit(',')) >> qi::lit("}"); rule_map = rule_vmap[createAttrSynthesizer<MapValue>()]; } named_string %= (alpha) >> *(char_("a-zA-Z0-9\\.\\-")); rule_vattr %= "(" >> *(rule_value >> qi::lit(":") >> rule_value >> -lit(',')) >> ")"; //named null { rule_named_null = (named_string >> rule_vattr)[createAttrSynthesizerForNamedNull()]; } //named array { rule_named_array = (named_string >> rule_vattr >> rule_varray)[createAttrSynthesizerForNamed<NamedArrayValue>()]; } //named map { rule_named_map = (named_string >> rule_vattr >> rule_vmap)[createAttrSynthesizerForNamed<NamedMapValue>()]; } rule_value = rule_float | rule_array | rule_map | rule_named_array | rule_named_map | rule_named_null | rule_bool | rule_null | rule_string; msl = rule_value; } standard_rule msl; standard_rule rule_value; standard_rule rule_float; standard_rule rule_bool; standard_rule rule_null; standard_rule rule_string; standard_rule rule_array; standard_rule rule_map; standard_rule rule_named_array; standard_rule rule_named_map; standard_rule rule_named_null; qi::rule<Iterator, msl::Value::MapType(), skipper<Iterator>> rule_vattr; qi::rule<Iterator, msl::Value::MapType(), skipper<Iterator>> rule_vmap; qi::rule<Iterator, msl::Value::ArrayType(), skipper<Iterator>> rule_varray; qi::rule<Iterator, std::string()> quoted_string; qi::rule<Iterator, std::string()> simple_string; qi::rule<Iterator, std::string()> named_string; }; template <typename Iterator> msl::Value::pointer parse_msl(Iterator first, Iterator last) { msl_grammar<Iterator> msl; // Our grammar msl::Value::pointer ast; // Our tree using boost::spirit::ascii::space; using boost::spirit::repository::confix; using ascii::char_; //qi::rule<Iterator> skipper<Iterator> skipper; bool r = phrase_parse(first, last, msl, skipper, ast); if (first != last) return nullptr; return ast; } } msl::Value::pointer msl::Value::fromString(const std::string &str) { return client::parse_msl(str.begin(), str.end()); }<commit_msg>- fixed issue with nan and inf in simple string - added ! to simple string<commit_after>#include "msl/msl.h" #define BOOST_RESULT_OF_USE_DECLTYPE #define BOOST_SPIRIT_USE_PHOENIX_V3 #include <boost/config/warning_disable.hpp> #include <boost/spirit/include/qi.hpp> #include <boost/spirit/include/phoenix_core.hpp> #include <boost/spirit/include/phoenix_operator.hpp> #include <boost/spirit/include/qi_char_class.hpp> #include <boost/make_shared.hpp> #include <boost/fusion/include/std_pair.hpp> #include <boost/spirit/repository/include/qi_confix.hpp> namespace msl { template<typename T, Value::Type my_type> class TemplatedValue : public Value { public: using base_type = TemplatedValue<T, my_type>; TemplatedValue() : { _type = my_type; } TemplatedValue(const T& t) : _value(t) { _type = my_type; } TemplatedValue(T&& t) : _value(std::move(t)) { _type = my_type; } protected: T _value; }; template<typename T, Value::Type my_type> class NamedTemplatedValue : public Value { public: using base_type = NamedTemplatedValue<T, my_type>; NamedTemplatedValue() : { _type = my_type; } NamedTemplatedValue(const std::string& name, const MapType& attr, const T& t) : _attributes(attr), _value(t), _name(name) { _type = my_type; } NamedTemplatedValue(const std::string& name, MapType&& attr, T&& t) : _attributes(std::move(attr)), _value(std::move(t)), _name(name) { _type = my_type; } const std::string& name() override { return _name; }; const MapType& attributes() override { return _attributes; } protected: MapType _attributes; T _value; std::string _name; }; class BoolValue : public TemplatedValue<bool, Value::Type::Boolean> { public: using base_type::TemplatedValue; bool asBool() override { return _value; } }; class StringValue : public TemplatedValue<std::string, Value::Type::String> { public: using base_type::TemplatedValue; const std::string& asString() override { return _value; } }; class FloatValue : public TemplatedValue<float, Value::Type::Float> { public: using base_type::TemplatedValue; float asFloat() override { return _value; } }; class PercentValue : public TemplatedValue<float, Value::Type::Percent> { public: using base_type::TemplatedValue; float asFloat() override { return _value; } }; class ArrayValue : public TemplatedValue<Value::ArrayType, Value::Type::Array> { public: using base_type::TemplatedValue; const ArrayType& asArray() override { return _value; } }; class MapValue : public TemplatedValue<Value::MapType, Value::Type::Map> { public: using base_type::TemplatedValue; const MapType& asMap() override { return _value; } }; class NamedArrayValue : public NamedTemplatedValue<Value::ArrayType, Value::Type::Array> { public: using base_type::NamedTemplatedValue; const ArrayType& asArray() override { return _value; } }; class NamedMapValue : public NamedTemplatedValue<Value::MapType, Value::Type::Map> { public: using base_type::NamedTemplatedValue; const MapType& asMap() override { return _value; } }; class NamedNullValue : public Value { public: NamedNullValue(const std::string& name, const MapType& attr) : _attributes(attr), _name(name) { } const std::string& name() override { return _name; }; const MapType& attributes() override { return _attributes; } protected: MapType _attributes; std::string _name; }; } namespace client { namespace qi = boost::spirit::qi; namespace ascii = boost::spirit::ascii; /////////////////////////////////////////////////////////////////////////////// // The skipper grammar /////////////////////////////////////////////////////////////////////////////// template <typename Iterator> struct skipper : qi::grammar<Iterator> { skipper() : skipper::base_type(start) { qi::char_type char_; ascii::space_type space; start = space // tab/space/cr/lf | "/*" >> *(char_ - "*/") >> "*/" // C-style comments | "//" >> *(char_ - eol) >> eol // C++-style comments ; } qi::rule<Iterator> start; }; template <typename T> struct ts_real_policies : boost::spirit::qi::real_policies<T> { //don't parse Inf as infinity template <typename Iterator, typename Attribute> static bool parse_inf(Iterator& first, Iterator const& last, Attribute& attr) { return false; } //don't parse Nan as nan template <typename Iterator, typename Attribute> static bool parse_nan(Iterator& first, Iterator const& last, Attribute& attr) { return false; } }; using namespace boost::spirit; template <typename Iterator> struct msl_grammar : qi::grammar<Iterator, msl::Value::pointer(), skipper<Iterator>> { using standard_rule = qi::rule<Iterator, msl::Value::pointer(), skipper<Iterator>>; template<typename Type> auto createAttrSynthesizer() { return [](auto&& f, auto &c) { using namespace boost::fusion; at_c<0>(c.attributes) = std::make_shared<Type>(std::move(f)); }; } template<typename Type> auto createAttrSynthesizerForNamed() { return [](auto&& f, auto &c) { using namespace boost::fusion; at_c<0>(c.attributes) = std::make_shared<Type>(at_c<0>(f), at_c<1>(f), at_c<2>(f)); }; } auto createAttrSynthesizerForNamedNull() { return [](auto&& f, auto &c) { using namespace boost::fusion; at_c<0>(c.attributes) = std::make_shared<msl::NamedNullValue>(at_c<0>(f), at_c<1>(f)); }; } msl_grammar() : msl_grammar::base_type(msl) { using namespace msl; using qi::lit; using qi::rule; using qi::float_; using qi::_1; using qi::phrase_parse; using ascii::space; using ascii::char_; using ascii::alpha; using ascii::string; using namespace qi::labels; using namespace boost::fusion; //null { auto rule_null_f = [](auto&& f, auto &c) { at_c<0>(c.attributes) = std::make_shared<Value>(); }; rule_null = lit("null")[rule_null_f]; } //bool { auto rule_true_f = [](auto&& f, auto &c) {at_c<0>(c.attributes) = std::make_shared<BoolValue>(true); }; auto rule_false_f = [](auto&& f, auto &c) {at_c<0>(c.attributes) = std::make_shared<BoolValue>(false); }; rule_bool = lit("true")[rule_true_f] | lit("false")[rule_false_f]; } //float { boost::spirit::qi::real_parser<float, ts_real_policies<float> > my_float; auto percent = [](auto&& f, auto &c) { at_c<0>(c.attributes) = std::make_shared<PercentValue>(f / 100.0f); }; rule_float = (my_float >> '%')[percent] | my_float[createAttrSynthesizer<FloatValue>()]; } //string { quoted_string %= lexeme['"' >> *(char_ - '"') >> '"']; simple_string %= (alpha | char_('&')) >> *(char_(R"foo(a-zA-Z0-9\!\.\-\(\)\\\/\_)foo")); rule_string = (quoted_string | simple_string)[createAttrSynthesizer<StringValue>()]; } //array { rule_varray %= '[' >> *(rule_value >> -lit(',')) >> ']'; rule_array = rule_varray[createAttrSynthesizer<ArrayValue>()]; } //map { rule_vmap %= qi::lit("{") >> *(rule_value >> qi::lit(":") >> rule_value >> -lit(',')) >> qi::lit("}"); rule_map = rule_vmap[createAttrSynthesizer<MapValue>()]; } named_string %= (alpha) >> *(char_("a-zA-Z0-9\\.\\-")); rule_vattr %= "(" >> *(rule_value >> qi::lit(":") >> rule_value >> -lit(',')) >> ")"; //named null { rule_named_null = (named_string >> rule_vattr)[createAttrSynthesizerForNamedNull()]; } //named array { rule_named_array = (named_string >> rule_vattr >> rule_varray)[createAttrSynthesizerForNamed<NamedArrayValue>()]; } //named map { rule_named_map = (named_string >> rule_vattr >> rule_vmap)[createAttrSynthesizerForNamed<NamedMapValue>()]; } rule_value = rule_float | rule_array | rule_map | rule_named_array | rule_named_map | rule_named_null | rule_bool | rule_null | rule_string; msl = rule_value; } standard_rule msl; standard_rule rule_value; standard_rule rule_float; standard_rule rule_bool; standard_rule rule_null; standard_rule rule_string; standard_rule rule_array; standard_rule rule_map; standard_rule rule_named_array; standard_rule rule_named_map; standard_rule rule_named_null; qi::rule<Iterator, msl::Value::MapType(), skipper<Iterator>> rule_vattr; qi::rule<Iterator, msl::Value::MapType(), skipper<Iterator>> rule_vmap; qi::rule<Iterator, msl::Value::ArrayType(), skipper<Iterator>> rule_varray; qi::rule<Iterator, std::string()> quoted_string; qi::rule<Iterator, std::string()> simple_string; qi::rule<Iterator, std::string()> named_string; }; template <typename Iterator> msl::Value::pointer parse_msl(Iterator first, Iterator last) { msl_grammar<Iterator> msl; // Our grammar msl::Value::pointer ast; // Our tree using boost::spirit::ascii::space; using boost::spirit::repository::confix; using ascii::char_; //qi::rule<Iterator> skipper<Iterator> skipper; bool r = phrase_parse(first, last, msl, skipper, ast); if (first != last) return nullptr; return ast; } } msl::Value::pointer msl::Value::fromString(const std::string &str) { return client::parse_msl(str.begin(), str.end()); }<|endoftext|>
<commit_before>#include "TetrisDrawer.h" #include <vector> TetrisDrawer::TetrisDrawer(sf::RenderWindow & window, Board & board) { this->window = &window; this->board = &board; blockScaleFactor = 1.0f; //backgroundScaleFactor = blockScaleFactor / 2.0f; if (!tetrominoTexture.loadFromFile(TEXTURE_DIR)) { //error std::cout << "Error tetromino"; } tetrominoTexture.setRepeated(true); tetrominoSprite.setTexture(tetrominoTexture); tetrominoSprite.setScale(sf::Vector2f(blockScaleFactor, blockScaleFactor)); if (!backgroundTexture.loadFromFile(BACKGROUND_DIR)) { //error std::cout << "Error background"; } backgroundTexture.setRepeated(true); backgroundTexture.setSmooth(true); background.setSize(sf::Vector2f(BACKGROUND_WIDTH, BACKGROUND_WIDTH)); background.setTexture(&backgroundTexture); if (!gameFont.loadFromFile(FONT_DIR)) { //Font error std::cout << "Font error"; } //Fill color for the boxes sf::Color boxColor(0, 0, 0, 192); gameInfoBox.setSize(sf::Vector2f(this->window->getSize().x / 3.f, this->window->getSize().y / 6.f)); gameInfoBox.setFillColor(boxColor); gameInfoBox.setPosition(this->window->getSize().x * (3.f/5.f), this->window->getSize().y / 10.f); float textSize = gameInfoBox.getSize().x / 10.f; gameInfoText.setFont(gameFont); gameInfoText.setCharacterSize(textSize); gameInfoText.setPosition(gameInfoBox.getPosition().x + gameInfoBox.getSize().x / 13.f, gameInfoBox.getPosition().y + gameInfoBox.getSize().y / 3.f); nextTetriminoBox.setFillColor(boxColor); nextTetriminoBox.setSize(sf::Vector2f(gameInfoBox.getSize().x, TEXTURE_WIDTH * 7)); nextTetriminoBox.setPosition(gameInfoBox.getPosition().x, gameInfoBox.getPosition().y + (gameInfoBox.getSize().y * 1.5f)); nextTetriminoText.setCharacterSize(textSize); nextTetriminoText.setFont(gameFont); nextTetriminoText.setString("Next Tetrimino"); nextTetriminoText.setPosition(nextTetriminoBox.getPosition().x + nextTetriminoBox.getSize().x / 5.f, nextTetriminoBox.getPosition().y + nextTetriminoBox.getSize().y / 15.f); } TetrisDrawer::~TetrisDrawer() { } void TetrisDrawer::draw(short level, int score, Tetrimino & next) { window->clear(sf::Color::Black); drawBackground(); drawBoard(); drawGameInfo(level, score); drawNextTetrimino(next); window->display(); } void TetrisDrawer::drawBackground() { for (float i = 0.f; i < window->getSize().x; i+=BACKGROUND_WIDTH) { for (float j = 0.f; j < window->getSize().y; j+=BACKGROUND_WIDTH) { background.setPosition(sf::Vector2f(i, j)); window->draw(background); } } } void TetrisDrawer::drawBoard() { const std::vector<short> * map = board->getBoard(); short rows = board->getRows(); short columns = board->getColumns(); int position; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { position = ((columns)*i) + j; if ((*map)[position] != board->getPaddingValue()) { tetrominoSprite.setTextureRect(sf::IntRect((*map)[position] * TEXTURE_WIDTH, 0, TEXTURE_WIDTH, TEXTURE_WIDTH)); tetrominoSprite.setPosition(sf::Vector2f(TEXTURE_WIDTH*j*blockScaleFactor, TEXTURE_WIDTH*i*blockScaleFactor)); window->draw(tetrominoSprite); } } } } void TetrisDrawer::drawGameInfo(short level, int score) { std::stringstream ss; ss << "Level " << level << " - Score " << score; gameInfoText.setString(ss.str()); window->draw(gameInfoBox); window->draw(gameInfoText); } void TetrisDrawer::drawNextTetrimino(Tetrimino & next) { window->draw(nextTetriminoBox); window->draw(nextTetriminoText); } <commit_msg>Add next tetri<commit_after>#include "TetrisDrawer.h" #include <vector> TetrisDrawer::TetrisDrawer(sf::RenderWindow & window, Board & board) { this->window = &window; this->board = &board; blockScaleFactor = 1.0f; //backgroundScaleFactor = blockScaleFactor / 2.0f; if (!tetrominoTexture.loadFromFile(TEXTURE_DIR)) { //error std::cout << "Error tetromino"; } tetrominoTexture.setRepeated(true); tetrominoSprite.setTexture(tetrominoTexture); tetrominoSprite.setScale(sf::Vector2f(blockScaleFactor, blockScaleFactor)); if (!backgroundTexture.loadFromFile(BACKGROUND_DIR)) { //error std::cout << "Error background"; } backgroundTexture.setRepeated(true); backgroundTexture.setSmooth(true); background.setSize(sf::Vector2f(BACKGROUND_WIDTH, BACKGROUND_WIDTH)); background.setTexture(&backgroundTexture); if (!gameFont.loadFromFile(FONT_DIR)) { //Font error std::cout << "Font error"; } //Fill color for the boxes sf::Color boxColor(0, 0, 0, 192); gameInfoBox.setSize(sf::Vector2f(this->window->getSize().x / 3.f, this->window->getSize().y / 6.f)); gameInfoBox.setFillColor(boxColor); gameInfoBox.setPosition(this->window->getSize().x * (3.f/5.f), this->window->getSize().y / 10.f); float textSize = gameInfoBox.getSize().x / 10.f; gameInfoText.setFont(gameFont); gameInfoText.setCharacterSize(textSize); gameInfoText.setPosition(gameInfoBox.getPosition().x + gameInfoBox.getSize().x / 13.f, gameInfoBox.getPosition().y + gameInfoBox.getSize().y / 3.f); nextTetriminoBox.setFillColor(boxColor); nextTetriminoBox.setSize(sf::Vector2f(gameInfoBox.getSize().x, TEXTURE_WIDTH * 7)); nextTetriminoBox.setPosition(gameInfoBox.getPosition().x, gameInfoBox.getPosition().y + (gameInfoBox.getSize().y * 1.5f)); nextTetriminoText.setCharacterSize(textSize); nextTetriminoText.setFont(gameFont); nextTetriminoText.setString("Next Tetrimino"); nextTetriminoText.setPosition(nextTetriminoBox.getPosition().x + nextTetriminoBox.getSize().x / 5.f, nextTetriminoBox.getPosition().y + nextTetriminoBox.getSize().y / 15.f); } TetrisDrawer::~TetrisDrawer() { } void TetrisDrawer::draw(short level, int score, Tetrimino & next) { window->clear(sf::Color::Black); drawBackground(); drawBoard(); drawGameInfo(level, score); drawNextTetrimino(next); window->display(); } void TetrisDrawer::drawBackground() { for (float i = 0.f; i < window->getSize().x; i+=BACKGROUND_WIDTH) { for (float j = 0.f; j < window->getSize().y; j+=BACKGROUND_WIDTH) { background.setPosition(sf::Vector2f(i, j)); window->draw(background); } } } void TetrisDrawer::drawBoard() { const std::vector<short> * map = board->getBoard(); short rows = board->getRows(); short columns = board->getColumns(); int position; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { position = ((columns)*i) + j; if ((*map)[position] != board->getPaddingValue()) { tetrominoSprite.setTextureRect(sf::IntRect((*map)[position] * TEXTURE_WIDTH, 0, TEXTURE_WIDTH, TEXTURE_WIDTH)); tetrominoSprite.setPosition(sf::Vector2f(TEXTURE_WIDTH*j*blockScaleFactor, TEXTURE_WIDTH*i*blockScaleFactor)); window->draw(tetrominoSprite); } } } } void TetrisDrawer::drawGameInfo(short level, int score) { std::stringstream ss; ss << "Level " << level << " - Score " << score; gameInfoText.setString(ss.str()); window->draw(gameInfoBox); window->draw(gameInfoText); } void TetrisDrawer::drawNextTetrimino(Tetrimino & next) { window->draw(nextTetriminoBox); window->draw(nextTetriminoText); unsigned short * map = next.getMap(); unsigned short color = next.getColor(); sf::Vector2f startingPosition = nextTetriminoBox.getPosition() + sf::Vector2f(TEXTURE_WIDTH * 4, TEXTURE_WIDTH * 2); for (int row = 0; row < Tetrimino::MAP_LENGTH; row++) { for (int column = 0; column < Tetrimino::MAP_LENGTH; column++) { int position = (row * Tetrimino::MAP_LENGTH) + column; if (map[position] != 0) { tetrominoSprite.setTextureRect(sf::IntRect(map[position] * TEXTURE_WIDTH * color, 0, TEXTURE_WIDTH, TEXTURE_WIDTH)); tetrominoSprite.setPosition(sf::Vector2f(TEXTURE_WIDTH*column + startingPosition.x, TEXTURE_WIDTH*row + startingPosition.y)); window->draw(tetrominoSprite); } } } } <|endoftext|>
<commit_before>//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2016 Ryo Suzuki // Copyright (c) 2016 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # pragma once # include "Fwd.hpp" # include "String.hpp" # include "Duration.hpp" namespace s3d { Date operator +(const Date& date, const Days& days); Date operator -(const Date& date, const Days& days); namespace detail { constexpr int32 DaysInMonth[2][12] { { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }, // common year { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } // leap year }; } /// <summary> /// 日付 /// </summary> struct Date { /// <summary> /// 西暦 /// </summary> int32 year; /// <summary> /// 月 [1-12] /// </summary> int32 month; /// <summary> /// 日 [1-31] /// </summary> int32 day; /// <summary> /// 曜日 /// </summary> enum DayOfWeek : int32 { /// <summary> /// 日曜日 /// </summary> Sunday, /// <summary> /// 月曜日 /// </summary> Monday, /// <summary> /// 火曜日 /// </summary> Tuesday, /// <summary> /// 水曜日 /// </summary> Wednesday, /// <summary> /// 木曜日 /// </summary> Thursday, /// <summary> /// 金曜日 /// </summary> Friday, /// <summary> /// 土曜日 /// </summary> Saturday }; /// <summary> /// 曜日を返します。 /// </summary> /// <returns> /// 曜日 /// </returns> constexpr DayOfWeek dayOfWeek() const noexcept { return static_cast<DayOfWeek>((month == 1 || month == 2) ? ((year - 1) + (year - 1) / 4 - (year - 1) / 100 + (year - 1) / 400 + (13 * (month + 12) + 8) / 5 + day) % 7 : (year + year / 4 - year / 100 + year / 400 + (13 * month + 8) / 5 + day) % 7); } /// <summary> /// 曜日を日本語で返します。 /// </summary> /// <returns> /// 日本語の曜日 /// </returns> const String& dayOfWeekJP() const; /// <summary> /// 曜日を英語で返します。 /// </summary> /// <returns> /// 英語の曜日 /// </returns> const String& dayOfWeekEN() const; /// <summary> /// 現在のローカルの年月日と一致するかを返します。 /// </summary> /// <returns> /// 現在のローカルの年月日と一致する場合は true, それ以外の場合は false /// </returns> bool isToday() const; /// <summary> /// うるう年であるかを返します。 /// </summary> /// <returns> /// うるう年である場合は true, それ以外の場合は false /// </returns> constexpr bool isLeapYear() const noexcept { return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0; } /// <summary> /// 月の日数を返します。 /// </summary> /// <returns> /// 月の日数 /// </returns> constexpr int32 daysInMonth() const noexcept { return (month < 1 || 13 <= month) ? 0 : detail::DaysInMonth[isLeapYear()][month - 1]; } /// <summary> /// 1 年の日数を返します。 /// </summary> /// <returns> /// 1 年の日数 /// </returns> constexpr int32 daysInYear() const noexcept { return isLeapYear() ? 366 : 365; } /// <summary> /// 日付の妥当性を返します。 /// </summary> /// <returns> /// 日付が正しい範囲の値であれば true, それ以外の場合は false /// </returns> constexpr bool isValid() const noexcept { return (1 <= month && month <= 12) && (1 <= day && day <= daysInMonth()); } /// <summary> /// デフォルトコンストラクタ /// </summary> Date() noexcept = default; /// <summary> /// 日付を作成します。 /// </summary> /// <param name="_year"> /// 西暦 /// </param> /// <param name="_month"> /// 月 /// </param> /// <param name="_day"> /// 日 /// </param> explicit constexpr Date(int32 _year, int32 _month = 1, int32 _day = 1) noexcept : year(_year) , month(_month) , day(_day) {} /// <summary> /// 日付を指定したフォーマットの文字列で返します。 /// フォーマット指定のパターンは以下の通りです。 /// /// yyyy 4 桁の年 (0001-) /// yy 2 桁の年 (00-99) /// y 年 (1-) /// MMMM 英語の月 (January-December) /// MMM 英語の月の略称 (Jan-Dec) /// MM 2 桁の月 (01-12) /// M 1-2 桁の月 (1-12) /// dd 2 桁の日 (01-31) /// d 1-2 桁の日 (1-31) /// EEEE 英語の曜日 (Sunday-Saturday) /// EEE 英語の曜日の略称 (Sun-Sat) /// E 日本語の曜日 (日-土) /// /// 引用符で囲まれていないアルファベットはパターン文字として解釈されます。 /// '' は単一引用符を表します。 /// </summary> /// <param name="format"> /// フォーマット指定 /// </param> /// <returns> /// フォーマットされた日付 /// </returns> String format(const String& format = L"yyyy/M/d") const; /// <summary> /// 昨日のローカルの日付を返します。 /// </summary> /// <returns> /// 昨日のローカルの日付 /// </returns> static Date Yesterday() { return Today() - Days(1); } /// <summary> /// 現在のローカルの日付を返します。 /// </summary> /// <returns> /// 現在のローカルの日付 /// </returns> static Date Today(); /// <summary> /// 明日のローカルの日付を返します。 /// </summary> /// <returns> /// 明日のローカルの日付 /// </returns> static Date Tomorrow() { return Today() + Days(1); } /// <summary> /// 日付を進めます。 /// </summary> /// <param name="days"> /// 進める日数 /// </param> /// <returns> /// *this /// </returns> Date& operator +=(const Days& days); /// <summary> /// 日付を戻します。 /// </summary> /// <param name="days"> /// 戻す日数 /// </param> /// <returns> /// *this /// </returns> Date& operator -=(const Days& days) { return *this += (-days); } }; /// <summary> /// 日付を進めます。 /// </summary> /// <param name="date"> /// 日付 /// </param> /// <param name="days"> /// 進める日数 /// </param> /// <returns> /// 進めた結果の日付 /// </returns> Date operator +(const Date& date, const Days& days); /// <summary> /// 日付を戻します。 /// </summary> /// <param name="date"> /// 日付 /// </param> /// <param name="days"> /// 戻す日数 /// </param> /// <returns> /// 戻した結果の日付 /// </returns> inline Date operator -(const Date& date, const Days& days) { return date + (-days); } /// <summary> /// 2 つの日付の間の日数を計算します。 /// </summary> /// <param name="to"> /// 終わりの日付 /// </param> /// <param name="from"> /// はじめの日付 /// </param> /// <returns> /// 2 つの日付の間の日数 /// </returns> Days operator -(const Date& to, const Date& from); /// <summary> /// 2 つの日付が等しいかを調べます。 /// </summary> /// <param name="a"> /// 比較する日付 /// </param> /// <param name="b"> /// 比較する日付 /// </param> /// <returns> /// 2 つの日付が等しい場合 true, それ以外の場合は false /// </returns> inline constexpr bool operator ==(const Date& a, const Date& b) noexcept { return a.year == b.year && a.month == b.month && a.day == b.day; } /// <summary> /// 2 つの日付が異なるかを調べます。 /// </summary> /// <param name="a"> /// 比較する日付 /// </param> /// <param name="b"> /// 比較する日付 /// </param> /// <returns> /// 2 つの日付が異なる場合 true, それ以外の場合は false /// </returns> inline constexpr bool operator !=(const Date& a, const Date& b) noexcept { return !(a == b); } /// <summary> /// 日付の &lt; 比較を行います。 /// </summary> /// <param name="a"> /// 比較する日付 /// </param> /// <param name="b"> /// 比較する日付 /// </param> /// <returns> /// 比較結果 /// </returns> inline bool operator <(const Date& a, const Date& b) { return ::memcmp(&a, &b, sizeof(Date)) < 0; } /// <summary> /// 日付の &gt; 比較を行います。 /// </summary> /// <param name="a"> /// 比較する日付 /// </param> /// <param name="b"> /// 比較する日付 /// </param> /// <returns> /// 比較結果 /// </returns> inline bool operator >(const Date& a, const Date& b) { return ::memcmp(&a, &b, sizeof(Date)) > 0; } /// <summary> /// 日付の &lt;= 比較を行います。 /// </summary> /// <param name="a"> /// 比較する日付 /// </param> /// <param name="b"> /// 比較する日付 /// </param> /// <returns> /// 比較結果 /// </returns> inline bool operator <=(const Date& a, const Date& b) { return !(a > b); } /// <summary> /// 日付の &gt;= 比較を行います。 /// </summary> /// <param name="a"> /// 比較する日付 /// </param> /// <param name="b"> /// 比較する日付 /// </param> /// <returns> /// 比較結果 /// </returns> inline bool operator >=(const Date& a, const Date& b) { return !(a < b); } template <class CharType> inline std::basic_ostream<CharType> & operator <<(std::basic_ostream<CharType> os, const Date& date) { return os << date.format(); } inline void Formatter(FormatData& formatData, const Date& date) { formatData.string.append(date.format()); } } namespace std { template <> struct hash<s3d::Date> { size_t operator()(const s3d::Date& date) const; }; } <commit_msg>memcmp関数のためにstring.hをインクルード<commit_after>//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2016 Ryo Suzuki // Copyright (c) 2016 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # pragma once // memcmp # ifdef SIV3D_TARGET_LINUX # include <string.h> # endif # include "Fwd.hpp" # include "String.hpp" # include "Duration.hpp" namespace s3d { Date operator +(const Date& date, const Days& days); Date operator -(const Date& date, const Days& days); namespace detail { constexpr int32 DaysInMonth[2][12] { { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }, // common year { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } // leap year }; } /// <summary> /// 日付 /// </summary> struct Date { /// <summary> /// 西暦 /// </summary> int32 year; /// <summary> /// 月 [1-12] /// </summary> int32 month; /// <summary> /// 日 [1-31] /// </summary> int32 day; /// <summary> /// 曜日 /// </summary> enum DayOfWeek : int32 { /// <summary> /// 日曜日 /// </summary> Sunday, /// <summary> /// 月曜日 /// </summary> Monday, /// <summary> /// 火曜日 /// </summary> Tuesday, /// <summary> /// 水曜日 /// </summary> Wednesday, /// <summary> /// 木曜日 /// </summary> Thursday, /// <summary> /// 金曜日 /// </summary> Friday, /// <summary> /// 土曜日 /// </summary> Saturday }; /// <summary> /// 曜日を返します。 /// </summary> /// <returns> /// 曜日 /// </returns> constexpr DayOfWeek dayOfWeek() const noexcept { return static_cast<DayOfWeek>((month == 1 || month == 2) ? ((year - 1) + (year - 1) / 4 - (year - 1) / 100 + (year - 1) / 400 + (13 * (month + 12) + 8) / 5 + day) % 7 : (year + year / 4 - year / 100 + year / 400 + (13 * month + 8) / 5 + day) % 7); } /// <summary> /// 曜日を日本語で返します。 /// </summary> /// <returns> /// 日本語の曜日 /// </returns> const String& dayOfWeekJP() const; /// <summary> /// 曜日を英語で返します。 /// </summary> /// <returns> /// 英語の曜日 /// </returns> const String& dayOfWeekEN() const; /// <summary> /// 現在のローカルの年月日と一致するかを返します。 /// </summary> /// <returns> /// 現在のローカルの年月日と一致する場合は true, それ以外の場合は false /// </returns> bool isToday() const; /// <summary> /// うるう年であるかを返します。 /// </summary> /// <returns> /// うるう年である場合は true, それ以外の場合は false /// </returns> constexpr bool isLeapYear() const noexcept { return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0; } /// <summary> /// 月の日数を返します。 /// </summary> /// <returns> /// 月の日数 /// </returns> constexpr int32 daysInMonth() const noexcept { return (month < 1 || 13 <= month) ? 0 : detail::DaysInMonth[isLeapYear()][month - 1]; } /// <summary> /// 1 年の日数を返します。 /// </summary> /// <returns> /// 1 年の日数 /// </returns> constexpr int32 daysInYear() const noexcept { return isLeapYear() ? 366 : 365; } /// <summary> /// 日付の妥当性を返します。 /// </summary> /// <returns> /// 日付が正しい範囲の値であれば true, それ以外の場合は false /// </returns> constexpr bool isValid() const noexcept { return (1 <= month && month <= 12) && (1 <= day && day <= daysInMonth()); } /// <summary> /// デフォルトコンストラクタ /// </summary> Date() noexcept = default; /// <summary> /// 日付を作成します。 /// </summary> /// <param name="_year"> /// 西暦 /// </param> /// <param name="_month"> /// 月 /// </param> /// <param name="_day"> /// 日 /// </param> explicit constexpr Date(int32 _year, int32 _month = 1, int32 _day = 1) noexcept : year(_year) , month(_month) , day(_day) {} /// <summary> /// 日付を指定したフォーマットの文字列で返します。 /// フォーマット指定のパターンは以下の通りです。 /// /// yyyy 4 桁の年 (0001-) /// yy 2 桁の年 (00-99) /// y 年 (1-) /// MMMM 英語の月 (January-December) /// MMM 英語の月の略称 (Jan-Dec) /// MM 2 桁の月 (01-12) /// M 1-2 桁の月 (1-12) /// dd 2 桁の日 (01-31) /// d 1-2 桁の日 (1-31) /// EEEE 英語の曜日 (Sunday-Saturday) /// EEE 英語の曜日の略称 (Sun-Sat) /// E 日本語の曜日 (日-土) /// /// 引用符で囲まれていないアルファベットはパターン文字として解釈されます。 /// '' は単一引用符を表します。 /// </summary> /// <param name="format"> /// フォーマット指定 /// </param> /// <returns> /// フォーマットされた日付 /// </returns> String format(const String& format = L"yyyy/M/d") const; /// <summary> /// 昨日のローカルの日付を返します。 /// </summary> /// <returns> /// 昨日のローカルの日付 /// </returns> static Date Yesterday() { return Today() - Days(1); } /// <summary> /// 現在のローカルの日付を返します。 /// </summary> /// <returns> /// 現在のローカルの日付 /// </returns> static Date Today(); /// <summary> /// 明日のローカルの日付を返します。 /// </summary> /// <returns> /// 明日のローカルの日付 /// </returns> static Date Tomorrow() { return Today() + Days(1); } /// <summary> /// 日付を進めます。 /// </summary> /// <param name="days"> /// 進める日数 /// </param> /// <returns> /// *this /// </returns> Date& operator +=(const Days& days); /// <summary> /// 日付を戻します。 /// </summary> /// <param name="days"> /// 戻す日数 /// </param> /// <returns> /// *this /// </returns> Date& operator -=(const Days& days) { return *this += (-days); } }; /// <summary> /// 日付を進めます。 /// </summary> /// <param name="date"> /// 日付 /// </param> /// <param name="days"> /// 進める日数 /// </param> /// <returns> /// 進めた結果の日付 /// </returns> Date operator +(const Date& date, const Days& days); /// <summary> /// 日付を戻します。 /// </summary> /// <param name="date"> /// 日付 /// </param> /// <param name="days"> /// 戻す日数 /// </param> /// <returns> /// 戻した結果の日付 /// </returns> inline Date operator -(const Date& date, const Days& days) { return date + (-days); } /// <summary> /// 2 つの日付の間の日数を計算します。 /// </summary> /// <param name="to"> /// 終わりの日付 /// </param> /// <param name="from"> /// はじめの日付 /// </param> /// <returns> /// 2 つの日付の間の日数 /// </returns> Days operator -(const Date& to, const Date& from); /// <summary> /// 2 つの日付が等しいかを調べます。 /// </summary> /// <param name="a"> /// 比較する日付 /// </param> /// <param name="b"> /// 比較する日付 /// </param> /// <returns> /// 2 つの日付が等しい場合 true, それ以外の場合は false /// </returns> inline constexpr bool operator ==(const Date& a, const Date& b) noexcept { return a.year == b.year && a.month == b.month && a.day == b.day; } /// <summary> /// 2 つの日付が異なるかを調べます。 /// </summary> /// <param name="a"> /// 比較する日付 /// </param> /// <param name="b"> /// 比較する日付 /// </param> /// <returns> /// 2 つの日付が異なる場合 true, それ以外の場合は false /// </returns> inline constexpr bool operator !=(const Date& a, const Date& b) noexcept { return !(a == b); } /// <summary> /// 日付の &lt; 比較を行います。 /// </summary> /// <param name="a"> /// 比較する日付 /// </param> /// <param name="b"> /// 比較する日付 /// </param> /// <returns> /// 比較結果 /// </returns> inline bool operator <(const Date& a, const Date& b) { return ::memcmp(&a, &b, sizeof(Date)) < 0; } /// <summary> /// 日付の &gt; 比較を行います。 /// </summary> /// <param name="a"> /// 比較する日付 /// </param> /// <param name="b"> /// 比較する日付 /// </param> /// <returns> /// 比較結果 /// </returns> inline bool operator >(const Date& a, const Date& b) { return ::memcmp(&a, &b, sizeof(Date)) > 0; } /// <summary> /// 日付の &lt;= 比較を行います。 /// </summary> /// <param name="a"> /// 比較する日付 /// </param> /// <param name="b"> /// 比較する日付 /// </param> /// <returns> /// 比較結果 /// </returns> inline bool operator <=(const Date& a, const Date& b) { return !(a > b); } /// <summary> /// 日付の &gt;= 比較を行います。 /// </summary> /// <param name="a"> /// 比較する日付 /// </param> /// <param name="b"> /// 比較する日付 /// </param> /// <returns> /// 比較結果 /// </returns> inline bool operator >=(const Date& a, const Date& b) { return !(a < b); } template <class CharType> inline std::basic_ostream<CharType> & operator <<(std::basic_ostream<CharType> os, const Date& date) { return os << date.format(); } inline void Formatter(FormatData& formatData, const Date& date) { formatData.string.append(date.format()); } } namespace std { template <> struct hash<s3d::Date> { size_t operator()(const s3d::Date& date) const; }; } <|endoftext|>
<commit_before>#include <algorithm> #include "yaml-cpp/node/convert.h" namespace { // we're not gonna mess with the mess that is all the isupper/etc. functions bool IsLower(char ch) { return 'a' <= ch && ch <= 'z'; } bool IsUpper(char ch) { return 'A' <= ch && ch <= 'Z'; } char ToLower(char ch) { return IsUpper(ch) ? ch + 'a' - 'A' : ch; } std::string tolower(const std::string& str) { std::string s(str); std::transform(s.begin(), s.end(), s.begin(), ToLower); return s; } template <typename T> bool IsEntirely(const std::string& str, T func) { for (std::size_t i = 0; i < str.size(); i++) if (!func(str[i])) return false; return true; } // IsFlexibleCase // . Returns true if 'str' is: // . UPPERCASE // . lowercase // . Capitalized bool IsFlexibleCase(const std::string& str) { if (str.empty()) return true; if (IsEntirely(str, IsLower)) return true; bool firstcaps = IsUpper(str[0]); std::string rest = str.substr(1); return firstcaps && (IsEntirely(rest, IsLower) || IsEntirely(rest, IsUpper)); } } namespace YAML { bool convert<bool>::decode(const Node& node, bool& rhs) { if (!node.IsScalar()) return false; // we can't use iostream bool extraction operators as they don't // recognize all possible values in the table below (taken from // http://yaml.org/type/bool.html) static const struct { std::string truename, falsename; } names[] = { {"y", "n"}, {"yes", "no"}, {"true", "false"}, {"on", "off"}, }; if (!IsFlexibleCase(node.Scalar())) return false; for (unsigned i = 0; i < sizeof(names) / sizeof(names[0]); i++) { if (names[i].truename == tolower(node.Scalar())) { rhs = true; return true; } if (names[i].falsename == tolower(node.Scalar())) { rhs = false; return true; } } return false; } } <commit_msg>only convert boolean strings of the 1.2 spec<commit_after>#include <algorithm> #include "yaml-cpp/node/convert.h" namespace { // we're not gonna mess with the mess that is all the isupper/etc. functions bool IsLower(char ch) { return 'a' <= ch && ch <= 'z'; } bool IsUpper(char ch) { return 'A' <= ch && ch <= 'Z'; } char ToLower(char ch) { return IsUpper(ch) ? ch + 'a' - 'A' : ch; } std::string tolower(const std::string& str) { std::string s(str); std::transform(s.begin(), s.end(), s.begin(), ToLower); return s; } template <typename T> bool IsEntirely(const std::string& str, T func) { for (std::size_t i = 0; i < str.size(); i++) if (!func(str[i])) return false; return true; } // IsFlexibleCase // . Returns true if 'str' is: // . UPPERCASE // . lowercase // . Capitalized bool IsFlexibleCase(const std::string& str) { if (str.empty()) return true; if (IsEntirely(str, IsLower)) return true; bool firstcaps = IsUpper(str[0]); std::string rest = str.substr(1); return firstcaps && (IsEntirely(rest, IsLower) || IsEntirely(rest, IsUpper)); } } namespace YAML { bool convert<bool>::decode(const Node& node, bool& rhs) { if (!node.IsScalar()) return false; // we can't use iostream bool extraction operators as they don't // recognize all possible values in the table below (taken from // http://yaml.org/type/bool.html) static const struct { std::string truename, falsename; } names[] = { // 1.1 spec // {"y", "n"}, {"yes", "no"}, {"true", "false"}, {"on", "off"}, // 1.2 spec {"true", "false"}, }; if (!IsFlexibleCase(node.Scalar())) return false; for (unsigned i = 0; i < sizeof(names) / sizeof(names[0]); i++) { if (names[i].truename == tolower(node.Scalar())) { rhs = true; return true; } if (names[i].falsename == tolower(node.Scalar())) { rhs = false; return true; } } return false; } } <|endoftext|>
<commit_before>#include "MainMenuScene.h" #include "NNInputSystem.h" #include "NNSceneDirector.h" #include "NNApplication.h" #include "StoryScene.h" MainMenuScene::MainMenuScene() : m_MainMenuImage(nullptr) { m_MenuSellction = 0; float width = (float)NNApplication::GetInstance()->GetScreenWidth(); float height = (float)NNApplication::GetInstance()->GetScreenHeight(); m_MainMenuImage = NNSprite::Create( L"Sprite/MainMenu.jpg" ); m_MainMenuImage->SetPosition( width/2, height/2 ); m_MainMenuImage->SetCenter( m_MainMenuImage->GetPositionX()/2.f, m_MainMenuImage->GetPositionY()/2.f + 70.f ); AddChild( m_MainMenuImage ); m_MainMenuSellcetionBar = NNSprite::Create( L"Sprite/MenuSellectionBar.png"); m_MainMenuSellcetionBar->SetPosition( width/2 + 200.f, height/2 + 200.f + m_MenuSellction * 50 ); AddChild( m_MainMenuSellcetionBar ) ; m_MianMenuLable[MENU_PLAY] = NNLabel::Create( L"Play", L" ", 35.f ); m_MianMenuLable[MENU_PLAY]->SetPosition( width/2 + 200.f, height/2 + 150.f ); AddChild( m_MianMenuLable[MENU_PLAY] ); m_MianMenuLable[MENU_EXIT] = NNLabel::Create( L"Exit", L" ", 35.f ); m_MianMenuLable[MENU_EXIT]->SetPosition( width/2 + 200.f, height/2 + 200.f); AddChild( m_MianMenuLable[MENU_EXIT] ); } MainMenuScene::~MainMenuScene() { } void MainMenuScene::Render() { NNScene::Render(); } void MainMenuScene::Update( float dTime ) { NNScene::Update( dTime ); m_MainMenuImage->SetVisible( true ); float width = (float)NNApplication::GetInstance()->GetScreenWidth(); float height = (float)NNApplication::GetInstance()->GetScreenHeight(); if ( NNInputSystem::GetInstance()->GetKeyState( VK_UP ) == KEY_DOWN || NNInputSystem::GetInstance()->GetKeyState( VK_LEFT ) == KEY_DOWN ) { --m_MenuSellction; } if ( NNInputSystem::GetInstance()->GetKeyState( VK_DOWN ) == KEY_DOWN || NNInputSystem::GetInstance()->GetKeyState( VK_RIGHT ) == KEY_DOWN ) { ++m_MenuSellction; } m_MainMenuSellcetionBar->SetPosition( width/2 + 200.f, height/2 + 200.f + m_MenuSellction * 50 ); m_MenuSellction = ( m_MenuSellction + MENU_EXIT + 1 ) % ( MENU_EXIT + 1); if ( NNInputSystem::GetInstance()->GetKeyState( VK_RETURN ) == KEY_UP ) { NNSceneDirector::GetInstance()->ChangeScene( StoryScene::Create() ); return; } }<commit_msg>@ MenuSellecter image changed@ MenuSellecter image changed<commit_after>#include "MainMenuScene.h" #include "NNInputSystem.h" #include "NNSceneDirector.h" #include "NNApplication.h" #include "StoryScene.h" MainMenuScene::MainMenuScene() : m_MainMenuImage(nullptr) { m_MenuSellction = 0; float width = (float)NNApplication::GetInstance()->GetScreenWidth(); float height = (float)NNApplication::GetInstance()->GetScreenHeight(); m_MainMenuImage = NNSprite::Create( L"Sprite/MainMenu.jpg" ); m_MainMenuImage->SetPosition( width/2, height/2 ); m_MainMenuImage->SetCenter( m_MainMenuImage->GetPositionX()/2.f, m_MainMenuImage->GetPositionY()/2.f + 70.f ); AddChild( m_MainMenuImage ); /* MenuSellectionBar type m_MainMenuSellcetionBar = NNSprite::Create( L"Sprite/MenuSellectionBar.png"); m_MainMenuSellcetionBar->SetPosition( width/2 + 200.f, height/2 + 200.f + m_MenuSellction * 50 ); AddChild( m_MainMenuSellcetionBar ) ; */ m_MainMenuSellcetionBar = NNSprite::Create( L"Sprite/MenuSellecter.gif"); m_MainMenuSellcetionBar->SetPosition( width/2, height/2 ); m_MainMenuSellcetionBar->SetScale( 0.5f, 0.5f ); AddChild( m_MainMenuSellcetionBar ) ; m_MianMenuLable[MENU_PLAY] = NNLabel::Create( L"Play", L" ", 35.f ); m_MianMenuLable[MENU_PLAY]->SetPosition( width/2 + 200.f, height/2 + 150.f ); AddChild( m_MianMenuLable[MENU_PLAY] ); m_MianMenuLable[MENU_EXIT] = NNLabel::Create( L"Exit", L" ", 35.f ); m_MianMenuLable[MENU_EXIT]->SetPosition( width/2 + 200.f, height/2 + 200.f); AddChild( m_MianMenuLable[MENU_EXIT] ); } MainMenuScene::~MainMenuScene() { } void MainMenuScene::Render() { NNScene::Render(); } void MainMenuScene::Update( float dTime ) { NNScene::Update( dTime ); m_MainMenuImage->SetVisible( true ); float width = (float)NNApplication::GetInstance()->GetScreenWidth(); float height = (float)NNApplication::GetInstance()->GetScreenHeight(); if ( NNInputSystem::GetInstance()->GetKeyState( VK_UP ) == KEY_DOWN || NNInputSystem::GetInstance()->GetKeyState( VK_LEFT ) == KEY_DOWN ) { --m_MenuSellction; } if ( NNInputSystem::GetInstance()->GetKeyState( VK_DOWN ) == KEY_DOWN || NNInputSystem::GetInstance()->GetKeyState( VK_RIGHT ) == KEY_DOWN ) { ++m_MenuSellction; } m_MainMenuSellcetionBar->SetPosition( width/2 + 150.f, height/2 + 150.f + m_MenuSellction * 50 ); m_MenuSellction = ( m_MenuSellction + MENU_EXIT + 1 ) % ( MENU_EXIT + 1); if ( m_MenuSellction == 0 && NNInputSystem::GetInstance()->GetKeyState(VK_RETURN) == KEY_UP ) { NNSceneDirector::GetInstance()->ChangeScene( StoryScene::Create() ); } else if ( m_MenuSellction == 1 ) { // exit } }<|endoftext|>
<commit_before> #include "NNApplication.h" #include "NNInputSystem.h" #include "NNAudioSystem.h" #include "NNResourceManager.h" #include <stdio.h> NNApplication* NNApplication::m_pInstance = nullptr; NNApplication::NNApplication() : m_Hwnd(nullptr), m_hInstance(nullptr), m_ScreenHeight(0), m_ScreenWidth(0), m_Fps(0.f), m_ElapsedTime(0.f), m_DeltaTime(0.f), m_PrevTime(0), m_NowTime(0), m_Renderer(nullptr), m_pSceneDirector(nullptr), m_RendererStatus(UNKNOWN),m_DestroyWindow(false) { } NNApplication::~NNApplication() { } NNApplication* NNApplication::GetInstance() { if ( m_pInstance == nullptr ) { m_pInstance = new NNApplication(); } return m_pInstance; } void NNApplication::ReleaseInstance() { if ( m_pInstance != nullptr ) { delete m_pInstance; m_pInstance = nullptr; } } bool NNApplication::Init( wchar_t* title, int width, int height, RendererStatus renderStatus ) { m_hInstance = GetModuleHandle(0); m_Title = title; m_ScreenWidth = width; m_ScreenHeight = height; m_RendererStatus = renderStatus; _CreateWindow( m_Title, m_ScreenWidth, m_ScreenHeight ); _CreateRenderer( renderStatus ); m_pSceneDirector = NNSceneDirector::GetInstance(); m_Renderer->Init(); m_pSceneDirector->Init(); return true; } bool NNApplication::Release() { if ( m_DestroyWindow == true ) { ReleaseInstance(); return true; } m_pSceneDirector->Release(); NNSceneDirector::ReleaseInstance(); NNResourceManager::ReleaseInstance(); NNInputSystem::ReleaseInstance(); NNAudioSystem::ReleaseInstance(); SafeDelete( m_Renderer ); ReleaseInstance(); return true; } bool NNApplication::Run() { MSG msg; ZeroMemory( &msg, sizeof(msg) ); while (true) { if ( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) ) { if ( msg.message == WM_QUIT ) { return true; } TranslateMessage( &msg ); DispatchMessage( &msg ); } else { m_NowTime = timeGetTime(); if ( m_PrevTime == 0.f ) { m_PrevTime = m_NowTime; } m_DeltaTime = static_cast<float>(m_NowTime - m_PrevTime) / 1000.f; m_PrevTime = m_NowTime; m_Fps = 1.f / m_DeltaTime; m_ElapsedTime += m_DeltaTime; NNInputSystem::GetInstance()->UpdateKeyState(); m_pSceneDirector->UpdateScene( m_DeltaTime ); m_Renderer->Begin(); m_Renderer->Clear(); m_pSceneDirector->RenderScene(); m_Renderer->End(); if ( NNInputSystem::GetInstance()->GetKeyState( VK_ESCAPE ) == KEY_DOWN ) { PostQuitMessage(0); } } } return true; } bool NNApplication::_CreateWindow( wchar_t* title, int width, int height ) { WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.cbClsExtra = NULL; wcex.cbWndExtra = NULL; wcex.hInstance = m_hInstance; wcex.hIcon = NULL; wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wcex.lpszMenuName = NULL; wcex.lpszClassName = L"NNApplication"; wcex.hIconSm = NULL; wcex.hIcon = NULL; RegisterClassEx( &wcex ); DWORD style = WS_OVERLAPPEDWINDOW; m_Hwnd = CreateWindow( L"NNApplication", title, style, CW_USEDEFAULT, CW_USEDEFAULT, width, height, NULL, NULL, m_hInstance, NULL); ShowWindow( m_Hwnd, SW_SHOWNORMAL ); return true; } bool NNApplication::_CreateRenderer( RendererStatus renderStatus ) { switch( renderStatus ) { case D2D: m_Renderer = new NND2DRenderer(); break; default: return false; } return true; } <commit_msg>* Fixed NNApplication.cpp<commit_after> #include "NNApplication.h" #include "NNInputSystem.h" #include "NNAudioSystem.h" #include "NNResourceManager.h" #include <stdio.h> NNApplication* NNApplication::m_pInstance = nullptr; NNApplication::NNApplication() : m_Hwnd(nullptr), m_hInstance(nullptr), m_ScreenHeight(0), m_ScreenWidth(0), m_Fps(0.f), m_ElapsedTime(0.f), m_DeltaTime(0.f), m_PrevTime(0), m_NowTime(0), m_Renderer(nullptr), m_pSceneDirector(nullptr), m_RendererStatus(UNKNOWN),m_DestroyWindow(false) { } NNApplication::~NNApplication() { } NNApplication* NNApplication::GetInstance() { if ( m_pInstance == nullptr ) { m_pInstance = new NNApplication(); } return m_pInstance; } void NNApplication::ReleaseInstance() { if ( m_pInstance != nullptr ) { delete m_pInstance; m_pInstance = nullptr; } } bool NNApplication::Init( wchar_t* title, int width, int height, RendererStatus renderStatus ) { m_hInstance = GetModuleHandle(0); m_Title = title; m_ScreenWidth = width; m_ScreenHeight = height; m_RendererStatus = renderStatus; _CreateWindow( m_Title, m_ScreenWidth, m_ScreenHeight ); _CreateRenderer( renderStatus ); m_pSceneDirector = NNSceneDirector::GetInstance(); m_Renderer->Init(); m_pSceneDirector->Init(); return true; } bool NNApplication::Release() { if ( m_DestroyWindow == true ) { ReleaseInstance(); return true; } m_pSceneDirector->Release(); NNSceneDirector::ReleaseInstance(); NNResourceManager::ReleaseInstance(); NNInputSystem::ReleaseInstance(); NNAudioSystem::ReleaseInstance(); SafeDelete( m_Renderer ); ReleaseInstance(); return true; } bool NNApplication::Run() { MSG msg; ZeroMemory( &msg, sizeof(msg) ); while (true) { if ( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) ) { if ( msg.message == WM_QUIT ) { return true; } TranslateMessage( &msg ); DispatchMessage( &msg ); } else { m_NowTime = timeGetTime(); if ( m_PrevTime == 0.f ) { m_PrevTime = m_NowTime; } m_DeltaTime = static_cast<float>(m_NowTime - m_PrevTime) / 1000.f; m_PrevTime = m_NowTime; m_Fps = 1.f / m_DeltaTime; m_ElapsedTime += m_DeltaTime; NNInputSystem::GetInstance()->UpdateKeyState(); m_pSceneDirector->UpdateScene( m_DeltaTime ); m_Renderer->Begin(); m_Renderer->Clear(); m_pSceneDirector->RenderScene(); m_Renderer->End(); if ( NNInputSystem::GetInstance()->GetKeyState( VK_ESCAPE ) == KEY_DOWN ) { PostQuitMessage(0); } } } return true; } bool NNApplication::_CreateWindow( wchar_t* title, int width, int height ) { WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.cbClsExtra = NULL; wcex.cbWndExtra = NULL; wcex.hInstance = m_hInstance; wcex.hIcon = NULL; wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wcex.lpszMenuName = NULL; wcex.lpszClassName = L"NNApplication"; wcex.hIconSm = NULL; wcex.hIcon = NULL; RegisterClassEx( &wcex ); DWORD style = WS_OVERLAPPEDWINDOW; m_Hwnd = CreateWindow( L"NNApplication", title, style, CW_USEDEFAULT, CW_USEDEFAULT, width, height, NULL, NULL, m_hInstance, NULL); ShowWindow( m_Hwnd, SW_SHOWNORMAL ); return true; } bool NNApplication::_CreateRenderer( RendererStatus renderStatus ) { switch( renderStatus ) { case D2D: m_Renderer = new NND2DRenderer(); break; default: return false; } return true; } LRESULT CALLBACK NNApplication::WndProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam ) { switch( message ) { case WM_DESTROY: NNApplication::GetInstance()->Release(); NNApplication::GetInstance()->m_DestroyWindow = true; PostQuitMessage(0); return 0; case WM_PAINT: PAINTSTRUCT ps; HDC hdc = BeginPaint( hWnd, &ps ); EndPaint( hWnd, &ps ); } return(DefWindowProc(hWnd,message,wParam,lParam)); }<|endoftext|>
<commit_before>#ifndef MJOLNIR_POTENTIAL_LOCAL_GAUSSIAN_POTENTIAL_HPP #define MJOLNIR_POTENTIAL_LOCAL_GAUSSIAN_POTENTIAL_HPP #include <mjolnir/math/constants.hpp> #include <cmath> namespace mjolnir { template<typename T> class System; // well-known gaussian-shape potential. // V(r) = k * exp(-(r-r0)^2 / 2sigma^2) // dV/dr = k * (-(r-r0) / sigma^2) * exp(-(r-r0)^2 / 2sigma^2) template<typename realT> class GaussianPotential { public: using real_type = realT; public: GaussianPotential(const real_type k, const real_type sigma, const real_type v0) noexcept : k_(k), sigma_(sigma), inv_sigma2_(-1./(2*sigma*sigma)), v0_(v0), cutoff_(v0_ + sigma_ * std::sqrt(2 * std::log(k_ / math::abs_tolerance<real_type>()))) {} ~GaussianPotential() = default; real_type potential(const real_type val) const noexcept { const real_type dval = val - this->v0_; return k_ * std::exp(inv_sigma2_ * dval * dval); } real_type derivative(const real_type val) const noexcept { const real_type dval = val - this->v0_; return 2*inv_sigma2_ * dval * k_ * std::exp(inv_sigma2_ * dval * dval); } template<typename T> void update(const System<T>&) const noexcept {return;} static const char* name() noexcept {return "Gaussian";} real_type k() const noexcept {return k_;} real_type sigma() const noexcept {return sigma_;} real_type v0() const noexcept {return v0_;} real_type cutoff() const noexcept {return cutoff_;} private: real_type k_, sigma_; real_type inv_sigma2_; real_type v0_; real_type cutoff_; }; #ifdef MJOLNIR_SEPARATE_BUILD extern template class GaussianPotential<double>; extern template class GaussianPotential<float>; #endif// MJOLNIR_SEPARATE_BUILD } // mjolnir #endif /* MJOLNIR_GAUSSIAN_POTENTIAL */ <commit_msg>fix too short cutoff problem in gaussian potentail when k is negative value<commit_after>#ifndef MJOLNIR_POTENTIAL_LOCAL_GAUSSIAN_POTENTIAL_HPP #define MJOLNIR_POTENTIAL_LOCAL_GAUSSIAN_POTENTIAL_HPP #include <mjolnir/math/constants.hpp> #include <cmath> namespace mjolnir { template<typename T> class System; // well-known gaussian-shape potential. // V(r) = k * exp(-(r-r0)^2 / 2sigma^2) // dV/dr = k * (-(r-r0) / sigma^2) * exp(-(r-r0)^2 / 2sigma^2) template<typename realT> class GaussianPotential { public: using real_type = realT; public: GaussianPotential(const real_type k, const real_type sigma, const real_type v0) noexcept : k_(k), sigma_(sigma), inv_sigma2_(-1./(2*sigma*sigma)), v0_(v0), cutoff_(v0_ + sigma_ * std::sqrt(2 * std::log(std::abs(k_) / math::abs_tolerance<real_type>()))) {} ~GaussianPotential() = default; real_type potential(const real_type val) const noexcept { const real_type dval = val - this->v0_; return k_ * std::exp(inv_sigma2_ * dval * dval); } real_type derivative(const real_type val) const noexcept { const real_type dval = val - this->v0_; return 2*inv_sigma2_ * dval * k_ * std::exp(inv_sigma2_ * dval * dval); } template<typename T> void update(const System<T>&) const noexcept {return;} static const char* name() noexcept {return "Gaussian";} real_type k() const noexcept {return k_;} real_type sigma() const noexcept {return sigma_;} real_type v0() const noexcept {return v0_;} real_type cutoff() const noexcept {return cutoff_;} private: real_type k_, sigma_; real_type inv_sigma2_; real_type v0_; real_type cutoff_; }; #ifdef MJOLNIR_SEPARATE_BUILD extern template class GaussianPotential<double>; extern template class GaussianPotential<float>; #endif// MJOLNIR_SEPARATE_BUILD } // mjolnir #endif /* MJOLNIR_GAUSSIAN_POTENTIAL */ <|endoftext|>
<commit_before>#include <iostream> #include <vector> #include <string> using namespace std; class data { //Ϣ public: string name; bool male; }; class person { // public: data info; person* father; person* mother; person* spouse; vector<person*> children; person(data info, person* father, person* mother); void marry(person* spouse); void divorce(); void givebirthto(); void givebirthto(data info); void showinfo(); void check(); }; person::person(data info, person* father = NULL, person* mother = NULL) { this->info = info; this->father = father; this->mother = mother; this->spouse = NULL; } void person::marry(person* spouse) { if (this->spouse != NULL) //ѽ鲻ܽ return; if (this->spouse->info.male == this->info.male) //ͬԲܽ return; this->spouse = spouse; spouse->spouse = this; } void person::divorce() { this->spouse = NULL; spouse->spouse = NULL; } void person::givebirthto() { if (this->father == NULL || this->mother == NULL) //޷һ˵õ return; data info; bool male; string name; cin >> name >> male; info.name = name; info.male = male; person* child = new person(info, this, this->spouse); children.push_back(child); } void person::givebirthto(data info) { person* child = new person(info, this, this->spouse); this->children.push_back(child); this->spouse->children.push_back(child); } void person::showinfo(); //ԼϢ void person::check(); //ͳƼܴ person* findperson(string name); //йظϢ person* findancestor(string name); //ij void output(); //ݹԼԱ int main() { /* data info; info.name = "god"; info.male = true; person god(info); data infowife; infowife.name = "godwife"; infowife.male = false; person godwife(infowife); data infoson; infoson.name = "godson"; infoson.male = true; god.marry(&godwife); god.givebirthto(infoson); */ return 0; }<commit_msg>genealogy-tree<commit_after><|endoftext|>
<commit_before>/*----------------------------------------------------------------------------- Copyright 2017 Hopsan Group 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. The full license is available in the file LICENSE. For details about the 'Hopsan Group' or information about Authors and Contributors see the HOPSANGROUP and AUTHORS files that are located in the Hopsan source code root directory. -----------------------------------------------------------------------------*/ //! //! @file CSVParser.cpp //! @author Peter Nordin <peter.nordin@liu.se> //! //! @brief Contains the Core Utility CSVParser class //! //$Id$ #define INDCSVP_REPLACEDECIMALCOMMA #include "indexingcsvparser/indexingcsvparser.h" #include "ComponentUtilities/CSVParser.h" #include <cstdlib> #ifdef _WIN32 #include "windows.h" #endif using namespace hopsan; CSVParserNG::CSVParserNG(const char separator_char, size_t linesToSkip) { mpCsvParser = new indcsvp::IndexingCSVParser(); mpCsvParser->setSeparatorChar(separator_char); mpCsvParser->setNumLinesToSkip(linesToSkip); } CSVParserNG::~CSVParserNG() { mpCsvParser->closeFile(); delete mpCsvParser; } bool CSVParserNG::openText(HString text) { #if defined(_WIN32) char tmpfilebuff[L_tmpnam]; errno_t rc = tmpnam_s(tmpfilebuff, L_tmpnam); if (rc != 0) { mErrorString = "Could not create temporary file name"; return false; } char tempdirbuff[MAX_PATH+1]; GetTempPathA(MAX_PATH+1, tempdirbuff); HString tmpfilename = HString(tempdirbuff)+tmpfilebuff; FILE* pTempfile = fopen(tmpfilename.c_str(), "w+b"); #else char tmpfilebuff[18] {"hopsan-csv-XXXXXX"}; int fd = mkstemp(tmpfilebuff); HString tmpfilename(tmpfilebuff); if (fd == -1) { mErrorString = "Could not create temporary file"; return false; } FILE* pTempfile = fdopen(fd, "r+b"); #endif if (pTempfile == 0) { mErrorString = HString("Could not open temporary file: ")+tmpfilename+" for writing"; return false; } fwrite(text.c_str(), sizeof(char), text.size(), pTempfile); rewind(pTempfile); return takeOwnershipOfFile(pTempfile); } bool CSVParserNG::openFile(const HString &rFilepath) { return mpCsvParser->openFile(rFilepath.c_str()); } bool CSVParserNG::takeOwnershipOfFile(FILE* pFile) { mpCsvParser->takeOwnershipOfFile(pFile); return true; } void CSVParserNG::closeFile() { mpCsvParser->closeFile(); } void CSVParserNG::setCommentChar(char commentChar) { mpCsvParser->setCommentChar(commentChar); } void CSVParserNG::setLinesToSkip(size_t linesToSkip) { mpCsvParser->setNumLinesToSkip(linesToSkip); } void CSVParserNG::setFieldSeparator(const char sep) { mpCsvParser->setSeparatorChar(sep); } char CSVParserNG::autoSetFieldSeparator(std::vector<char> &rAlternatives) { return mpCsvParser->autoSetSeparatorChar(rAlternatives); } void CSVParserNG::indexFile() { mpCsvParser->indexFile(); } size_t CSVParserNG::getNumDataRows() const { return mpCsvParser->numRows(); } size_t CSVParserNG::getNumDataCols(const size_t row) const { return mpCsvParser->numCols(row); } bool CSVParserNG::allRowsHaveSameNumCols() const { return mpCsvParser->allRowsHaveSameNumCols(); } void CSVParserNG::getMinMaxNumCols(size_t &rMin, size_t &rMax) const { return mpCsvParser->minMaxNumCols(rMin, rMax); } HString CSVParserNG::getErrorString() const { return mErrorString; } bool CSVParserNG::copyRow(const size_t rowIdx, std::vector<double> &rRow) { if (rowIdx < mpCsvParser->numRows()) { return mpCsvParser->getIndexedRowAs<double>(rowIdx, rRow); //! @todo convert decimal separator } else { mErrorString = "rowIdx out of range"; return false; } } bool CSVParserNG::copyRow(const size_t rowIdx, std::vector<long int> &rRow) { if (rowIdx < mpCsvParser->numRows()) { return mpCsvParser->getIndexedRowAs<long int>(rowIdx, rRow); } else { mErrorString = "rowIdx out of range"; return false; } } bool CSVParserNG::copyColumn(const size_t columnIdx, std::vector<double> &rColumn) { if (mpCsvParser->numRows() > 0) { return copyRangeFromColumn(columnIdx, 0, mpCsvParser->numRows(), rColumn); } else { mErrorString = "To few rows < 1"; return false; } } bool CSVParserNG::copyRangeFromColumn(const size_t columnIdx, const size_t startRow, const size_t numRows, std::vector<double> &rColumn) { rColumn.clear(); //! @todo assumes that all rows have same num cols if (columnIdx < mpCsvParser->numCols(startRow)) { return mpCsvParser->getIndexedColumnRowRangeAs<double>(columnIdx, startRow, numRows, rColumn); } else { mErrorString = "columnIdx out of range"; return false; } } bool CSVParserNG::copyEveryNthFromColumn(const size_t columnIdx, const size_t stepSize, std::vector<double> &rColumn) { return copyEveryNthFromColumnRange(columnIdx, 0, mpCsvParser->numRows(), stepSize, rColumn); } bool CSVParserNG::copyEveryNthFromColumnRange(const size_t columnIdx, const size_t startRow, const size_t numRows, const size_t stepSize, std::vector<double> &rColumn) { rColumn.clear(); std::vector<double> wholeColRange; bool rc = mpCsvParser->getIndexedColumnRowRangeAs<double>(columnIdx, startRow, numRows, wholeColRange); if (rc) { rColumn.reserve(numRows/stepSize); for (size_t r=0; r<wholeColRange.size(); r+=stepSize) { rColumn.push_back(wholeColRange[r]); } return true; } else { mErrorString = "Failed to get data"; return false; } } <commit_msg>Handle difference in MSVC and MinGW tmpnam_s<commit_after>/*----------------------------------------------------------------------------- Copyright 2017 Hopsan Group 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. The full license is available in the file LICENSE. For details about the 'Hopsan Group' or information about Authors and Contributors see the HOPSANGROUP and AUTHORS files that are located in the Hopsan source code root directory. -----------------------------------------------------------------------------*/ //! //! @file CSVParser.cpp //! @author Peter Nordin <peter.nordin@liu.se> //! //! @brief Contains the Core Utility CSVParser class //! //$Id$ #define INDCSVP_REPLACEDECIMALCOMMA #include "indexingcsvparser/indexingcsvparser.h" #include "ComponentUtilities/CSVParser.h" #include <cstdlib> #ifdef _WIN32 #include "windows.h" #endif using namespace hopsan; CSVParserNG::CSVParserNG(const char separator_char, size_t linesToSkip) { mpCsvParser = new indcsvp::IndexingCSVParser(); mpCsvParser->setSeparatorChar(separator_char); mpCsvParser->setNumLinesToSkip(linesToSkip); } CSVParserNG::~CSVParserNG() { mpCsvParser->closeFile(); delete mpCsvParser; } bool CSVParserNG::openText(HString text) { #if defined(_WIN32) char tmpfilebuff[L_tmpnam]; errno_t rc = tmpnam_s(tmpfilebuff, L_tmpnam); if (rc != 0) { mErrorString = "Could not create temporary file name"; return false; } HString tmpfilename; // tmpnam_s should give an absolute path C:\something, if second char is not : // then assume its a relative path (this happens with MinGW-w64 4.9.4) if (tmpfilebuff[1] != ':') { char tempdirbuff[MAX_PATH+1]; GetTempPathA(MAX_PATH+1, tempdirbuff); tmpfilename = HString(tempdirbuff)+tmpfilebuff; } else { tmpfilename = HString(tmpfilebuff); } FILE* pTempfile = fopen(tmpfilename.c_str(), "w+b"); #else char tmpfilebuff[18] {"hopsan-csv-XXXXXX"}; int fd = mkstemp(tmpfilebuff); HString tmpfilename(tmpfilebuff); if (fd == -1) { mErrorString = "Could not create temporary file"; return false; } FILE* pTempfile = fdopen(fd, "r+b"); #endif if (pTempfile == 0) { mErrorString = HString("Could not open temporary file: ")+tmpfilename+" for writing"; return false; } fwrite(text.c_str(), sizeof(char), text.size(), pTempfile); rewind(pTempfile); return takeOwnershipOfFile(pTempfile); } bool CSVParserNG::openFile(const HString &rFilepath) { return mpCsvParser->openFile(rFilepath.c_str()); } bool CSVParserNG::takeOwnershipOfFile(FILE* pFile) { mpCsvParser->takeOwnershipOfFile(pFile); return true; } void CSVParserNG::closeFile() { mpCsvParser->closeFile(); } void CSVParserNG::setCommentChar(char commentChar) { mpCsvParser->setCommentChar(commentChar); } void CSVParserNG::setLinesToSkip(size_t linesToSkip) { mpCsvParser->setNumLinesToSkip(linesToSkip); } void CSVParserNG::setFieldSeparator(const char sep) { mpCsvParser->setSeparatorChar(sep); } char CSVParserNG::autoSetFieldSeparator(std::vector<char> &rAlternatives) { return mpCsvParser->autoSetSeparatorChar(rAlternatives); } void CSVParserNG::indexFile() { mpCsvParser->indexFile(); } size_t CSVParserNG::getNumDataRows() const { return mpCsvParser->numRows(); } size_t CSVParserNG::getNumDataCols(const size_t row) const { return mpCsvParser->numCols(row); } bool CSVParserNG::allRowsHaveSameNumCols() const { return mpCsvParser->allRowsHaveSameNumCols(); } void CSVParserNG::getMinMaxNumCols(size_t &rMin, size_t &rMax) const { return mpCsvParser->minMaxNumCols(rMin, rMax); } HString CSVParserNG::getErrorString() const { return mErrorString; } bool CSVParserNG::copyRow(const size_t rowIdx, std::vector<double> &rRow) { if (rowIdx < mpCsvParser->numRows()) { return mpCsvParser->getIndexedRowAs<double>(rowIdx, rRow); //! @todo convert decimal separator } else { mErrorString = "rowIdx out of range"; return false; } } bool CSVParserNG::copyRow(const size_t rowIdx, std::vector<long int> &rRow) { if (rowIdx < mpCsvParser->numRows()) { return mpCsvParser->getIndexedRowAs<long int>(rowIdx, rRow); } else { mErrorString = "rowIdx out of range"; return false; } } bool CSVParserNG::copyColumn(const size_t columnIdx, std::vector<double> &rColumn) { if (mpCsvParser->numRows() > 0) { return copyRangeFromColumn(columnIdx, 0, mpCsvParser->numRows(), rColumn); } else { mErrorString = "To few rows < 1"; return false; } } bool CSVParserNG::copyRangeFromColumn(const size_t columnIdx, const size_t startRow, const size_t numRows, std::vector<double> &rColumn) { rColumn.clear(); //! @todo assumes that all rows have same num cols if (columnIdx < mpCsvParser->numCols(startRow)) { return mpCsvParser->getIndexedColumnRowRangeAs<double>(columnIdx, startRow, numRows, rColumn); } else { mErrorString = "columnIdx out of range"; return false; } } bool CSVParserNG::copyEveryNthFromColumn(const size_t columnIdx, const size_t stepSize, std::vector<double> &rColumn) { return copyEveryNthFromColumnRange(columnIdx, 0, mpCsvParser->numRows(), stepSize, rColumn); } bool CSVParserNG::copyEveryNthFromColumnRange(const size_t columnIdx, const size_t startRow, const size_t numRows, const size_t stepSize, std::vector<double> &rColumn) { rColumn.clear(); std::vector<double> wholeColRange; bool rc = mpCsvParser->getIndexedColumnRowRangeAs<double>(columnIdx, startRow, numRows, wholeColRange); if (rc) { rColumn.reserve(numRows/stepSize); for (size_t r=0; r<wholeColRange.size(); r+=stepSize) { rColumn.push_back(wholeColRange[r]); } return true; } else { mErrorString = "Failed to get data"; return false; } } <|endoftext|>
<commit_before>#ifndef SORTED__HPP__ #define SORTED__HPP__ #include "iterbase.hpp" #include <iterator> #include <algorithm> #include <vector> namespace iter { template <typename Container, typename CompareFunc> class Sorted; template <typename Container, typename CompareFunc> Sorted<Container, CompareFunc> sorted(Container &, CompareFunc); template <typename Container, typename CompareFunc> class Sorted { private: friend Sorted sorted<Container, CompareFunc>(Container &, CompareFunc); std::vector<iterator_type<Container>> sorted_iters; using sorted_iter_type = decltype(std::begin(sorted_iters)); Sorted() = delete; Sorted & operator=(const Sorted &) = delete; Sorted(Container & container, CompareFunc compare_func) { // Fill the sorted_iters vector with an iterator to each // element in the container for (auto iter = std::begin(container); iter != std::end(container); ++iter) { sorted_iters.push_back(iter); } // sort by comparing the elements that the iterators point to std::sort(std::begin(sorted_iters), std::end(sorted_iters), [&] (const iterator_type<Container> & it1, const iterator_type<Container> & it2) { return compare_func(*it1, *it2); }); } public: Sorted(const Sorted &) = default; // Iterates over a series of Iterators, automatically dereferencing // them when accessed with operator * class IteratorIterator : public sorted_iter_type { public: IteratorIterator(sorted_iter_type iter) : sorted_iter_type(iter) { } IteratorIterator(const IteratorIterator &) = default; // Dereference the current iterator before returning iterator_deref<Container> operator*() { return *sorted_iter_type::operator*(); } }; IteratorIterator begin() { IteratorIterator iteriter(std::begin(sorted_iters)); return iteriter; } IteratorIterator end() { IteratorIterator iteriter(std::end(sorted_iters)); return iteriter; } }; template <typename Container, typename CompareFunc> Sorted<Container, CompareFunc> sorted( Container & container, CompareFunc compare_func) { return Sorted<Container, CompareFunc>(container, compare_func); } template <typename Container> auto sorted(Container & container) -> decltype(sorted( container, std::less<decltype( *std::begin(std::declval<Container>()))>() )) { return sorted( container, std::less<decltype( *std::begin(std::declval<Container>()))>() ); } } #endif //#ifndef SORTED__HPP__ <commit_msg>uniform initialization updates<commit_after>#ifndef SORTED__HPP__ #define SORTED__HPP__ #include "iterbase.hpp" #include <iterator> #include <algorithm> #include <vector> namespace iter { template <typename Container, typename CompareFunc> class Sorted; template <typename Container, typename CompareFunc> Sorted<Container, CompareFunc> sorted(Container &, CompareFunc); template <typename Container, typename CompareFunc> class Sorted { private: friend Sorted sorted<Container, CompareFunc>(Container &, CompareFunc); std::vector<iterator_type<Container>> sorted_iters; using sorted_iter_type = decltype(std::begin(sorted_iters)); Sorted() = delete; Sorted & operator=(const Sorted &) = delete; Sorted(Container & container, CompareFunc compare_func) { // Fill the sorted_iters vector with an iterator to each // element in the container for (auto iter = std::begin(container); iter != std::end(container); ++iter) { sorted_iters.push_back(iter); } // sort by comparing the elements that the iterators point to std::sort(std::begin(sorted_iters), std::end(sorted_iters), [&] (const iterator_type<Container> & it1, const iterator_type<Container> & it2) { return compare_func(*it1, *it2); }); } public: Sorted(const Sorted &) = default; // Iterates over a series of Iterators, automatically dereferencing // them when accessed with operator * class IteratorIterator : public sorted_iter_type { public: IteratorIterator(sorted_iter_type iter) : sorted_iter_type{iter} { } IteratorIterator(const IteratorIterator &) = default; // Dereference the current iterator before returning iterator_deref<Container> operator*() { return *sorted_iter_type::operator*(); } }; IteratorIterator begin() { return {std::begin(sorted_iters)}; } IteratorIterator end() { return {std::end(sorted_iters)}; } }; template <typename Container, typename CompareFunc> Sorted<Container, CompareFunc> sorted( Container & container, CompareFunc compare_func) { return {container, compare_func}; } template <typename Container> auto sorted(Container & container) -> decltype(sorted( container, std::less<decltype( *std::begin(std::declval<Container>()))>() )) { return sorted( container, std::less<decltype( *std::begin(std::declval<Container>()))>() ); } } #endif //#ifndef SORTED__HPP__ <|endoftext|>
<commit_before>/// HEADER #include "render_histogram.h" /// PROJECT #include <csapex/model/connector_in.h> #include <csapex/model/connector_out.h> #include <csapex_vision/cv_mat_message.h> #include <csapex_core_plugins/vector_message.h> #include <csapex/utility/register_apex_plugin.h> #include <csapex_core_plugins/ros_message_conversion.h> #include <utils_cv/histogram.hpp> #include <utils_param/parameter_factory.h> using namespace csapex; using namespace csapex::connection_types; using namespace vision_plugins; CSAPEX_REGISTER_CLASS(vision_plugins::RenderHistogram, csapex::Node) RenderHistogram::RenderHistogram() : height_(480), width_(640) { Tag::createIfNotExists("Histogram"); addTag(Tag::get("Histogram")); addTag(Tag::get("Vision")); addTag(Tag::get("vision_plugins")); addParameter(param::ParameterFactory::declareRange("width", 200, 1000, width_, 10), boost::bind(&RenderHistogram::update, this)); addParameter(param::ParameterFactory::declareRange("height", 200, 1000, height_, 10), boost::bind(&RenderHistogram::update, this)); addParameter(param::ParameterFactory::declareRange("line width", 1, 10, 1, 1)); } void RenderHistogram::process() { #warning "FIX ENCODING" boost::shared_ptr<std::vector<CvMatMessage::Ptr> const> in = input_->getMessage<GenericVectorMessage, CvMatMessage::Ptr>(); CvMatMessage::Ptr out(new CvMatMessage(enc::bgr)); out->value = cv::Mat(height_, width_, CV_8UC3, cv::Scalar(0,0,0)); int line_width = param<int>("line width"); int color_count = 0; for(std::vector<CvMatMessage::Ptr>::const_iterator it = in->begin() ; it != in->end() ; ++it, ++color_count) { cv::Mat histogram = (*it)->value; int type = histogram.type() & 7; switch(type) { case CV_32F: utils_cv::render_curve<float>(histogram, utils_cv::COLOR_PALETTE.at(color_count % utils_cv::COLOR_PALETTE.size()), line_width, out->value); break; case CV_32S: utils_cv::render_curve<int>(histogram, utils_cv::COLOR_PALETTE.at(color_count % utils_cv::COLOR_PALETTE.size()), line_width, out->value); break; default: aerr << "Only 32bit float or 32bit integer histograms supported!" << std::endl; } } output_->publish(out); } void RenderHistogram::setup() { input_ = addInput<GenericVectorMessage, CvMatMessage::Ptr>("histograms"); output_ = addOutput<CvMatMessage>("image"); } void RenderHistogram::update() { width_ = param<int>("width"); height_ = param<int>("height"); } <commit_msg>minor<commit_after>/// HEADER #include "render_histogram.h" /// PROJECT #include <csapex/model/connector_in.h> #include <csapex/model/connector_out.h> #include <csapex_vision/cv_mat_message.h> #include <csapex_core_plugins/vector_message.h> #include <csapex/utility/register_apex_plugin.h> #include <csapex_core_plugins/ros_message_conversion.h> #include <utils_cv/histogram.hpp> #include <utils_param/parameter_factory.h> using namespace csapex; using namespace csapex::connection_types; using namespace vision_plugins; CSAPEX_REGISTER_CLASS(vision_plugins::RenderHistogram, csapex::Node) RenderHistogram::RenderHistogram() : height_(480), width_(640) { Tag::createIfNotExists("Histogram"); addTag(Tag::get("Histogram")); addTag(Tag::get("Vision")); addTag(Tag::get("vision_plugins")); addParameter(param::ParameterFactory::declareRange("width", 200, 1000, width_, 10), boost::bind(&RenderHistogram::update, this)); addParameter(param::ParameterFactory::declareRange("height", 200, 1000, height_, 10), boost::bind(&RenderHistogram::update, this)); addParameter(param::ParameterFactory::declareRange("line width", 1, 10, 1, 1)); } void RenderHistogram::process() { #warning "FIX ENCODING" boost::shared_ptr<std::vector<CvMatMessage::Ptr> const> in = input_->getMessage<GenericVectorMessage, CvMatMessage::Ptr>(); CvMatMessage::Ptr out(new CvMatMessage(enc::bgr)); out->value = cv::Mat(height_, width_, CV_8UC3, cv::Scalar(0,0,0)); int line_width = param<int>("line width"); int color_count = 0; for(std::vector<CvMatMessage::Ptr>::const_iterator it = in->begin() ; it != in->end() ; ++it, ++color_count) { cv::Mat histogram = (*it)->value; int type = histogram.type() & 7; switch(type) { case CV_32F: utils_cv::render_curve<float>(histogram, utils_cv::COLOR_PALETTE.at(color_count % utils_cv::COLOR_PALETTE.size()), line_width, out->value); break; case CV_32S: utils_cv::render_curve<int>(histogram, utils_cv::COLOR_PALETTE.at(color_count % utils_cv::COLOR_PALETTE.size()), line_width, out->value); break; default: aerr << "Only 32bit float or 32bit integer histograms supported!" << std::endl; } } output_->publish(out); } void RenderHistogram::setup() { input_ = addInput<GenericVectorMessage, CvMatMessage::Ptr>("histograms"); output_ = addOutput<CvMatMessage>("image"); } void RenderHistogram::update() { width_ = param<int>("width"); height_ = param<int>("height"); } <|endoftext|>
<commit_before>#pragma once #include <Zmey/Scripting/Binding.h> #include <Zmey/Modules.h> #include <Zmey/Memory/MemoryManagement.h> #include "ChakraScriptEngine.h" namespace Zmey { namespace Chakra { namespace Binding { uint32_t GCurrentPendingClassProjectionIndex = 0u; std::array<AutoNativeClassProjecter*, 256> GPendingClassProjections; AutoNativeClassProjecter::AutoNativeClassProjecter(const wchar_t* className, JsNativeFunction constructor, JsValueRef& prototype, uint16_t MemberCount, const wchar_t** memberNames, const JsNativeFunction* memberFuncs) : ClassName(className) , NameHash(0ull) , Constructor(constructor) , Prototype(prototype) , ActualMemberCount(MemberCount) { std::memcpy(MemberNames, memberNames, MemberCount * sizeof(const wchar_t*)); std::memcpy(MemberFuncs, memberFuncs, MemberCount * sizeof(JsNativeFunction)); RegisterForInitialization(); } AutoNativeClassProjecter::AutoNativeClassProjecter(const wchar_t* className, JsNativeFunction constructor, JsValueRef& prototype) : ClassName(className) , NameHash(0ull) , Constructor(constructor) , Prototype(prototype) , ActualMemberCount(0u) { RegisterForInitialization(); } void AutoNativeClassProjecter::RegisterForInitialization() { JsContextRef activeContext; JsGetCurrentContext(&activeContext); if (!activeContext) { // We are still not initialized. Store this data for the initialize call GPendingClassProjections[GCurrentPendingClassProjectionIndex++] = this; return; } else { Project(); } } void AutoNativeClassProjecter::Project() { tmp::string utf8Name = Zmey::ConvertWideStringToUtf8(tmp::wstring(ClassName)); NameHash = Zmey::Hash(Zmey::HashHelpers::CaseInsensitiveStringWrapper(utf8Name.c_str())); const tmp::vector<const wchar_t *> memberNames(MemberNames, MemberNames + ActualMemberCount); const tmp::vector<JsNativeFunction> memberFuncs(MemberFuncs, MemberFuncs + ActualMemberCount); ProjectNativeClass(ClassName, Constructor, Prototype, memberNames, memberFuncs); } JsValueRef AutoNativeClassProjecter::GetPrototypeOf(const Zmey::Hash classNameHash) { for (uint32_t i = 0u; i < GCurrentPendingClassProjectionIndex; ++i) { auto projectionData = GPendingClassProjections[i]; if (projectionData->NameHash == classNameHash) { return projectionData->Prototype; } } return nullptr; } void CheckChakraCall(JsErrorCode error, const char* functionCall, const char* file, int line) { if (error != JsNoError) { FORMAT_LOG(Error, Scripting, "Chakra call %s failed at %s:%d with %d", functionCall, file, line, error); } } #define CHECKCHAKRA(Call) \ CheckChakraCall(Call, #Call, __FILE__, __LINE__) void Initialize() { JsValueRef globalObject; CHECKCHAKRA(JsGetGlobalObject(&globalObject)); JsValueRef console; CHECKCHAKRA(JsCreateObject(&console)); SetProperty(globalObject, L"console", console); SetCallback(console, L"debug", JSConsoleDebug, nullptr); SetCallback(console, L"log", JSConsoleLog, nullptr); SetCallback(console, L"warn", JSConsoleWarn, nullptr); SetCallback(console, L"error", JSConsoleError, nullptr); SetCallback(globalObject, L"setTimeout", JSSetTimeout, nullptr); SetCallback(globalObject, L"setInterval", JSSetInterval, nullptr); for (uint32_t i = 0u; i < GCurrentPendingClassProjectionIndex; ++i) { auto projectionData = GPendingClassProjections[i]; projectionData->Project(); } } // The following funcs (SetCallback / SetProp / ProjectClass) were pretty much copied from Chakra's open gl sample void SetCallback(JsValueRef object, const wchar_t *propertyName, JsNativeFunction callback, void *callbackState) { JsPropertyIdRef propertyId; JsGetPropertyIdFromName(propertyName, &propertyId); JsValueRef function; JsCreateFunction(callback, callbackState, &function); JsSetProperty(object, propertyId, function, true); } void SetProperty(JsValueRef object, const wchar_t *propertyName, JsValueRef property) { JsPropertyIdRef propertyId; CHECKCHAKRA(JsGetPropertyIdFromName(propertyName, &propertyId)); CHECKCHAKRA(JsSetProperty(object, propertyId, property, true)); } void DefineProperty(JsValueRef object, const wchar_t* propertyName, JsNativeFunction getter) { JsPropertyIdRef propertyId; CHECKCHAKRA(JsGetPropertyIdFromName(propertyName, &propertyId)); JsValueRef propertyDescriptor; CHECKCHAKRA(JsCreateObject(&propertyDescriptor)); JsValueRef getterFunc; CHECKCHAKRA(JsCreateFunction(getter, nullptr, &getterFunc)); SetProperty(propertyDescriptor, L"get", getterFunc); bool ignoredResult; CHECKCHAKRA(JsDefineProperty(object, propertyId, propertyDescriptor, &ignoredResult)); } void DefineProperty(JsValueRef object, const wchar_t* propertyName, JsNativeFunction getter, JsNativeFunction setter) { JsPropertyIdRef propertyId; CHECKCHAKRA(JsGetPropertyIdFromName(propertyName, &propertyId)); JsValueRef propertyDescriptor; CHECKCHAKRA(JsCreateObject(&propertyDescriptor)); JsValueRef getterFunc; CHECKCHAKRA(JsCreateFunction(getter, nullptr, &getterFunc)); SetProperty(propertyDescriptor, L"get", getterFunc); JsValueRef setterFunc; CHECKCHAKRA(JsCreateFunction(setter, nullptr, &setterFunc)); SetProperty(propertyDescriptor, L"set", setterFunc); bool ignoredResult; CHECKCHAKRA(JsDefineProperty(object, propertyId, propertyDescriptor, &ignoredResult)); } void ProjectNativeClass(const wchar_t *className, JsNativeFunction constructor, JsValueRef &prototype, const tmp::vector<const wchar_t *>& memberNames, const tmp::vector<JsNativeFunction>& memberFuncs) { // create class's prototype and project its member functions JsCreateObject(&prototype); assert(memberNames.size() == memberNames.size()); for (int i = 0; i < memberNames.size(); ++i) { SetCallback(prototype, memberNames[i], memberFuncs[i], nullptr); } if (constructor) { JsValueRef globalObject; JsGetGlobalObject(&globalObject); JsValueRef jsConstructor; JsCreateFunction(constructor, nullptr, &jsConstructor); SetProperty(globalObject, className, jsConstructor); SetProperty(jsConstructor, L"prototype", prototype); } } void ProjectGlobal(const wchar_t* globalName, void* objectToProject, Zmey::Hash classNameHash) { JsValueRef globalObject; CHECKCHAKRA(JsGetGlobalObject(&globalObject)); JsValueRef object; CHECKCHAKRA(JsCreateExternalObject(objectToProject, nullptr, &object)); SetProperty(globalObject, globalName, object); JsValueRef prototype = AutoNativeClassProjecter::GetPrototypeOf(classNameHash); CHECKCHAKRA(JsSetPrototype(object, prototype)); } uint32_t GCurrentAnyTypeIndex = 0u; std::array<stl::unique_ptr<AnyTypeData>, 256> GAnyTypeList; void RegisterPrototypesForAnyTypeSet(AnyTypeData data) { GAnyTypeList[GCurrentAnyTypeIndex] = stl::make_unique<AnyTypeData>(data); JsValueRef globalObject; CHECKCHAKRA(JsGetGlobalObject(&globalObject)); JsValueRef enumObject; CHECKCHAKRA(JsCreateObject(&enumObject)); auto scope = Zmey::TempAllocator::GetTlsAllocator().ScopeNow(); for (int i = 0; i < data.PrototypeNames.size(); ++i) { JsValueRef indexValue; CHECKCHAKRA(JsIntToNumber(i, &indexValue)); tmp::wstring name = Zmey::ConvertUtf8ToWideString(tmp::string(data.PrototypeNames[i])); SetProperty(enumObject, name.c_str(), indexValue); } tmp::wstring anySetName = Zmey::ConvertUtf8ToWideString(tmp::string(data.Name)); SetProperty(globalObject, anySetName.c_str(), enumObject); } JsValueRef GetProtototypeOfAnyTypeSet(Zmey::Hash anyTypeName, int index) { auto it = std::find_if(GAnyTypeList.begin(), GAnyTypeList.begin() + GCurrentAnyTypeIndex, [anyTypeName](const stl::unique_ptr<AnyTypeData>& data) { return data->NameHash == anyTypeName; }); ASSERT_FATAL(it != GAnyTypeList.end()); return (*it)->Prototypes[index]; } JsValueRef CALLBACK JSConsoleDebug(JsValueRef callee, bool isConstructCall, JsValueRef* arguments, unsigned short argumentCount, void *callbackState) { return JSConsoleMessage(Zmey::LogSeverity::Debug, callee, isConstructCall, arguments, argumentCount, callbackState); } JsValueRef CALLBACK JSConsoleLog(JsValueRef callee, bool isConstructCall, JsValueRef* arguments, unsigned short argumentCount, void *callbackState) { return JSConsoleMessage(Zmey::LogSeverity::Info, callee, isConstructCall, arguments, argumentCount, callbackState); } JsValueRef CALLBACK JSConsoleWarn(JsValueRef callee, bool isConstructCall, JsValueRef* arguments, unsigned short argumentCount, void *callbackState) { return JSConsoleMessage(Zmey::LogSeverity::Warning, callee, isConstructCall, arguments, argumentCount, callbackState); } JsValueRef CALLBACK JSConsoleError(JsValueRef callee, bool isConstructCall, JsValueRef* arguments, unsigned short argumentCount, void *callbackState) { return JSConsoleMessage(Zmey::LogSeverity::Error, callee, isConstructCall, arguments, argumentCount, callbackState); } JsValueRef JSConsoleMessage(Zmey::LogSeverity severity, JsValueRef callee, bool isConstructCall, JsValueRef* arguments, unsigned short argumentCount, void *callbackState) { auto tempScope = TempAllocator::GetTlsAllocator().ScopeNow(); tmp::wstring message; for (unsigned int index = 1; index < argumentCount; index++) { if (index > 1) { message += ' '; } JsValueRef stringValue; JsConvertValueToString(arguments[index], &stringValue); const wchar_t* string; size_t length; JsStringToPointer(stringValue, &string, &length); message.append(string); } tmp::string mbMessage = Zmey::ConvertWideStringToUtf8(message); Zmey::GLogHandler->WriteLog(severity, "Script", mbMessage.c_str()); return JS_INVALID_REFERENCE; } JsValueRef CALLBACK Binding::JSSetTimeout(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState) { assert(!isConstructCall && argumentCount == 3); JsValueRef func = arguments[1]; int delay = 0; JsNumberToInt(arguments[2], &delay); auto host = static_cast<ChakraScriptEngine*>(Zmey::Modules::ScriptEngine); host->m_ExecutionTasks.push_back(stl::make_unique<ExecutionTask>(func, delay, arguments[0], JS_INVALID_REFERENCE)); return JS_INVALID_REFERENCE; } // JsNativeFunction for setInterval(func, delay) JsValueRef CALLBACK Binding::JSSetInterval(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState) { assert(!isConstructCall && argumentCount == 3); JsValueRef func = arguments[1]; int delay = 0; JsNumberToInt(arguments[2], &delay); auto host = static_cast<ChakraScriptEngine*>(Zmey::Modules::ScriptEngine); host->m_ExecutionTasks.push_back(stl::make_unique<ExecutionTask>(func, delay, arguments[0], JS_INVALID_REFERENCE, true)); return JS_INVALID_REFERENCE; } } } }<commit_msg>Added a bunch of checks to chakra calls.<commit_after>#pragma once #include <Zmey/Scripting/Binding.h> #include <Zmey/Modules.h> #include <Zmey/Memory/MemoryManagement.h> #include "ChakraScriptEngine.h" namespace Zmey { namespace Chakra { namespace Binding { uint32_t GCurrentPendingClassProjectionIndex = 0u; std::array<AutoNativeClassProjecter*, 256> GPendingClassProjections; AutoNativeClassProjecter::AutoNativeClassProjecter(const wchar_t* className, JsNativeFunction constructor, JsValueRef& prototype, uint16_t MemberCount, const wchar_t** memberNames, const JsNativeFunction* memberFuncs) : ClassName(className) , NameHash(0ull) , Constructor(constructor) , Prototype(prototype) , ActualMemberCount(MemberCount) { std::memcpy(MemberNames, memberNames, MemberCount * sizeof(const wchar_t*)); std::memcpy(MemberFuncs, memberFuncs, MemberCount * sizeof(JsNativeFunction)); RegisterForInitialization(); } AutoNativeClassProjecter::AutoNativeClassProjecter(const wchar_t* className, JsNativeFunction constructor, JsValueRef& prototype) : ClassName(className) , NameHash(0ull) , Constructor(constructor) , Prototype(prototype) , ActualMemberCount(0u) { RegisterForInitialization(); } void AutoNativeClassProjecter::RegisterForInitialization() { JsContextRef activeContext; JsGetCurrentContext(&activeContext); if (!activeContext) { // We are still not initialized. Store this data for the initialize call GPendingClassProjections[GCurrentPendingClassProjectionIndex++] = this; return; } else { Project(); } } void AutoNativeClassProjecter::Project() { tmp::string utf8Name = Zmey::ConvertWideStringToUtf8(tmp::wstring(ClassName)); NameHash = Zmey::Hash(Zmey::HashHelpers::CaseInsensitiveStringWrapper(utf8Name.c_str())); const tmp::vector<const wchar_t *> memberNames(MemberNames, MemberNames + ActualMemberCount); const tmp::vector<JsNativeFunction> memberFuncs(MemberFuncs, MemberFuncs + ActualMemberCount); ProjectNativeClass(ClassName, Constructor, Prototype, memberNames, memberFuncs); } JsValueRef AutoNativeClassProjecter::GetPrototypeOf(const Zmey::Hash classNameHash) { for (uint32_t i = 0u; i < GCurrentPendingClassProjectionIndex; ++i) { auto projectionData = GPendingClassProjections[i]; if (projectionData->NameHash == classNameHash) { return projectionData->Prototype; } } return nullptr; } void CheckChakraCall(JsErrorCode error, const char* functionCall, const char* file, int line) { if (error != JsNoError) { FORMAT_LOG(Error, Scripting, "Chakra call %s failed at %s:%d with %d", functionCall, file, line, error); } } #define CHECKCHAKRA(Call) \ CheckChakraCall(Call, #Call, __FILE__, __LINE__) void Initialize() { JsValueRef globalObject; CHECKCHAKRA(JsGetGlobalObject(&globalObject)); JsValueRef console; CHECKCHAKRA(JsCreateObject(&console)); SetProperty(globalObject, L"console", console); SetCallback(console, L"debug", JSConsoleDebug, nullptr); SetCallback(console, L"log", JSConsoleLog, nullptr); SetCallback(console, L"warn", JSConsoleWarn, nullptr); SetCallback(console, L"error", JSConsoleError, nullptr); SetCallback(globalObject, L"setTimeout", JSSetTimeout, nullptr); SetCallback(globalObject, L"setInterval", JSSetInterval, nullptr); for (uint32_t i = 0u; i < GCurrentPendingClassProjectionIndex; ++i) { auto projectionData = GPendingClassProjections[i]; projectionData->Project(); } } // The following funcs (SetCallback / SetProp / ProjectClass) were pretty much copied from Chakra's open gl sample void SetCallback(JsValueRef object, const wchar_t *propertyName, JsNativeFunction callback, void *callbackState) { JsPropertyIdRef propertyId; CHECKCHAKRA(JsGetPropertyIdFromName(propertyName, &propertyId)); JsValueRef function; CHECKCHAKRA(JsCreateFunction(callback, callbackState, &function)); CHECKCHAKRA(JsSetProperty(object, propertyId, function, true)); } void SetProperty(JsValueRef object, const wchar_t *propertyName, JsValueRef property) { JsPropertyIdRef propertyId; CHECKCHAKRA(JsGetPropertyIdFromName(propertyName, &propertyId)); CHECKCHAKRA(JsSetProperty(object, propertyId, property, true)); } void DefineProperty(JsValueRef object, const wchar_t* propertyName, JsNativeFunction getter) { JsPropertyIdRef propertyId; CHECKCHAKRA(JsGetPropertyIdFromName(propertyName, &propertyId)); JsValueRef propertyDescriptor; CHECKCHAKRA(JsCreateObject(&propertyDescriptor)); JsValueRef getterFunc; CHECKCHAKRA(JsCreateFunction(getter, nullptr, &getterFunc)); SetProperty(propertyDescriptor, L"get", getterFunc); bool ignoredResult; CHECKCHAKRA(JsDefineProperty(object, propertyId, propertyDescriptor, &ignoredResult)); } void DefineProperty(JsValueRef object, const wchar_t* propertyName, JsNativeFunction getter, JsNativeFunction setter) { JsPropertyIdRef propertyId; CHECKCHAKRA(JsGetPropertyIdFromName(propertyName, &propertyId)); JsValueRef propertyDescriptor; CHECKCHAKRA(JsCreateObject(&propertyDescriptor)); JsValueRef getterFunc; CHECKCHAKRA(JsCreateFunction(getter, nullptr, &getterFunc)); SetProperty(propertyDescriptor, L"get", getterFunc); JsValueRef setterFunc; CHECKCHAKRA(JsCreateFunction(setter, nullptr, &setterFunc)); SetProperty(propertyDescriptor, L"set", setterFunc); bool ignoredResult; CHECKCHAKRA(JsDefineProperty(object, propertyId, propertyDescriptor, &ignoredResult)); } void ProjectNativeClass(const wchar_t *className, JsNativeFunction constructor, JsValueRef &prototype, const tmp::vector<const wchar_t *>& memberNames, const tmp::vector<JsNativeFunction>& memberFuncs) { // create class's prototype and project its member functions JsCreateObject(&prototype); assert(memberNames.size() == memberNames.size()); for (int i = 0; i < memberNames.size(); ++i) { SetCallback(prototype, memberNames[i], memberFuncs[i], nullptr); } if (constructor) { JsValueRef globalObject; CHECKCHAKRA(JsGetGlobalObject(&globalObject)); JsValueRef jsConstructor; CHECKCHAKRA(JsCreateFunction(constructor, nullptr, &jsConstructor)); SetProperty(globalObject, className, jsConstructor); SetProperty(jsConstructor, L"prototype", prototype); } } void ProjectGlobal(const wchar_t* globalName, void* objectToProject, Zmey::Hash classNameHash) { JsValueRef globalObject; CHECKCHAKRA(JsGetGlobalObject(&globalObject)); JsValueRef object; CHECKCHAKRA(JsCreateExternalObject(objectToProject, nullptr, &object)); SetProperty(globalObject, globalName, object); JsValueRef prototype = AutoNativeClassProjecter::GetPrototypeOf(classNameHash); CHECKCHAKRA(JsSetPrototype(object, prototype)); } uint32_t GCurrentAnyTypeIndex = 0u; std::array<stl::unique_ptr<AnyTypeData>, 256> GAnyTypeList; void RegisterPrototypesForAnyTypeSet(AnyTypeData data) { GAnyTypeList[GCurrentAnyTypeIndex] = stl::make_unique<AnyTypeData>(data); JsValueRef globalObject; CHECKCHAKRA(JsGetGlobalObject(&globalObject)); JsValueRef enumObject; CHECKCHAKRA(JsCreateObject(&enumObject)); auto scope = Zmey::TempAllocator::GetTlsAllocator().ScopeNow(); for (int i = 0; i < data.PrototypeNames.size(); ++i) { JsValueRef indexValue; CHECKCHAKRA(JsIntToNumber(i, &indexValue)); tmp::wstring name = Zmey::ConvertUtf8ToWideString(tmp::string(data.PrototypeNames[i])); SetProperty(enumObject, name.c_str(), indexValue); } tmp::wstring anySetName = Zmey::ConvertUtf8ToWideString(tmp::string(data.Name)); SetProperty(globalObject, anySetName.c_str(), enumObject); } JsValueRef GetProtototypeOfAnyTypeSet(Zmey::Hash anyTypeName, int index) { auto it = std::find_if(GAnyTypeList.begin(), GAnyTypeList.begin() + GCurrentAnyTypeIndex, [anyTypeName](const stl::unique_ptr<AnyTypeData>& data) { return data->NameHash == anyTypeName; }); ASSERT_FATAL(it != GAnyTypeList.end()); return (*it)->Prototypes[index]; } JsValueRef CALLBACK JSConsoleDebug(JsValueRef callee, bool isConstructCall, JsValueRef* arguments, unsigned short argumentCount, void *callbackState) { return JSConsoleMessage(Zmey::LogSeverity::Debug, callee, isConstructCall, arguments, argumentCount, callbackState); } JsValueRef CALLBACK JSConsoleLog(JsValueRef callee, bool isConstructCall, JsValueRef* arguments, unsigned short argumentCount, void *callbackState) { return JSConsoleMessage(Zmey::LogSeverity::Info, callee, isConstructCall, arguments, argumentCount, callbackState); } JsValueRef CALLBACK JSConsoleWarn(JsValueRef callee, bool isConstructCall, JsValueRef* arguments, unsigned short argumentCount, void *callbackState) { return JSConsoleMessage(Zmey::LogSeverity::Warning, callee, isConstructCall, arguments, argumentCount, callbackState); } JsValueRef CALLBACK JSConsoleError(JsValueRef callee, bool isConstructCall, JsValueRef* arguments, unsigned short argumentCount, void *callbackState) { return JSConsoleMessage(Zmey::LogSeverity::Error, callee, isConstructCall, arguments, argumentCount, callbackState); } JsValueRef JSConsoleMessage(Zmey::LogSeverity severity, JsValueRef callee, bool isConstructCall, JsValueRef* arguments, unsigned short argumentCount, void *callbackState) { auto tempScope = TempAllocator::GetTlsAllocator().ScopeNow(); tmp::wstring message; for (unsigned int index = 1; index < argumentCount; index++) { if (index > 1) { message += ' '; } JsValueRef stringValue; CHECKCHAKRA(JsConvertValueToString(arguments[index], &stringValue)); const wchar_t* string; size_t length; CHECKCHAKRA(JsStringToPointer(stringValue, &string, &length)); message.append(string); } tmp::string mbMessage = Zmey::ConvertWideStringToUtf8(message); Zmey::GLogHandler->WriteLog(severity, "Script", mbMessage.c_str()); return JS_INVALID_REFERENCE; } JsValueRef CALLBACK Binding::JSSetTimeout(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState) { assert(!isConstructCall && argumentCount == 3); JsValueRef func = arguments[1]; int delay = 0; CHECKCHAKRA(JsNumberToInt(arguments[2], &delay)); auto host = static_cast<ChakraScriptEngine*>(Zmey::Modules::ScriptEngine); host->m_ExecutionTasks.push_back(stl::make_unique<ExecutionTask>(func, delay, arguments[0], JS_INVALID_REFERENCE)); return JS_INVALID_REFERENCE; } // JsNativeFunction for setInterval(func, delay) JsValueRef CALLBACK Binding::JSSetInterval(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState) { assert(!isConstructCall && argumentCount == 3); JsValueRef func = arguments[1]; int delay = 0; CHECKCHAKRA(JsNumberToInt(arguments[2], &delay)); auto host = static_cast<ChakraScriptEngine*>(Zmey::Modules::ScriptEngine); host->m_ExecutionTasks.push_back(stl::make_unique<ExecutionTask>(func, delay, arguments[0], JS_INVALID_REFERENCE, true)); return JS_INVALID_REFERENCE; } } } }<|endoftext|>
<commit_before>#include <gtest/gtest.h> #include "utils.hpp" using aoc2019::run_intcode; auto run_program(std::vector<int> program, std::deque<int> input) { return run_intcode(program, std::move(input)); } TEST(Intcode, TestPositionEquality) { const std::vector<int> program = {3, 9, 8, 9, 10, 9, 4, 9, 99, -1, 8}; ASSERT_EQ(1, run_program(program, {8}).front()); ASSERT_EQ(0, run_program(program, {9}).front()); } TEST(Intcode, TestPositionLess) { const std::vector<int> program = {3, 9, 7, 9, 10, 9, 4, 9, 99, -1, 8}; ASSERT_EQ(1, run_program(program, {7}).front()); ASSERT_EQ(0, run_program(program, {9}).front()); } TEST(Intcode, TestImmediateEquality) { const std::vector<int> program = {3, 3, 1108, -1, 8, 3, 4, 3, 99}; ASSERT_EQ(1, run_program(program, {8}).front()); ASSERT_EQ(0, run_program(program, {9}).front()); } TEST(Intcode, TestImmediateLess) { const std::vector<int> program = {3, 3, 1107, -1, 8, 3, 4, 3, 99}; ASSERT_EQ(1, run_program(program, {7}).front()); ASSERT_EQ(0, run_program(program, {9}).front()); } TEST(Intcode, TestComplicatedConditional) { const std::vector<int> program = {3, 21, 1008, 21, 8, 20, 1005, 20, 22, 107, 8, 21, 20, 1006, 20, 31, 1106, 0, 36, 98, 0, 0, 1002, 21, 125, 20, 4, 20, 1105, 1, 46, 104, 999, 1105, 1, 46, 1101, 1000, 1, 20, 4, 20, 1105, 1, 46, 98, 99}; auto pcopy = program; auto output = run_intcode(pcopy, {7}); ASSERT_EQ(999, output.front()); pcopy = program; output = run_intcode(pcopy, {9}); ASSERT_EQ(1001, output.front()); pcopy = program; output = run_intcode(pcopy, {8}); ASSERT_EQ(1000, output.front()); } <commit_msg>Remove more old intcode references.<commit_after>#include <gtest/gtest.h> #include "utils.hpp" using aoc2019::run_intcode; using aoc2019::IntCodeComputer; auto run_program(std::vector<int64_t> program, std::deque<int64_t> input) { std::deque<std::int64_t> output; IntCodeComputer computer(std::move(program), std::move(input)); computer.connectOutput(output); computer.run(); return output; } TEST(Intcode, TestPositionEquality) { const std::vector<int64_t> program = {3, 9, 8, 9, 10, 9, 4, 9, 99, -1, 8}; ASSERT_EQ(1, run_program(program, {8}).front()); ASSERT_EQ(0, run_program(program, {9}).front()); } TEST(Intcode, TestPositionLess) { const std::vector<int64_t> program = {3, 9, 7, 9, 10, 9, 4, 9, 99, -1, 8}; ASSERT_EQ(1, run_program(program, {7}).front()); ASSERT_EQ(0, run_program(program, {9}).front()); } TEST(Intcode, TestImmediateEquality) { const std::vector<int64_t> program = {3, 3, 1108, -1, 8, 3, 4, 3, 99}; ASSERT_EQ(1, run_program(program, {8}).front()); ASSERT_EQ(0, run_program(program, {9}).front()); } TEST(Intcode, TestImmediateLess) { const std::vector<int64_t> program = {3, 3, 1107, -1, 8, 3, 4, 3, 99}; ASSERT_EQ(1, run_program(program, {7}).front()); ASSERT_EQ(0, run_program(program, {9}).front()); } TEST(Intcode, TestComplicatedConditional) { const std::vector<int> program = {3, 21, 1008, 21, 8, 20, 1005, 20, 22, 107, 8, 21, 20, 1006, 20, 31, 1106, 0, 36, 98, 0, 0, 1002, 21, 125, 20, 4, 20, 1105, 1, 46, 104, 999, 1105, 1, 46, 1101, 1000, 1, 20, 4, 20, 1105, 1, 46, 98, 99}; auto pcopy = program; auto output = run_intcode(pcopy, {7}); ASSERT_EQ(999, output.front()); pcopy = program; output = run_intcode(pcopy, {9}); ASSERT_EQ(1001, output.front()); pcopy = program; output = run_intcode(pcopy, {8}); ASSERT_EQ(1000, output.front()); } <|endoftext|>
<commit_before>#ifndef RBX_VM_H #define RBX_VM_H #include "missing/time.h" #include "vm_jit.hpp" #include "globals.hpp" #include "memory/object_mark.hpp" #include "memory/managed.hpp" #include "vm_thread_state.hpp" #include "thread_nexus.hpp" #include "metrics.hpp" #include "util/thread.hpp" #include "memory/variable_buffer.hpp" #include "memory/root_buffer.hpp" #include "memory/slab.hpp" #include "shared_state.hpp" #include "unwind_info.hpp" #include "fiber_stack.hpp" #include <vector> #include <setjmp.h> namespace llvm { class Module; } namespace rbxti { class Env; } namespace rubinius { class Exception; class LLVMState; namespace event { class Loop; } namespace memory { class GarbageCollector; class WriteBarrier; } class Channel; class GlobalCache; class Primitives; class Memory; class TypeInfo; class String; class Symbol; class ConfigParser; class TypeError; class Assertion; struct CallFrame; class CallSiteInformation; class Object; class Configuration; class VMManager; class LookupTable; class SymbolTable; class SharedState; class Fiber; class Park; class NativeMethodEnvironment; class VariableScope; enum MethodMissingReason { eNone, ePrivate, eProtected, eSuper, eVCall, eNormal }; enum ConstantMissingReason { vFound, vPrivate, vNonExistent }; /** * Represents an execution context for running Ruby code. * * Each Ruby thread is backed by an instance of this class, as well as an * instance of the Thread class. Thread manages the (Ruby visible) thread- * related state, while this class manages the execution machinery for * running Ruby code. */ class VM : public memory::ManagedThread { friend class State; friend class VMJIT; private: UnwindInfoSet unwinds_; CallFrame* call_frame_; ThreadNexus* thread_nexus_; CallSiteInformation* saved_call_site_information_; FiberStacks fiber_stacks_; Park* park_; rbxti::Env* tooling_env_; void* stack_start_; size_t stack_size_; void* current_stack_start_; size_t current_stack_size_; utilities::thread::SpinLock interrupt_lock_; VMJIT vm_jit_; MethodMissingReason method_missing_reason_; ConstantMissingReason constant_missing_reason_; bool zombie_; bool tooling_; bool allocation_tracking_; bool main_thread_; ThreadNexus::Phase thread_phase_; public: /* Data members */ SharedState& shared; memory::TypedRoot<Channel*> waiting_channel_; memory::TypedRoot<Exception*> interrupted_exception_; /// The Thread object for this VM state memory::TypedRoot<Thread*> thread; /// The current fiber running on this thread memory::TypedRoot<Fiber*> current_fiber; /// Root fiber, if any (lazily initialized) memory::TypedRoot<Fiber*> root_fiber; /// Object that waits for inflation memory::TypedRoot<Object*> waiting_object_; NativeMethodEnvironment* native_method_environment; void (*custom_wakeup_)(void*); void* custom_wakeup_data_; VMThreadState thread_state_; public: /* Inline methods */ UnwindInfoSet& unwinds() { return unwinds_; } uint32_t thread_id() const { return id_; } ThreadNexus::Phase thread_phase() { return thread_phase_; } ThreadNexus* thread_nexus() { return thread_nexus_; } void set_thread_phase(ThreadNexus::Phase thread_phase) { thread_phase_ = thread_phase; } void restore_thread_phase(ThreadNexus::Phase thread_phase) { switch(thread_phase) { case ThreadNexus::cManaged: become_managed(); break; case ThreadNexus::cBlocking: case ThreadNexus::cUnmanaged: case ThreadNexus::cWaiting: case ThreadNexus::cSleeping: default: thread_phase_ = thread_phase; } } utilities::thread::SpinLock& interrupt_lock() { return interrupt_lock_; } void set_zombie(STATE); bool zombie_p() { return zombie_; } void set_main_thread() { main_thread_ = true; } bool main_thread_p() { return main_thread_; } VMThreadState* thread_state() { return &thread_state_; } Memory* memory() { return shared.memory(); } void raise_stack_error(STATE); size_t stack_size() { return current_stack_size_; } void restore_stack_bounds() { current_stack_start_ = stack_start_; current_stack_size_ = stack_size_; } void set_stack_bounds(void* start, size_t size) { current_stack_start_ = start; current_stack_size_ = size; } void set_stack_bounds(size_t size); bool check_stack(STATE, void* stack_address) { ssize_t stack_used = (reinterpret_cast<intptr_t>(current_stack_start_) - reinterpret_cast<intptr_t>(stack_address)); if(stack_used < 0) stack_used = -stack_used; if(stack_used > stack_size_) { raise_stack_error(state); return false; } return true; } bool push_call_frame(STATE, CallFrame* frame, CallFrame*& previous_frame); bool pop_call_frame(STATE, CallFrame* frame) { call_frame_ = frame; return !thread_interrupted_p(state); } bool thread_interrupted_p(STATE) { if(check_local_interrupts()) { return check_thread_raise_or_kill(state); } return false; } bool check_thread_raise_or_kill(STATE); // Do NOT de-duplicate void set_call_frame(CallFrame* frame) { call_frame_ = frame; } CallFrame* call_frame() { return call_frame_; } CallFrame* get_call_frame(ssize_t up=0); CallFrame* get_ruby_frame(ssize_t up=0); CallFrame* get_variables_frame(ssize_t up=0); CallFrame* get_scope_frame(ssize_t up=0); bool scope_valid_p(VariableScope* scope); void set_call_site_information(CallSiteInformation* info) { saved_call_site_information_ = info; } CallSiteInformation* saved_call_site_information() { return saved_call_site_information_; } GlobalCache* global_cache() const { return shared.global_cache; } Globals& globals() { return shared.globals; } MethodMissingReason method_missing_reason() const { return method_missing_reason_; } void set_method_missing_reason(MethodMissingReason reason) { method_missing_reason_ = reason; } ConstantMissingReason constant_missing_reason() const { return constant_missing_reason_; } void set_constant_missing_reason(ConstantMissingReason reason) { constant_missing_reason_ = reason; } void after_fork_child(STATE); bool thread_step() const { return vm_jit_.thread_step_; } void clear_thread_step() { clear_check_local_interrupts(); vm_jit_.thread_step_ = false; } void set_thread_step() { set_check_local_interrupts(); vm_jit_.thread_step_ = true; } bool check_local_interrupts() const { return vm_jit_.check_local_interrupts_; } void clear_check_local_interrupts() { vm_jit_.check_local_interrupts_ = false; } void set_check_local_interrupts() { vm_jit_.check_local_interrupts_ = true; } bool interrupt_by_kill() const { return vm_jit_.interrupt_by_kill_; } void clear_interrupt_by_kill() { vm_jit_.interrupt_by_kill_ = false; } void set_interrupt_by_kill() { vm_jit_.interrupt_by_kill_ = true; } Exception* interrupted_exception() const { return interrupted_exception_.get(); } void clear_interrupted_exception() { interrupted_exception_.set(cNil); } rbxti::Env* tooling_env() const { return tooling_env_; } bool tooling() const { return tooling_; } void enable_tooling() { tooling_ = true; } void disable_tooling() { tooling_ = false; } bool allocation_tracking() const { return allocation_tracking_; } void enable_allocation_tracking() { allocation_tracking_ = true; } void disable_allocation_tracking() { allocation_tracking_ = false; } FiberStack* allocate_fiber_stack() { return fiber_stacks_.allocate(); } void* fiber_trampoline() { return fiber_stacks_.trampoline(); } FiberData* new_fiber_data(bool root=false) { return fiber_stacks_.new_data(root); } void remove_fiber_data(FiberData* data) { fiber_stacks_.remove_data(data); } memory::VariableRootBuffers& current_root_buffers(); public: static VM* current(); static void discard(STATE, VM*); public: /* Prototypes */ VM(uint32_t id, SharedState& shared, const char* name = NULL); ~VM(); void bootstrap_class(STATE); void bootstrap_ontology(STATE); void bootstrap_symbol(STATE); void initialize_config(); void collect_maybe(STATE); void checkpoint(STATE) { metrics().machine.checkpoints++; if(thread_nexus_->stop_lock(this)) { metrics().machine.stops++; collect_maybe(state); thread_nexus_->unlock(); } } void blocking_suspend(STATE, metrics::metric& counter); void sleeping_suspend(STATE, metrics::metric& counter); void become_managed(); void become_unmanaged() { thread_phase_ = ThreadNexus::cUnmanaged; } void set_current_thread(); void setup_errno(STATE, int num, const char* name, Class* sce, Module* ern); void bootstrap_exceptions(STATE); void initialize_fundamental_constants(STATE); void initialize_builtin_classes(STATE); void initialize_platform_data(STATE); Object* ruby_lib_version(); void set_current_fiber(Fiber* fib); TypeInfo* find_type(int type); static void init_ffi(STATE); void raise_from_errno(const char* reason); void raise_exception(Exception* exc); Exception* new_exception(Class* cls, const char* msg); Object* current_block(); void set_const(const char* name, Object* val); void set_const(Module* mod, const char* name, Object* val); Object* path2class(const char* name); llvm::Module* llvm_module(); void llvm_cleanup(); void print_backtrace(); void wait_on_channel(Channel* channel); void wait_on_inflated_lock(Object* wait); void wait_on_custom_function(void (*func)(void*), void* data); void clear_waiter(); bool wakeup(STATE); void reset_parked(); void set_sleeping(); void clear_sleeping(); void interrupt_with_signal(); bool should_interrupt_with_signal() const { return vm_jit_.interrupt_with_signal_; } void register_raise(STATE, Exception* exc); void register_kill(STATE); void gc_scan(memory::GarbageCollector* gc); void gc_fiber_clear_mark(); void gc_fiber_scan(memory::GarbageCollector* gc, bool only_marked = true); void gc_verify(memory::GarbageCollector* gc); }; } #endif <commit_msg>Cast cast cast your bits gently for GCC. Closes #3652.<commit_after>#ifndef RBX_VM_H #define RBX_VM_H #include "missing/time.h" #include "vm_jit.hpp" #include "globals.hpp" #include "memory/object_mark.hpp" #include "memory/managed.hpp" #include "vm_thread_state.hpp" #include "thread_nexus.hpp" #include "metrics.hpp" #include "util/thread.hpp" #include "memory/variable_buffer.hpp" #include "memory/root_buffer.hpp" #include "memory/slab.hpp" #include "shared_state.hpp" #include "unwind_info.hpp" #include "fiber_stack.hpp" #include <vector> #include <setjmp.h> namespace llvm { class Module; } namespace rbxti { class Env; } namespace rubinius { class Exception; class LLVMState; namespace event { class Loop; } namespace memory { class GarbageCollector; class WriteBarrier; } class Channel; class GlobalCache; class Primitives; class Memory; class TypeInfo; class String; class Symbol; class ConfigParser; class TypeError; class Assertion; struct CallFrame; class CallSiteInformation; class Object; class Configuration; class VMManager; class LookupTable; class SymbolTable; class SharedState; class Fiber; class Park; class NativeMethodEnvironment; class VariableScope; enum MethodMissingReason { eNone, ePrivate, eProtected, eSuper, eVCall, eNormal }; enum ConstantMissingReason { vFound, vPrivate, vNonExistent }; /** * Represents an execution context for running Ruby code. * * Each Ruby thread is backed by an instance of this class, as well as an * instance of the Thread class. Thread manages the (Ruby visible) thread- * related state, while this class manages the execution machinery for * running Ruby code. */ class VM : public memory::ManagedThread { friend class State; friend class VMJIT; private: UnwindInfoSet unwinds_; CallFrame* call_frame_; ThreadNexus* thread_nexus_; CallSiteInformation* saved_call_site_information_; FiberStacks fiber_stacks_; Park* park_; rbxti::Env* tooling_env_; void* stack_start_; size_t stack_size_; void* current_stack_start_; size_t current_stack_size_; utilities::thread::SpinLock interrupt_lock_; VMJIT vm_jit_; MethodMissingReason method_missing_reason_; ConstantMissingReason constant_missing_reason_; bool zombie_; bool tooling_; bool allocation_tracking_; bool main_thread_; ThreadNexus::Phase thread_phase_; public: /* Data members */ SharedState& shared; memory::TypedRoot<Channel*> waiting_channel_; memory::TypedRoot<Exception*> interrupted_exception_; /// The Thread object for this VM state memory::TypedRoot<Thread*> thread; /// The current fiber running on this thread memory::TypedRoot<Fiber*> current_fiber; /// Root fiber, if any (lazily initialized) memory::TypedRoot<Fiber*> root_fiber; /// Object that waits for inflation memory::TypedRoot<Object*> waiting_object_; NativeMethodEnvironment* native_method_environment; void (*custom_wakeup_)(void*); void* custom_wakeup_data_; VMThreadState thread_state_; public: /* Inline methods */ UnwindInfoSet& unwinds() { return unwinds_; } uint32_t thread_id() const { return id_; } ThreadNexus::Phase thread_phase() { return thread_phase_; } ThreadNexus* thread_nexus() { return thread_nexus_; } void set_thread_phase(ThreadNexus::Phase thread_phase) { thread_phase_ = thread_phase; } void restore_thread_phase(ThreadNexus::Phase thread_phase) { switch(thread_phase) { case ThreadNexus::cManaged: become_managed(); break; case ThreadNexus::cBlocking: case ThreadNexus::cUnmanaged: case ThreadNexus::cWaiting: case ThreadNexus::cSleeping: default: thread_phase_ = thread_phase; } } utilities::thread::SpinLock& interrupt_lock() { return interrupt_lock_; } void set_zombie(STATE); bool zombie_p() { return zombie_; } void set_main_thread() { main_thread_ = true; } bool main_thread_p() { return main_thread_; } VMThreadState* thread_state() { return &thread_state_; } Memory* memory() { return shared.memory(); } void raise_stack_error(STATE); size_t stack_size() { return current_stack_size_; } void restore_stack_bounds() { current_stack_start_ = stack_start_; current_stack_size_ = stack_size_; } void set_stack_bounds(void* start, size_t size) { current_stack_start_ = start; current_stack_size_ = size; } void set_stack_bounds(size_t size); bool check_stack(STATE, void* stack_address) { ssize_t stack_used = (reinterpret_cast<intptr_t>(current_stack_start_) - reinterpret_cast<intptr_t>(stack_address)); if(stack_used < 0) stack_used = -stack_used; if(static_cast<size_t>(stack_used) > stack_size_) { raise_stack_error(state); return false; } return true; } bool push_call_frame(STATE, CallFrame* frame, CallFrame*& previous_frame); bool pop_call_frame(STATE, CallFrame* frame) { call_frame_ = frame; return !thread_interrupted_p(state); } bool thread_interrupted_p(STATE) { if(check_local_interrupts()) { return check_thread_raise_or_kill(state); } return false; } bool check_thread_raise_or_kill(STATE); // Do NOT de-duplicate void set_call_frame(CallFrame* frame) { call_frame_ = frame; } CallFrame* call_frame() { return call_frame_; } CallFrame* get_call_frame(ssize_t up=0); CallFrame* get_ruby_frame(ssize_t up=0); CallFrame* get_variables_frame(ssize_t up=0); CallFrame* get_scope_frame(ssize_t up=0); bool scope_valid_p(VariableScope* scope); void set_call_site_information(CallSiteInformation* info) { saved_call_site_information_ = info; } CallSiteInformation* saved_call_site_information() { return saved_call_site_information_; } GlobalCache* global_cache() const { return shared.global_cache; } Globals& globals() { return shared.globals; } MethodMissingReason method_missing_reason() const { return method_missing_reason_; } void set_method_missing_reason(MethodMissingReason reason) { method_missing_reason_ = reason; } ConstantMissingReason constant_missing_reason() const { return constant_missing_reason_; } void set_constant_missing_reason(ConstantMissingReason reason) { constant_missing_reason_ = reason; } void after_fork_child(STATE); bool thread_step() const { return vm_jit_.thread_step_; } void clear_thread_step() { clear_check_local_interrupts(); vm_jit_.thread_step_ = false; } void set_thread_step() { set_check_local_interrupts(); vm_jit_.thread_step_ = true; } bool check_local_interrupts() const { return vm_jit_.check_local_interrupts_; } void clear_check_local_interrupts() { vm_jit_.check_local_interrupts_ = false; } void set_check_local_interrupts() { vm_jit_.check_local_interrupts_ = true; } bool interrupt_by_kill() const { return vm_jit_.interrupt_by_kill_; } void clear_interrupt_by_kill() { vm_jit_.interrupt_by_kill_ = false; } void set_interrupt_by_kill() { vm_jit_.interrupt_by_kill_ = true; } Exception* interrupted_exception() const { return interrupted_exception_.get(); } void clear_interrupted_exception() { interrupted_exception_.set(cNil); } rbxti::Env* tooling_env() const { return tooling_env_; } bool tooling() const { return tooling_; } void enable_tooling() { tooling_ = true; } void disable_tooling() { tooling_ = false; } bool allocation_tracking() const { return allocation_tracking_; } void enable_allocation_tracking() { allocation_tracking_ = true; } void disable_allocation_tracking() { allocation_tracking_ = false; } FiberStack* allocate_fiber_stack() { return fiber_stacks_.allocate(); } void* fiber_trampoline() { return fiber_stacks_.trampoline(); } FiberData* new_fiber_data(bool root=false) { return fiber_stacks_.new_data(root); } void remove_fiber_data(FiberData* data) { fiber_stacks_.remove_data(data); } memory::VariableRootBuffers& current_root_buffers(); public: static VM* current(); static void discard(STATE, VM*); public: /* Prototypes */ VM(uint32_t id, SharedState& shared, const char* name = NULL); ~VM(); void bootstrap_class(STATE); void bootstrap_ontology(STATE); void bootstrap_symbol(STATE); void initialize_config(); void collect_maybe(STATE); void checkpoint(STATE) { metrics().machine.checkpoints++; if(thread_nexus_->stop_lock(this)) { metrics().machine.stops++; collect_maybe(state); thread_nexus_->unlock(); } } void blocking_suspend(STATE, metrics::metric& counter); void sleeping_suspend(STATE, metrics::metric& counter); void become_managed(); void become_unmanaged() { thread_phase_ = ThreadNexus::cUnmanaged; } void set_current_thread(); void setup_errno(STATE, int num, const char* name, Class* sce, Module* ern); void bootstrap_exceptions(STATE); void initialize_fundamental_constants(STATE); void initialize_builtin_classes(STATE); void initialize_platform_data(STATE); Object* ruby_lib_version(); void set_current_fiber(Fiber* fib); TypeInfo* find_type(int type); static void init_ffi(STATE); void raise_from_errno(const char* reason); void raise_exception(Exception* exc); Exception* new_exception(Class* cls, const char* msg); Object* current_block(); void set_const(const char* name, Object* val); void set_const(Module* mod, const char* name, Object* val); Object* path2class(const char* name); llvm::Module* llvm_module(); void llvm_cleanup(); void print_backtrace(); void wait_on_channel(Channel* channel); void wait_on_inflated_lock(Object* wait); void wait_on_custom_function(void (*func)(void*), void* data); void clear_waiter(); bool wakeup(STATE); void reset_parked(); void set_sleeping(); void clear_sleeping(); void interrupt_with_signal(); bool should_interrupt_with_signal() const { return vm_jit_.interrupt_with_signal_; } void register_raise(STATE, Exception* exc); void register_kill(STATE); void gc_scan(memory::GarbageCollector* gc); void gc_fiber_clear_mark(); void gc_fiber_scan(memory::GarbageCollector* gc, bool only_marked = true); void gc_verify(memory::GarbageCollector* gc); }; } #endif <|endoftext|>
<commit_before>/* * Copyright (c) 2017, The OpenThread Authors. * 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. */ /** * @file * This file implements the web server of border router */ #include "web/web-service/web_server.hpp" #define BOOST_NO_CXX11_SCOPED_ENUMS #include <boost/filesystem.hpp> #undef BOOST_NO_CXX11_SCOPED_ENUMS #include <server_http.hpp> #define OT_ADD_PREFIX_PATH "^/add_prefix" #define OT_AVAILABLE_NETWORK_PATH "^/available_network$" #define OT_DELETE_PREFIX_PATH "^/delete_prefix" #define OT_FORM_NETWORK_PATH "^/form_network$" #define OT_GET_NETWORK_PATH "^/get_properties$" #define OT_JOIN_NETWORK_PATH "^/join_network$" #define OT_SET_NETWORK_PATH "^/settings$" #define OT_COMMISSIONER_START_PATH "^/commission$" #define OT_REQUEST_METHOD_GET "GET" #define OT_REQUEST_METHOD_POST "POST" #define OT_RESPONSE_SUCCESS_STATUS "HTTP/1.1 200 OK\r\n" #define OT_RESPONSE_HEADER_LENGTH "Content-Length: " #define OT_RESPONSE_HEADER_CSS_TYPE "\r\nContent-Type: text/css" #define OT_RESPONSE_HEADER_TYPE "Content-Type: application/json\r\n charset=utf-8" #define OT_RESPONSE_PLACEHOLD "\r\n\r\n" #define OT_RESPONSE_FAILURE_STATUS "HTTP/1.1 400 Bad Request\r\n" #define OT_BUFFER_SIZE 1024 namespace otbr { namespace Web { WebServer::WebServer(void) : mServer(new HttpServer()) { } WebServer::~WebServer(void) { delete mServer; } void WebServer::Init() { std::string networkName, extPanId; if (mWpanService.GetWpanServiceStatus(networkName, extPanId) > 0) { return; } } void WebServer::StartWebServer(const char *aIfName, const char *aListenAddr, uint16_t aPort) { if (aListenAddr != NULL) { mServer->config.address = aListenAddr; } mServer->config.port = aPort; mWpanService.SetInterfaceName(aIfName); Init(); ResponseJoinNetwork(); ResponseFormNetwork(); ResponseAddOnMeshPrefix(); ResponseDeleteOnMeshPrefix(); ResponseGetStatus(); ResponseGetAvailableNetwork(); ResponseCommission(); DefaultHttpResponse(); mServer->start(); } void WebServer::StopWebServer(void) { mServer->stop(); } void WebServer::HandleHttpRequest(const char *aUrl, const char *aMethod, HttpRequestCallback aCallback) { mServer->resource[aUrl][aMethod] = [aCallback, this](std::shared_ptr<HttpServer::Response> response, std::shared_ptr<HttpServer::Request> request) { try { std::string httpResponse; if (aCallback != NULL) { httpResponse = aCallback(request->content.string(), this); } *response << OT_RESPONSE_SUCCESS_STATUS << OT_RESPONSE_HEADER_LENGTH << httpResponse.length() << OT_RESPONSE_PLACEHOLD << httpResponse; } catch (std::exception &e) { *response << OT_RESPONSE_FAILURE_STATUS << OT_RESPONSE_HEADER_LENGTH << strlen(e.what()) << OT_RESPONSE_PLACEHOLD << e.what(); } }; } void DefaultResourceSend(const HttpServer & aServer, const std::shared_ptr<HttpServer::Response> &aResponse, const std::shared_ptr<std::ifstream> & aIfStream) { static std::vector<char> buffer(OT_BUFFER_SIZE); // Safe when server is running on one thread std::streamsize readLength; if ((readLength = aIfStream->read(&buffer[0], buffer.size()).gcount()) > 0) { aResponse->write(&buffer[0], readLength); if (readLength == static_cast<std::streamsize>(buffer.size())) { aServer.send(aResponse, [&aServer, aResponse, aIfStream](const boost::system::error_code &ec) { if (!ec) { DefaultResourceSend(aServer, aResponse, aIfStream); } else { std::cerr << "Connection interrupted" << std::endl; } }); } } } void WebServer::DefaultHttpResponse(void) { mServer->default_resource[OT_REQUEST_METHOD_GET] = [this](std::shared_ptr<HttpServer::Response> response, std::shared_ptr<HttpServer::Request> request) { try { auto webRootPath = boost::filesystem::canonical(WEB_FILE_PATH); auto path = boost::filesystem::canonical(webRootPath / request->path); // Check if path is within webRootPath if (std::distance(webRootPath.begin(), webRootPath.end()) > std::distance(path.begin(), path.end()) || !std::equal(webRootPath.begin(), webRootPath.end(), path.begin())) { throw std::invalid_argument("path must be within root path"); } if (boost::filesystem::is_directory(path)) { path /= "index.html"; } if (!(boost::filesystem::exists(path) && boost::filesystem::is_regular_file(path))) { throw std::invalid_argument("file does not exist"); } std::string cacheControl, etag; auto ifs = std::make_shared<std::ifstream>(); ifs->open(path.string(), std::ifstream::in | std::ios::binary | std::ios::ate); std::string extension = boost::filesystem::extension(path.string()); std::string style = ""; if (extension == ".css") { style = OT_RESPONSE_HEADER_CSS_TYPE; } if (*ifs) { auto length = ifs->tellg(); ifs->seekg(0, std::ios::beg); *response << OT_RESPONSE_SUCCESS_STATUS << cacheControl << etag << OT_RESPONSE_HEADER_LENGTH << length << style << OT_RESPONSE_PLACEHOLD; DefaultResourceSend(*mServer, response, ifs); } else { throw std::invalid_argument("could not read file"); } } catch (const std::exception &e) { std::string content = "Could not open path"; *response << OT_RESPONSE_FAILURE_STATUS << OT_RESPONSE_HEADER_LENGTH << content.length() << OT_RESPONSE_PLACEHOLD << content; } }; } std::string WebServer::HandleJoinNetworkRequest(const std::string &aJoinRequest, void *aUserData) { WebServer *webServer = static_cast<WebServer *>(aUserData); return webServer->HandleJoinNetworkRequest(aJoinRequest); } std::string WebServer::HandleFormNetworkRequest(const std::string &aFormRequest, void *aUserData) { WebServer *webServer = static_cast<WebServer *>(aUserData); return webServer->HandleFormNetworkRequest(aFormRequest); } std::string WebServer::HandleAddPrefixRequest(const std::string &aAddPrefixRequest, void *aUserData) { WebServer *webServer = static_cast<WebServer *>(aUserData); return webServer->HandleAddPrefixRequest(aAddPrefixRequest); } std::string WebServer::HandleDeletePrefixRequest(const std::string &aDeletePrefixRequest, void *aUserData) { WebServer *webServer = static_cast<WebServer *>(aUserData); return webServer->HandleDeletePrefixRequest(aDeletePrefixRequest); } std::string WebServer::HandleGetStatusRequest(const std::string &aGetStatusRequest, void *aUserData) { WebServer *webServer = static_cast<WebServer *>(aUserData); return webServer->HandleGetStatusRequest(aGetStatusRequest); } std::string WebServer::HandleGetAvailableNetworkResponse(const std::string &aGetAvailableNetworkRequest, void * aUserData) { WebServer *webServer = static_cast<WebServer *>(aUserData); return webServer->HandleGetAvailableNetworkResponse(aGetAvailableNetworkRequest); } std::string WebServer::HandleCommission(const std::string &aCommissionRequest, void *aUserData) { WebServer *webServer = static_cast<WebServer *>(aUserData); return webServer->HandleCommission(aCommissionRequest); } void WebServer::ResponseJoinNetwork(void) { HandleHttpRequest(OT_JOIN_NETWORK_PATH, OT_REQUEST_METHOD_POST, HandleJoinNetworkRequest); } void WebServer::ResponseFormNetwork(void) { HandleHttpRequest(OT_FORM_NETWORK_PATH, OT_REQUEST_METHOD_POST, HandleFormNetworkRequest); } void WebServer::ResponseAddOnMeshPrefix(void) { HandleHttpRequest(OT_ADD_PREFIX_PATH, OT_REQUEST_METHOD_POST, HandleAddPrefixRequest); } void WebServer::ResponseDeleteOnMeshPrefix(void) { HandleHttpRequest(OT_DELETE_PREFIX_PATH, OT_REQUEST_METHOD_POST, HandleDeletePrefixRequest); } void WebServer::ResponseGetStatus(void) { HandleHttpRequest(OT_GET_NETWORK_PATH, OT_REQUEST_METHOD_GET, HandleGetStatusRequest); } void WebServer::ResponseGetAvailableNetwork(void) { HandleHttpRequest(OT_AVAILABLE_NETWORK_PATH, OT_REQUEST_METHOD_GET, HandleGetAvailableNetworkResponse); } void WebServer::ResponseCommission(void) { HandleHttpRequest(OT_COMMISSIONER_START_PATH, OT_REQUEST_METHOD_POST, HandleCommission); } std::string WebServer::HandleJoinNetworkRequest(const std::string &aJoinRequest) { return mWpanService.HandleJoinNetworkRequest(aJoinRequest); } std::string WebServer::HandleFormNetworkRequest(const std::string &aFormRequest) { return mWpanService.HandleFormNetworkRequest(aFormRequest); } std::string WebServer::HandleAddPrefixRequest(const std::string &aAddPrefixRequest) { return mWpanService.HandleAddPrefixRequest(aAddPrefixRequest); } std::string WebServer::HandleDeletePrefixRequest(const std::string &aDeletePrefixRequest) { return mWpanService.HandleDeletePrefixRequest(aDeletePrefixRequest); } std::string WebServer::HandleGetStatusRequest(const std::string &aGetStatusRequest) { (void)aGetStatusRequest; return mWpanService.HandleStatusRequest(); } std::string WebServer::HandleGetAvailableNetworkResponse(const std::string &aGetAvailableNetworkRequest) { (void)aGetAvailableNetworkRequest; return mWpanService.HandleAvailableNetworkRequest(); } std::string WebServer::HandleCommission(const std::string &aCommissionRequest) { return mWpanService.HandleCommission(aCommissionRequest); } } // namespace Web } // namespace otbr <commit_msg>[web] verbose invalid path exception (#480)<commit_after>/* * Copyright (c) 2017, The OpenThread Authors. * 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. */ /** * @file * This file implements the web server of border router */ #include "web/web-service/web_server.hpp" #define BOOST_NO_CXX11_SCOPED_ENUMS #include <boost/filesystem.hpp> #undef BOOST_NO_CXX11_SCOPED_ENUMS #include <server_http.hpp> #define OT_ADD_PREFIX_PATH "^/add_prefix" #define OT_AVAILABLE_NETWORK_PATH "^/available_network$" #define OT_DELETE_PREFIX_PATH "^/delete_prefix" #define OT_FORM_NETWORK_PATH "^/form_network$" #define OT_GET_NETWORK_PATH "^/get_properties$" #define OT_JOIN_NETWORK_PATH "^/join_network$" #define OT_SET_NETWORK_PATH "^/settings$" #define OT_COMMISSIONER_START_PATH "^/commission$" #define OT_REQUEST_METHOD_GET "GET" #define OT_REQUEST_METHOD_POST "POST" #define OT_RESPONSE_SUCCESS_STATUS "HTTP/1.1 200 OK\r\n" #define OT_RESPONSE_HEADER_LENGTH "Content-Length: " #define OT_RESPONSE_HEADER_CSS_TYPE "\r\nContent-Type: text/css" #define OT_RESPONSE_HEADER_TYPE "Content-Type: application/json\r\n charset=utf-8" #define OT_RESPONSE_PLACEHOLD "\r\n\r\n" #define OT_RESPONSE_FAILURE_STATUS "HTTP/1.1 400 Bad Request\r\n" #define OT_BUFFER_SIZE 1024 namespace otbr { namespace Web { WebServer::WebServer(void) : mServer(new HttpServer()) { } WebServer::~WebServer(void) { delete mServer; } void WebServer::Init() { std::string networkName, extPanId; if (mWpanService.GetWpanServiceStatus(networkName, extPanId) > 0) { return; } } void WebServer::StartWebServer(const char *aIfName, const char *aListenAddr, uint16_t aPort) { if (aListenAddr != NULL) { mServer->config.address = aListenAddr; } mServer->config.port = aPort; mWpanService.SetInterfaceName(aIfName); Init(); ResponseJoinNetwork(); ResponseFormNetwork(); ResponseAddOnMeshPrefix(); ResponseDeleteOnMeshPrefix(); ResponseGetStatus(); ResponseGetAvailableNetwork(); ResponseCommission(); DefaultHttpResponse(); mServer->start(); } void WebServer::StopWebServer(void) { mServer->stop(); } void WebServer::HandleHttpRequest(const char *aUrl, const char *aMethod, HttpRequestCallback aCallback) { mServer->resource[aUrl][aMethod] = [aCallback, this](std::shared_ptr<HttpServer::Response> response, std::shared_ptr<HttpServer::Request> request) { try { std::string httpResponse; if (aCallback != NULL) { httpResponse = aCallback(request->content.string(), this); } *response << OT_RESPONSE_SUCCESS_STATUS << OT_RESPONSE_HEADER_LENGTH << httpResponse.length() << OT_RESPONSE_PLACEHOLD << httpResponse; } catch (std::exception &e) { *response << OT_RESPONSE_FAILURE_STATUS << OT_RESPONSE_HEADER_LENGTH << strlen(e.what()) << OT_RESPONSE_PLACEHOLD << e.what(); } }; } void DefaultResourceSend(const HttpServer & aServer, const std::shared_ptr<HttpServer::Response> &aResponse, const std::shared_ptr<std::ifstream> & aIfStream) { static std::vector<char> buffer(OT_BUFFER_SIZE); // Safe when server is running on one thread std::streamsize readLength; if ((readLength = aIfStream->read(&buffer[0], buffer.size()).gcount()) > 0) { aResponse->write(&buffer[0], readLength); if (readLength == static_cast<std::streamsize>(buffer.size())) { aServer.send(aResponse, [&aServer, aResponse, aIfStream](const boost::system::error_code &ec) { if (!ec) { DefaultResourceSend(aServer, aResponse, aIfStream); } else { std::cerr << "Connection interrupted" << std::endl; } }); } } } void WebServer::DefaultHttpResponse(void) { mServer->default_resource[OT_REQUEST_METHOD_GET] = [this](std::shared_ptr<HttpServer::Response> response, std::shared_ptr<HttpServer::Request> request) { try { auto webRootPath = boost::filesystem::canonical(WEB_FILE_PATH); auto path = boost::filesystem::canonical(webRootPath / request->path); // Check if path is within webRootPath if (std::distance(webRootPath.begin(), webRootPath.end()) > std::distance(path.begin(), path.end()) || !std::equal(webRootPath.begin(), webRootPath.end(), path.begin())) { throw std::invalid_argument("path must be within root path"); } if (boost::filesystem::is_directory(path)) { path /= "index.html"; } if (!(boost::filesystem::exists(path) && boost::filesystem::is_regular_file(path))) { throw std::invalid_argument("file does not exist"); } std::string cacheControl, etag; auto ifs = std::make_shared<std::ifstream>(); ifs->open(path.string(), std::ifstream::in | std::ios::binary | std::ios::ate); std::string extension = boost::filesystem::extension(path.string()); std::string style = ""; if (extension == ".css") { style = OT_RESPONSE_HEADER_CSS_TYPE; } if (*ifs) { auto length = ifs->tellg(); ifs->seekg(0, std::ios::beg); *response << OT_RESPONSE_SUCCESS_STATUS << cacheControl << etag << OT_RESPONSE_HEADER_LENGTH << length << style << OT_RESPONSE_PLACEHOLD; DefaultResourceSend(*mServer, response, ifs); } else { throw std::invalid_argument("could not read file"); } } catch (const std::exception &e) { std::string content = "Could not open path `" + request->path + "`: " + e.what(); *response << OT_RESPONSE_FAILURE_STATUS << OT_RESPONSE_HEADER_LENGTH << content.length() << OT_RESPONSE_PLACEHOLD << content; } }; } std::string WebServer::HandleJoinNetworkRequest(const std::string &aJoinRequest, void *aUserData) { WebServer *webServer = static_cast<WebServer *>(aUserData); return webServer->HandleJoinNetworkRequest(aJoinRequest); } std::string WebServer::HandleFormNetworkRequest(const std::string &aFormRequest, void *aUserData) { WebServer *webServer = static_cast<WebServer *>(aUserData); return webServer->HandleFormNetworkRequest(aFormRequest); } std::string WebServer::HandleAddPrefixRequest(const std::string &aAddPrefixRequest, void *aUserData) { WebServer *webServer = static_cast<WebServer *>(aUserData); return webServer->HandleAddPrefixRequest(aAddPrefixRequest); } std::string WebServer::HandleDeletePrefixRequest(const std::string &aDeletePrefixRequest, void *aUserData) { WebServer *webServer = static_cast<WebServer *>(aUserData); return webServer->HandleDeletePrefixRequest(aDeletePrefixRequest); } std::string WebServer::HandleGetStatusRequest(const std::string &aGetStatusRequest, void *aUserData) { WebServer *webServer = static_cast<WebServer *>(aUserData); return webServer->HandleGetStatusRequest(aGetStatusRequest); } std::string WebServer::HandleGetAvailableNetworkResponse(const std::string &aGetAvailableNetworkRequest, void * aUserData) { WebServer *webServer = static_cast<WebServer *>(aUserData); return webServer->HandleGetAvailableNetworkResponse(aGetAvailableNetworkRequest); } std::string WebServer::HandleCommission(const std::string &aCommissionRequest, void *aUserData) { WebServer *webServer = static_cast<WebServer *>(aUserData); return webServer->HandleCommission(aCommissionRequest); } void WebServer::ResponseJoinNetwork(void) { HandleHttpRequest(OT_JOIN_NETWORK_PATH, OT_REQUEST_METHOD_POST, HandleJoinNetworkRequest); } void WebServer::ResponseFormNetwork(void) { HandleHttpRequest(OT_FORM_NETWORK_PATH, OT_REQUEST_METHOD_POST, HandleFormNetworkRequest); } void WebServer::ResponseAddOnMeshPrefix(void) { HandleHttpRequest(OT_ADD_PREFIX_PATH, OT_REQUEST_METHOD_POST, HandleAddPrefixRequest); } void WebServer::ResponseDeleteOnMeshPrefix(void) { HandleHttpRequest(OT_DELETE_PREFIX_PATH, OT_REQUEST_METHOD_POST, HandleDeletePrefixRequest); } void WebServer::ResponseGetStatus(void) { HandleHttpRequest(OT_GET_NETWORK_PATH, OT_REQUEST_METHOD_GET, HandleGetStatusRequest); } void WebServer::ResponseGetAvailableNetwork(void) { HandleHttpRequest(OT_AVAILABLE_NETWORK_PATH, OT_REQUEST_METHOD_GET, HandleGetAvailableNetworkResponse); } void WebServer::ResponseCommission(void) { HandleHttpRequest(OT_COMMISSIONER_START_PATH, OT_REQUEST_METHOD_POST, HandleCommission); } std::string WebServer::HandleJoinNetworkRequest(const std::string &aJoinRequest) { return mWpanService.HandleJoinNetworkRequest(aJoinRequest); } std::string WebServer::HandleFormNetworkRequest(const std::string &aFormRequest) { return mWpanService.HandleFormNetworkRequest(aFormRequest); } std::string WebServer::HandleAddPrefixRequest(const std::string &aAddPrefixRequest) { return mWpanService.HandleAddPrefixRequest(aAddPrefixRequest); } std::string WebServer::HandleDeletePrefixRequest(const std::string &aDeletePrefixRequest) { return mWpanService.HandleDeletePrefixRequest(aDeletePrefixRequest); } std::string WebServer::HandleGetStatusRequest(const std::string &aGetStatusRequest) { (void)aGetStatusRequest; return mWpanService.HandleStatusRequest(); } std::string WebServer::HandleGetAvailableNetworkResponse(const std::string &aGetAvailableNetworkRequest) { (void)aGetAvailableNetworkRequest; return mWpanService.HandleAvailableNetworkRequest(); } std::string WebServer::HandleCommission(const std::string &aCommissionRequest) { return mWpanService.HandleCommission(aCommissionRequest); } } // namespace Web } // namespace otbr <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: AntiAliasBinaryImageFilter.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information. =========================================================================*/ // Software Guide : BeginLatex // // This example introduces the use of the \doxygen{AntiAliasBinaryImageFilter}. This // filter expect a binary mask as input, and using Level Sets it smooths the // image by keeping the edge of the structure within 1 pixel distance from the // original location. It is usually desirable to run this filter before // extracting isocontour with surface extraction methods. // // \index{itk::AntiAliasBinaryImageFilter|textbf} // // Software Guide : EndLatex #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkCastImageFilter.h" #include "itkRescaleIntensityImageFilter.h" // Software Guide : BeginLatex // // The first step required for using this filter is to include its header file // // \index{itk::AntiAliasBinaryImageFilter!header} // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet #include "itkAntiAliasBinaryImageFilter.h" // Software Guide : EndCodeSnippet int main(int argc, char** argv) { if( argc < 3 ) { std::cerr << "Usage: " << std::endl; std::cerr << argv[0] << " inputImage outputImage [RMS] [numberOfIterations]" << std::endl; return -1; } const char * inputFilename = argv[1]; const char * outputFilename = argv[2]; double maximumRMSError = 0.01; unsigned int numberOfIterations = 50; if( argc > 3 ) { maximumRMSError = atof( argv[3] ); } if( numberOfIterations > 4 ) { numberOfIterations = atoi( argv[4] ); } typedef unsigned char CharPixelType; // IO typedef double RealPixelType; // Operations const unsigned int Dimension = 3; typedef itk::Image<CharPixelType, Dimension> CharImageType; typedef itk::Image<RealPixelType, Dimension> RealImageType; typedef itk::ImageFileReader< CharImageType > ReaderType; typedef itk::ImageFileWriter< CharImageType > WriterType; // Software Guide : BeginLatex // // This filter operates on image of pixel type float. It is then necessary // to cast the type of the input images that are usually of integer type. // The \doxygen{CastImageFilter} is used here for that purpose. Its image // template parameters are defined for casting from the input type to the // float type using for processing. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef itk::CastImageFilter< CharImageType, RealImageType> CastToRealFilterType; // Software Guide : EndCodeSnippet typedef itk::RescaleIntensityImageFilter<RealImageType, CharImageType > RescaleFilter; // Software Guide : BeginLatex // // The \doxygen{AntiAliasBinaryImageFilter} is instantiated using the float image type. // // \index{itk::AntiAliasBinaryImageFilter|textbf} // // Software Guide : EndLatex typedef itk::AntiAliasBinaryImageFilter<RealImageType, RealImageType> AntiAliasFilterType; //Setting the IO ReaderType::Pointer reader = ReaderType::New(); WriterType::Pointer writer = WriterType::New(); CastToRealFilterType::Pointer toReal = CastToRealFilterType::New(); RescaleFilter::Pointer rescale = RescaleFilter::New(); //Setting the ITK pipeline filter // Software Guide : BeginCodeSnippet AntiAliasFilterType::Pointer antiAliasFilter = AntiAliasFilterType::New(); reader->SetFileName( inputFilename ); writer->SetFileName( outputFilename ); //The output of an edge filter is 0 or 1 rescale->SetOutputMinimum( 0 ); rescale->SetOutputMaximum( 255 ); toReal->SetInput( reader->GetOutput() ); antiAliasFilter->SetInput( toReal->GetOutput() ); antiAliasFilter->SetMaximumRMSError( maximumRMSError ); antiAliasFilter->SetNumberOfIterations( numberOfIterations ); antiAliasFilter->SetNumberOfLayers( 2 ); rescale->SetInput( antiAliasFilter->GetOutput() ); writer->SetInput( rescale->GetOutput() ); try { writer->Update(); } catch( itk::ExceptionObject & err ) { std::cout << "ExceptionObject caught !" << std::endl; std::cout << err << std::endl; return -1; } // Software Guide : EndCodeSnippet return 0; } <commit_msg>BUG: wrong logic for argument checking.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: AntiAliasBinaryImageFilter.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information. =========================================================================*/ // Software Guide : BeginLatex // // This example introduces the use of the \doxygen{AntiAliasBinaryImageFilter}. This // filter expect a binary mask as input, and using Level Sets it smooths the // image by keeping the edge of the structure within 1 pixel distance from the // original location. It is usually desirable to run this filter before // extracting isocontour with surface extraction methods. // // \index{itk::AntiAliasBinaryImageFilter|textbf} // // Software Guide : EndLatex #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkCastImageFilter.h" #include "itkRescaleIntensityImageFilter.h" // Software Guide : BeginLatex // // The first step required for using this filter is to include its header file // // \index{itk::AntiAliasBinaryImageFilter!header} // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet #include "itkAntiAliasBinaryImageFilter.h" // Software Guide : EndCodeSnippet int main(int argc, char* argv[]) { if( argc < 3 ) { std::cerr << "Usage: " << std::endl; std::cerr << argv[0] << " inputImage outputImage [RMS] [numberOfIterations]" << std::endl; return -1; } const char * inputFilename = argv[1]; const char * outputFilename = argv[2]; double maximumRMSError = 0.01; unsigned int numberOfIterations = 50; if( argc > 3 ) { maximumRMSError = atof( argv[3] ); } if( argc > 4 ) { numberOfIterations = atoi( argv[4] ); } typedef unsigned char CharPixelType; // IO typedef double RealPixelType; // Operations const unsigned int Dimension = 3; typedef itk::Image<CharPixelType, Dimension> CharImageType; typedef itk::Image<RealPixelType, Dimension> RealImageType; typedef itk::ImageFileReader< CharImageType > ReaderType; typedef itk::ImageFileWriter< CharImageType > WriterType; // Software Guide : BeginLatex // // This filter operates on image of pixel type float. It is then necessary // to cast the type of the input images that are usually of integer type. // The \doxygen{CastImageFilter} is used here for that purpose. Its image // template parameters are defined for casting from the input type to the // float type using for processing. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef itk::CastImageFilter< CharImageType, RealImageType> CastToRealFilterType; // Software Guide : EndCodeSnippet typedef itk::RescaleIntensityImageFilter<RealImageType, CharImageType > RescaleFilter; // Software Guide : BeginLatex // // The \doxygen{AntiAliasBinaryImageFilter} is instantiated using the float image type. // // \index{itk::AntiAliasBinaryImageFilter|textbf} // // Software Guide : EndLatex typedef itk::AntiAliasBinaryImageFilter<RealImageType, RealImageType> AntiAliasFilterType; //Setting the IO ReaderType::Pointer reader = ReaderType::New(); WriterType::Pointer writer = WriterType::New(); CastToRealFilterType::Pointer toReal = CastToRealFilterType::New(); RescaleFilter::Pointer rescale = RescaleFilter::New(); //Setting the ITK pipeline filter // Software Guide : BeginCodeSnippet AntiAliasFilterType::Pointer antiAliasFilter = AntiAliasFilterType::New(); reader->SetFileName( inputFilename ); writer->SetFileName( outputFilename ); //The output of an edge filter is 0 or 1 rescale->SetOutputMinimum( 0 ); rescale->SetOutputMaximum( 255 ); toReal->SetInput( reader->GetOutput() ); antiAliasFilter->SetInput( toReal->GetOutput() ); antiAliasFilter->SetMaximumRMSError( maximumRMSError ); antiAliasFilter->SetNumberOfIterations( numberOfIterations ); antiAliasFilter->SetNumberOfLayers( 2 ); rescale->SetInput( antiAliasFilter->GetOutput() ); writer->SetInput( rescale->GetOutput() ); try { writer->Update(); std::cout << "Completed in " << antiAliasFilter->GetNumberOfIterations() << std::endl; } catch( itk::ExceptionObject & err ) { std::cout << "ExceptionObject caught !" << std::endl; std::cout << err << std::endl; return -1; } // Software Guide : EndCodeSnippet return 0; } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: DeformableRegistration1.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information. =========================================================================*/ #include "itkImageFileReader.h" #include "itkImageFileWriter.h" //#include "itkMetaImageIO.h" #include "itkRescaleIntensityImageFilter.h" #include "itkHistogramMatchingImageFilter.h" // Software Guide : BeginLatex // // The finite element (FEM) library within the Insight Toolkit can be // used to solve deformable image registration problems. The first step in // implementing a FEM-based registration is to include the appropriate // header files. // // \index{Registration!Finite Element-Based} // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet #include "itkFEM.h" #include "itkFEMRegistrationFilter.h" // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Next, we use \code{typedef}s to instantiate all necessary classes. We // define the image and element types we plan to use to solve a // two-dimensional registration problem. We define multiple element // types so that they can be used without recompiling the code. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef itk::Image<unsigned char, 2> fileImageType; typedef itk::Image<float, 2> ImageType; typedef itk::fem::Element2DC0LinearQuadrilateralMembrane ElementType; typedef itk::fem::Element2DC0LinearTriangularMembrane ElementType2; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Note that in order to solve a three-dimensional registration // problem, we would simply define 3D image and element types in lieu // of those above. The following declarations could be used for a 3D // problem: // // SoftwareGuide : EndLatex // SoftwareGuide : BeginCodeSnippet typedef itk::Image<unsigned char, 3> fileImage3DType; typedef itk::Image<float, 3> Image3DType; typedef itk::fem::Element3DC0LinearHexahedronMembrane Element3DType; typedef itk::fem::Element3DC0LinearTetrahedronMembrane Element3DType2; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Here, we instantiate the load types and explicitly template the // load implementation type. We also define visitors that allow the // elements and loads to communicate with one another. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef itk::fem::ImageMetricLoad<ImageType,ImageType> ImageLoadType; template class itk::fem::ImageMetricLoadImplementation<ImageLoadType>; typedef ElementType::LoadImplementationFunctionPointer LoadImpFP; typedef ElementType::LoadType ElementLoadType; typedef ElementType2::LoadImplementationFunctionPointer LoadImpFP2; typedef ElementType2::LoadType ElementLoadType2; typedef itk::fem::VisitorDispatcher<ElementType,ElementLoadType, LoadImpFP> DispatcherType; typedef itk::fem::VisitorDispatcher<ElementType2,ElementLoadType2, LoadImpFP2> DispatcherType2; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Once all the necessary components have been instantianted, we can // instantiate the \doxygen{FEMRegistrationFilter}, which depends on the // image input and output types. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef itk::fem::FEMRegistrationFilter<ImageType,ImageType> RegistrationType; // Software Guide : EndCodeSnippet int main(int argc, char *argv[]) { char *paramname; if ( argc < 2 ) { std::cout << "Parameter file name missing" << std::endl; std::cout << "Usage: " << argv[0] << " param.file" << std::endl; return -1; } else { paramname=argv[1]; } // Software Guide : BeginLatex // // The \doxygen{FEMImageMetricLoad} must be registered before it // can be used correctly with a particular element type. An example // of this is shown below for \code{ElementType}. Similar // definitions are required for all other defined element types. // // Software Guide : EndLatex // Register the correct load implementation with the element-typed visitor dispatcher. { // Software Guide : BeginCodeSnippet ElementType::LoadImplementationFunctionPointer fp = &itk::fem::ImageMetricLoadImplementation<ImageLoadType>::ImplementImageMetricLoad; DispatcherType::RegisterVisitor((ImageLoadType*)0,fp); // Software Guide : EndCodeSnippet } { ElementType2::LoadImplementationFunctionPointer fp = &itk::fem::ImageMetricLoadImplementation<ImageLoadType>::ImplementImageMetricLoad; DispatcherType2::RegisterVisitor((ImageLoadType*)0,fp); } // Software Guide : BeginLatex // // In order to begin the registration, we declare an instance of the // \doxygen{FEMRegistrationFilter}. For simplicity, we will call // it \code{X}. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet RegistrationType::Pointer X = RegistrationType::New(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Next, we call \code{X->SetConfigFileName()} to read the parameter // file containing information we need to set up the registration // filter. A sample parameter file is shown at the end of this // section, and the individual components are labeled. // // Software Guide : EndLatex // Attempt to read the parameter file, and exit if an error occurs X->SetConfigFileName(paramname); if ( !X->ReadConfigFile( (X->GetConfigFileName()).c_str() ) ) { return -1; } // Read the image files typedef itk::ImageFileReader< fileImageType > FileSourceType; typedef fileImageType::PixelType PixType; FileSourceType::Pointer reffilter = FileSourceType::New(); reffilter->SetFileName( (X->GetMovingFile()).c_str() ); FileSourceType::Pointer tarfilter = FileSourceType::New(); tarfilter->SetFileName( (X->GetFixedFile()).c_str() ); try { reffilter->Update(); } catch( itk::ExceptionObject & e ) { std::cerr << "Exception caught during reference file reading " << std::endl; std::cerr << e << std::endl; return -1; } try { tarfilter->Update(); } catch( itk::ExceptionObject & e ) { std::cerr << "Exception caught during target file reading " << std::endl; std::cerr << e << std::endl; return -1; } // Rescale the image intensities so that they fall between 0 and 255 typedef itk::RescaleIntensityImageFilter<fileImageType,ImageType> FilterType; FilterType::Pointer refrescalefilter = FilterType::New(); FilterType::Pointer tarrescalefilter = FilterType::New(); refrescalefilter->SetInput(reffilter->GetOutput()); tarrescalefilter->SetInput(tarfilter->GetOutput()); const double desiredMinimum = 0.0; const double desiredMaximum = 255.0; refrescalefilter->SetOutputMinimum( desiredMinimum ); refrescalefilter->SetOutputMaximum( desiredMaximum ); refrescalefilter->UpdateLargestPossibleRegion(); tarrescalefilter->SetOutputMinimum( desiredMinimum ); tarrescalefilter->SetOutputMaximum( desiredMaximum ); tarrescalefilter->UpdateLargestPossibleRegion(); // Histogram match the images typedef itk::HistogramMatchingImageFilter<ImageType,ImageType> HEFilterType; HEFilterType::Pointer IntensityEqualizeFilter = HEFilterType::New(); IntensityEqualizeFilter->SetReferenceImage( refrescalefilter->GetOutput() ); IntensityEqualizeFilter->SetInput( tarrescalefilter->GetOutput() ); IntensityEqualizeFilter->SetNumberOfHistogramLevels( 100); IntensityEqualizeFilter->SetNumberOfMatchPoints( 15); IntensityEqualizeFilter->ThresholdAtMeanIntensityOn(); IntensityEqualizeFilter->Update(); X->SetFixedImage(refrescalefilter->GetOutput()); X->SetMovingImage(IntensityEqualizeFilter->GetOutput()); // Software Guide : BeginLatex // // In order to initialize the mesh of elements, we must first create // ``dummy'' material and element objects and assign them to the // registration filter. These objects are subsequently used to // either read a predefined mesh from a file or generate a mesh using // the software. The values assigned to the fields within the // material object are arbitrary since they will be replaced with // those specified in the parameter file. Similarly, the element // object will be replaced with those from the desired mesh. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet // Create the material properties itk::fem::MaterialLinearElasticity::Pointer m; m = itk::fem::MaterialLinearElasticity::New(); m->GN = 0; // Global number of the material m->E = X->GetElasticity(); // Young's modulus -- used in the membrane m->A = 1.0; // Cross-sectional area m->h = 1.0; // Thickness m->I = 1.0; // Moment of inertia m->nu = 0.; // Poisson's ratio -- DONT CHOOSE 1.0!! m->RhoC = 1.0; // Density // Create the element type ElementType::Pointer e1=ElementType::New(); e1->m_mat=dynamic_cast<itk::fem::MaterialLinearElasticity*>( m ); X->SetElement(e1); X->SetMaterial(m); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Now we are ready to run the registration: // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet X->RunRegistration(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // To output the image resulting from the registration, we can call // \code{WriteWarpedImage()}. The image is written in floating point // format. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet X->WriteWarpedImage((X->GetResultsFileName()).c_str()); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We can also output the displacement fields resulting from the // registration, we can call \code{WriteDisplacementField()} with the // desired vector component as an argument. For a 2D registration, // you would want to write out both the $x$ and $y$ displacements, and // this requires two calls to the aforementioned function. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet if (X->GetWriteDisplacements()) { X->WriteDisplacementField(0); X->WriteDisplacementField(1); // If this were a 3D example, you might also want to call this line: // X->WriteDisplacementField(2); } // Software Guide : EndCodeSnippet // This is a documented sample parameter file that can be used with // this deformable registration example. // // ../Data/FiniteElementRegistrationParameters1.txt // // Clean up and exit. TODO: THIS IS REALLY BAD. NEEDS TO BE FIXED!!!! // Instantiated as ::Pointer and the delete is used. delete m; delete e1; return 0; } <commit_msg><commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: DeformableRegistration1.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information. =========================================================================*/ #include "itkImageFileReader.h" #include "itkImageFileWriter.h" //#include "itkMetaImageIO.h" #include "itkRescaleIntensityImageFilter.h" #include "itkHistogramMatchingImageFilter.h" // Software Guide : BeginLatex // // The finite element (FEM) library within the Insight Toolkit can be // used to solve deformable image registration problems. The first step in // implementing a FEM-based registration is to include the appropriate // header files. // // \index{Registration!Finite Element-Based} // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet #include "itkFEM.h" #include "itkFEMRegistrationFilter.h" // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Next, we use \code{typedef}s to instantiate all necessary classes. We // define the image and element types we plan to use to solve a // two-dimensional registration problem. We define multiple element // types so that they can be used without recompiling the code. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef itk::Image<unsigned char, 2> fileImageType; typedef itk::Image<float, 2> ImageType; typedef itk::fem::Element2DC0LinearQuadrilateralMembrane ElementType; typedef itk::fem::Element2DC0LinearTriangularMembrane ElementType2; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Note that in order to solve a three-dimensional registration // problem, we would simply define 3D image and element types in lieu // of those above. The following declarations could be used for a 3D // problem: // // SoftwareGuide : EndLatex // SoftwareGuide : BeginCodeSnippet typedef itk::Image<unsigned char, 3> fileImage3DType; typedef itk::Image<float, 3> Image3DType; typedef itk::fem::Element3DC0LinearHexahedronMembrane Element3DType; typedef itk::fem::Element3DC0LinearTetrahedronMembrane Element3DType2; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Here, we instantiate the load types and explicitly template the // load implementation type. We also define visitors that allow the // elements and loads to communicate with one another. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef itk::fem::ImageMetricLoad<ImageType,ImageType> ImageLoadType; template class itk::fem::ImageMetricLoadImplementation<ImageLoadType>; typedef ElementType::LoadImplementationFunctionPointer LoadImpFP; typedef ElementType::LoadType ElementLoadType; typedef ElementType2::LoadImplementationFunctionPointer LoadImpFP2; typedef ElementType2::LoadType ElementLoadType2; typedef itk::fem::VisitorDispatcher<ElementType,ElementLoadType, LoadImpFP> DispatcherType; typedef itk::fem::VisitorDispatcher<ElementType2,ElementLoadType2, LoadImpFP2> DispatcherType2; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Once all the necessary components have been instantianted, we can // instantiate the \doxygen{FEMRegistrationFilter}, which depends on the // image input and output types. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef itk::fem::FEMRegistrationFilter<ImageType,ImageType> RegistrationType; // Software Guide : EndCodeSnippet int main(int argc, char *argv[]) { char *paramname; if ( argc < 2 ) { std::cout << "Parameter file name missing" << std::endl; std::cout << "Usage: " << argv[0] << " param.file" << std::endl; return -1; } else { paramname=argv[1]; } // Software Guide : BeginLatex // // The \doxygen{FEMImageMetricLoad} must be registered before it // can be used correctly with a particular element type. An example // of this is shown below for \code{ElementType}. Similar // definitions are required for all other defined element types. // // Software Guide : EndLatex // Register the correct load implementation with the element-typed visitor dispatcher. { // Software Guide : BeginCodeSnippet ElementType::LoadImplementationFunctionPointer fp = &itk::fem::ImageMetricLoadImplementation<ImageLoadType>::ImplementImageMetricLoad; DispatcherType::RegisterVisitor((ImageLoadType*)0,fp); // Software Guide : EndCodeSnippet } { ElementType2::LoadImplementationFunctionPointer fp = &itk::fem::ImageMetricLoadImplementation<ImageLoadType>::ImplementImageMetricLoad; DispatcherType2::RegisterVisitor((ImageLoadType*)0,fp); } // Software Guide : BeginLatex // // In order to begin the registration, we declare an instance of the // FEMRegistrationFilter. For simplicity, we will call // it \code{X}. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet RegistrationType::Pointer X = RegistrationType::New(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Next, we call \code{X->SetConfigFileName()} to read the parameter // file containing information we need to set up the registration // filter. A sample parameter file is shown at the end of this // section, and the individual components are labeled. // // Software Guide : EndLatex // Attempt to read the parameter file, and exit if an error occurs X->SetConfigFileName(paramname); if ( !X->ReadConfigFile( (X->GetConfigFileName()).c_str() ) ) { return -1; } // Read the image files typedef itk::ImageFileReader< fileImageType > FileSourceType; typedef fileImageType::PixelType PixType; FileSourceType::Pointer reffilter = FileSourceType::New(); reffilter->SetFileName( (X->GetMovingFile()).c_str() ); FileSourceType::Pointer tarfilter = FileSourceType::New(); tarfilter->SetFileName( (X->GetFixedFile()).c_str() ); try { reffilter->Update(); } catch( itk::ExceptionObject & e ) { std::cerr << "Exception caught during reference file reading " << std::endl; std::cerr << e << std::endl; return -1; } try { tarfilter->Update(); } catch( itk::ExceptionObject & e ) { std::cerr << "Exception caught during target file reading " << std::endl; std::cerr << e << std::endl; return -1; } // Rescale the image intensities so that they fall between 0 and 255 typedef itk::RescaleIntensityImageFilter<fileImageType,ImageType> FilterType; FilterType::Pointer refrescalefilter = FilterType::New(); FilterType::Pointer tarrescalefilter = FilterType::New(); refrescalefilter->SetInput(reffilter->GetOutput()); tarrescalefilter->SetInput(tarfilter->GetOutput()); const double desiredMinimum = 0.0; const double desiredMaximum = 255.0; refrescalefilter->SetOutputMinimum( desiredMinimum ); refrescalefilter->SetOutputMaximum( desiredMaximum ); refrescalefilter->UpdateLargestPossibleRegion(); tarrescalefilter->SetOutputMinimum( desiredMinimum ); tarrescalefilter->SetOutputMaximum( desiredMaximum ); tarrescalefilter->UpdateLargestPossibleRegion(); // Histogram match the images typedef itk::HistogramMatchingImageFilter<ImageType,ImageType> HEFilterType; HEFilterType::Pointer IntensityEqualizeFilter = HEFilterType::New(); IntensityEqualizeFilter->SetReferenceImage( refrescalefilter->GetOutput() ); IntensityEqualizeFilter->SetInput( tarrescalefilter->GetOutput() ); IntensityEqualizeFilter->SetNumberOfHistogramLevels( 100); IntensityEqualizeFilter->SetNumberOfMatchPoints( 15); IntensityEqualizeFilter->ThresholdAtMeanIntensityOn(); IntensityEqualizeFilter->Update(); X->SetFixedImage(refrescalefilter->GetOutput()); X->SetMovingImage(IntensityEqualizeFilter->GetOutput()); // Software Guide : BeginLatex // // In order to initialize the mesh of elements, we must first create // ``dummy'' material and element objects and assign them to the // registration filter. These objects are subsequently used to // either read a predefined mesh from a file or generate a mesh using // the software. The values assigned to the fields within the // material object are arbitrary since they will be replaced with // those specified in the parameter file. Similarly, the element // object will be replaced with those from the desired mesh. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet // Create the material properties itk::fem::MaterialLinearElasticity::Pointer m; m = itk::fem::MaterialLinearElasticity::New(); m->GN = 0; // Global number of the material m->E = X->GetElasticity(); // Young's modulus -- used in the membrane m->A = 1.0; // Cross-sectional area m->h = 1.0; // Thickness m->I = 1.0; // Moment of inertia m->nu = 0.; // Poisson's ratio -- DONT CHOOSE 1.0!! m->RhoC = 1.0; // Density // Create the element type ElementType::Pointer e1=ElementType::New(); e1->m_mat=dynamic_cast<itk::fem::MaterialLinearElasticity*>( m ); X->SetElement(e1); X->SetMaterial(m); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Now we are ready to run the registration: // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet X->RunRegistration(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // To output the image resulting from the registration, we can call // \code{WriteWarpedImage()}. The image is written in floating point // format. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet X->WriteWarpedImage((X->GetResultsFileName()).c_str()); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We can also output the displacement fields resulting from the // registration, we can call \code{WriteDisplacementField()} with the // desired vector component as an argument. For a 2D registration, // you would want to write out both the $x$ and $y$ displacements, and // this requires two calls to the aforementioned function. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet if (X->GetWriteDisplacements()) { X->WriteDisplacementField(0); X->WriteDisplacementField(1); // If this were a 3D example, you might also want to call this line: // X->WriteDisplacementField(2); } // Software Guide : EndCodeSnippet // This is a documented sample parameter file that can be used with // this deformable registration example. // // ../Data/FiniteElementRegistrationParameters1.txt // return 0; } <|endoftext|>
<commit_before>/* The MIT License (MIT) Copyright (c) 2015 Martin Richter 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. */ #ifndef TWPP_DETAIL_FILE_TYPES_HPP #define TWPP_DETAIL_FILE_TYPES_HPP #include "../twpp.hpp" namespace Twpp { TWPP_DETAIL_PACK_BEGIN typedef std::uintptr_t UIntPtr; typedef std::uint8_t UInt8; typedef std::uint16_t UInt16; typedef std::uint32_t UInt32; typedef std::int8_t Int8; typedef std::int16_t Int16; typedef std::int32_t Int32; /// Boolean value. /// Implemented as a class to provide better type safety. class Bool { public: constexpr Bool(bool value = false) noexcept : m_value(value){} constexpr operator bool() const noexcept{ return m_value != 0; } private: Int16 m_value; }; /// Handle to memory area. /// Implemented as a class to provide better type safety. class Handle { public: typedef Detail::RawHandle Raw; constexpr explicit Handle(Raw raw = Raw()) noexcept : m_raw(raw){} /// Underlying OS-dependent handle. constexpr Raw raw() const noexcept{ return m_raw; } constexpr operator bool() const noexcept{ return m_raw != Raw(); } private: Raw m_raw; }; TWPP_DETAIL_PACK_END } #endif // TWPP_DETAIL_FILE_TYPES_HPP <commit_msg>Fix Handle equality operator.<commit_after>/* The MIT License (MIT) Copyright (c) 2015, 2019 Martin Richter 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. */ #ifndef TWPP_DETAIL_FILE_TYPES_HPP #define TWPP_DETAIL_FILE_TYPES_HPP #include "../twpp.hpp" namespace Twpp { TWPP_DETAIL_PACK_BEGIN typedef std::uintptr_t UIntPtr; typedef std::uint8_t UInt8; typedef std::uint16_t UInt16; typedef std::uint32_t UInt32; typedef std::int8_t Int8; typedef std::int16_t Int16; typedef std::int32_t Int32; /// Boolean value. /// Implemented as a class to provide better type safety. class Bool { public: constexpr Bool(bool value = false) noexcept : m_value(value){} constexpr operator bool() const noexcept{ return m_value != 0; } private: Int16 m_value; }; /// Handle to memory area. /// Implemented as a class to provide better type safety. class Handle { public: typedef Detail::RawHandle Raw; constexpr explicit Handle(Raw raw = Raw()) noexcept : m_raw(raw){} /// Underlying OS-dependent handle. constexpr Raw raw() const noexcept{ return m_raw; } constexpr operator bool() const noexcept{ return m_raw != Raw(); } private: Raw m_raw; }; TWPP_DETAIL_PACK_END static inline constexpr bool operator==(Handle a, Handle b) noexcept{ return a.raw() == b.raw(); } static inline constexpr bool operator!=(Handle a, Handle b) noexcept{ return !(a == b); } } #endif // TWPP_DETAIL_FILE_TYPES_HPP <|endoftext|>
<commit_before>#ifndef UNIT_CONFIG_HPP_ #define UNIT_CONFIG_HPP_ namespace unit_config { const float DT = 0.001; // Maximum angular position in the roll and pitch axes (deg) const float MAX_PITCH_ROLL_POS = 30.0; // Maximum angular velocity in the roll and pitch axes (deg/s) const float MAX_PITCH_ROLL_VEL = 100.0; // Sensor offsets const float GYR_X_OFFSET = 0.05; const float GYR_Y_OFFSET = -0.05; const float GYR_Z_OFFSET = -0.01; const float ACC_X_OFFSET = 0.0; const float ACC_Y_OFFSET = 0.0; const float ACC_Z_OFFSET = 0.0; // Initial angular velocity controller gains const float ANGVEL_X_KP = 0.2; const float ANGVEL_X_KI = 0.0; const float ANGVEL_X_KD = 0.0; const float ANGVEL_Y_KP = 0.2; const float ANGVEL_Y_KI = 0.0; const float ANGVEL_Y_KD = 0.0; const float ANGVEL_Z_KP = 0.0; const float ANGVEL_Z_KI = 0.0; const float ANGVEL_Z_KD = 0.0; // Initial angular position controller gains const float ANGPOS_X_KP = 1.0; const float ANGPOS_X_KI = 0.0; const float ANGPOS_X_KD = 0.0; const float ANGPOS_Y_KP = 1.0; const float ANGPOS_Y_KI = 0.0; const float ANGPOS_Y_KD = 0.0; const float ANGPOS_Z_KP = 0.0; const float ANGPOS_Z_KI = 0.0; const float ANGPOS_Z_KD = 0.0; } #endif // UNIT_CONFIG_HPP_ <commit_msg>Calibrate apollo gyro.<commit_after>#ifndef UNIT_CONFIG_HPP_ #define UNIT_CONFIG_HPP_ namespace unit_config { const float DT = 0.001; // Maximum angular position in the roll and pitch axes (deg) const float MAX_PITCH_ROLL_POS = 30.0; // Maximum angular velocity in the roll and pitch axes (deg/s) const float MAX_PITCH_ROLL_VEL = 100.0; // Sensor offsets const float GYR_X_OFFSET = 0.0043; const float GYR_Y_OFFSET = 0.016; const float GYR_Z_OFFSET = 0.0073; const float ACC_X_OFFSET = 0.0; const float ACC_Y_OFFSET = 0.0; const float ACC_Z_OFFSET = 0.0; // Initial angular velocity controller gains const float ANGVEL_X_KP = 0.2; const float ANGVEL_X_KI = 0.0; const float ANGVEL_X_KD = 0.0; const float ANGVEL_Y_KP = 0.2; const float ANGVEL_Y_KI = 0.0; const float ANGVEL_Y_KD = 0.0; const float ANGVEL_Z_KP = 0.0; const float ANGVEL_Z_KI = 0.0; const float ANGVEL_Z_KD = 0.0; // Initial angular position controller gains const float ANGPOS_X_KP = 1.0; const float ANGPOS_X_KI = 0.0; const float ANGPOS_X_KD = 0.0; const float ANGPOS_Y_KP = 1.0; const float ANGPOS_Y_KI = 0.0; const float ANGPOS_Y_KD = 0.0; const float ANGPOS_Z_KP = 0.0; const float ANGPOS_Z_KI = 0.0; const float ANGPOS_Z_KD = 0.0; } #endif // UNIT_CONFIG_HPP_ <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkGenericInterpolatedVelocityField.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 "vtkGenericInterpolatedVelocityField.h" #include "vtkGenericAttributeCollection.h" #include "vtkGenericAttribute.h" #include "vtkGenericDataSet.h" #include "vtkGenericCellIterator.h" #include "vtkGenericAdaptorCell.h" #include "vtkObjectFactory.h" #include "vtkDataSetAttributes.h" // for vtkDataSetAttributes::VECTORS #include <vtkstd/vector> vtkCxxRevisionMacro(vtkGenericInterpolatedVelocityField, "1.1"); vtkStandardNewMacro(vtkGenericInterpolatedVelocityField); typedef vtkstd::vector< vtkGenericDataSet* > DataSetsTypeBase; class vtkGenericInterpolatedVelocityFieldDataSetsType: public DataSetsTypeBase {}; vtkGenericInterpolatedVelocityField::vtkGenericInterpolatedVelocityField() { this->NumFuncs = 3; // u, v, w this->NumIndepVars = 4; // x, y, z, t this->GenCell = 0; this->CacheHit = 0; this->CacheMiss = 0; this->Caching = 1; // Caching on by default this->VectorsSelection = 0; this->DataSets = new vtkGenericInterpolatedVelocityFieldDataSetsType; this->LastDataSet = 0; } vtkGenericInterpolatedVelocityField::~vtkGenericInterpolatedVelocityField() { this->NumFuncs = 0; this->NumIndepVars = 0; if(this->GenCell!=0) { this->GenCell->Delete(); } this->SetVectorsSelection(0); delete this->DataSets; } static int tmp_count=0; // Evaluate u,v,w at x,y,z,t int vtkGenericInterpolatedVelocityField::FunctionValues(double* x, double* f) { vtkGenericDataSet* ds; if(!this->LastDataSet && !this->DataSets->empty()) { ds = (*this->DataSets)[0]; this->LastDataSet = ds; } else { ds = this->LastDataSet; } int retVal = this->FunctionValues(ds, x, f); if (!retVal) { tmp_count = 0; for(DataSetsTypeBase::iterator i = this->DataSets->begin(); i != this->DataSets->end(); ++i) { ds = *i; if(ds && ds != this->LastDataSet) { this->ClearLastCell(); retVal = this->FunctionValues(ds, x, f); if (retVal) { this->LastDataSet = ds; return retVal; } } } this->ClearLastCell(); return 0; } tmp_count++; return retVal; } const double vtkGenericInterpolatedVelocityField::TOLERANCE_SCALE = 1.0E-8; // Evaluate u,v,w at x,y,z,t int vtkGenericInterpolatedVelocityField::FunctionValues( vtkGenericDataSet* dataset, double* x, double* f) { int i, subId; vtkGenericAttribute *vectors; double dist2; int ret; int attrib; for(i=0; i<3; i++) { f[i] = 0; } // See if a dataset has been specified and if there are input vectors int validState=dataset!=0; if(validState) { if(this->VectorsSelection!=0) { attrib=dataset->GetAttributes()->FindAttribute(this->VectorsSelection); validState=attrib>=0; if(validState) { vectors=dataset->GetAttributes()->GetAttribute(attrib); validState=(vectors->GetType()==vtkDataSetAttributes::VECTORS)||(vectors->GetCentering()==vtkPointCentered); } } else { // Find the first attribute, point centered and with vector type. attrib=0; validState=0; int c=dataset->GetAttributes()->GetNumberOfAttributes(); while(attrib<c&&!validState) { validState=(dataset->GetAttributes()->GetAttribute(attrib)->GetType()==vtkDataSetAttributes::VECTORS)&&(dataset->GetAttributes()->GetAttribute(attrib)->GetCentering()==vtkPointCentered); ++attrib; } if(validState) { vectors=dataset->GetAttributes()->GetAttribute(attrib-1); } } } if (!validState) { vtkErrorMacro(<<"Can't evaluate dataset!"); return 0; } double tol2 = dataset->GetLength() * vtkGenericInterpolatedVelocityField::TOLERANCE_SCALE; int found = 0; if (this->Caching) { // See if the point is in the cached cell if (this->GenCell==0 || this->GenCell->IsAtEnd() || !(ret=this->GenCell->GetCell()->EvaluatePosition(x, 0, subId, this->LastPCoords, dist2)) || ret == -1) { // if not, find and get it if (this->GenCell!=0 && !this->GenCell->IsAtEnd()) { this->CacheMiss++; found=dataset->FindCell(x,this->GenCell,tol2,subId, this->LastPCoords); } } else { this->CacheHit++; found = 1; } } if (!found) { // if the cell is not found, do a global search (ignore initial // cell if there is one) if(this->GenCell==0) { this->GenCell=dataset->NewCellIterator(); } found=dataset->FindCell(x,this->GenCell,tol2,subId,this->LastPCoords); if(!found) { return 0; } } this->GenCell->GetCell()->InterpolateTuple(vectors,this->LastPCoords,f); return 1; } //----------------------------------------------------------------------------- void vtkGenericInterpolatedVelocityField::AddDataSet(vtkGenericDataSet* dataset) { if (!dataset) { return; } this->DataSets->push_back(dataset); } //----------------------------------------------------------------------------- // Description: // Set the last cell id to -1 so that the next search does not // start from the previous cell void vtkGenericInterpolatedVelocityField::ClearLastCell() { if(this->GenCell!=0) { if(!this->GenCell->IsAtEnd()) { this->GenCell->Next(); } } } //----------------------------------------------------------------------------- // Description: // Return the cell cached from last evaluation. vtkGenericAdaptorCell *vtkGenericInterpolatedVelocityField::GetLastCell() { vtkGenericAdaptorCell *result; if(this->GenCell!=0 && !this->GenCell->IsAtEnd()) { result=this->GenCell->GetCell(); } else { result=0; } return result; } //----------------------------------------------------------------------------- int vtkGenericInterpolatedVelocityField::GetLastLocalCoordinates(double pcoords[3]) { int j; // If last cell is valid, fill p with the local coordinates // and return true if (this->GenCell!=0 && !this->GenCell->IsAtEnd()) { for (j=0; j < 3; j++) { pcoords[j] = this->LastPCoords[j]; } return 1; } // otherwise, return false else { return 0; } } void vtkGenericInterpolatedVelocityField::CopyParameters( vtkGenericInterpolatedVelocityField* from) { this->Caching = from->Caching; } void vtkGenericInterpolatedVelocityField::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); if ( this->VectorsSelection ) { os << indent << "VectorsSelection: " << this->VectorsSelection << endl; } else { os << indent << "VectorsSelection: (none)" << endl; } if ( this->GenCell ) { os << indent << "Last cell: " << this->GenCell << endl; } else { os << indent << "Last cell: (none)" << endl; } os << indent << "Cache hit: " << this->CacheHit << endl; os << indent << "Cache miss: " << this->CacheMiss << endl; os << indent << "Caching: "; if ( this->Caching ) { os << "on." << endl; } else { os << "off." << endl; } os << indent << "VectorsSelection: " << (this->VectorsSelection?this->VectorsSelection:"(none)") << endl; os << indent << "LastDataSet : " << this->LastDataSet << endl; } <commit_msg>Fixed VC6 warning<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkGenericInterpolatedVelocityField.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 "vtkGenericInterpolatedVelocityField.h" #include "vtkGenericAttributeCollection.h" #include "vtkGenericAttribute.h" #include "vtkGenericDataSet.h" #include "vtkGenericCellIterator.h" #include "vtkGenericAdaptorCell.h" #include "vtkObjectFactory.h" #include "vtkDataSetAttributes.h" // for vtkDataSetAttributes::VECTORS #include <vtkstd/vector> vtkCxxRevisionMacro(vtkGenericInterpolatedVelocityField, "1.2"); vtkStandardNewMacro(vtkGenericInterpolatedVelocityField); typedef vtkstd::vector< vtkGenericDataSet* > DataSetsTypeBase; class vtkGenericInterpolatedVelocityFieldDataSetsType: public DataSetsTypeBase {}; vtkGenericInterpolatedVelocityField::vtkGenericInterpolatedVelocityField() { this->NumFuncs = 3; // u, v, w this->NumIndepVars = 4; // x, y, z, t this->GenCell = 0; this->CacheHit = 0; this->CacheMiss = 0; this->Caching = 1; // Caching on by default this->VectorsSelection = 0; this->DataSets = new vtkGenericInterpolatedVelocityFieldDataSetsType; this->LastDataSet = 0; } vtkGenericInterpolatedVelocityField::~vtkGenericInterpolatedVelocityField() { this->NumFuncs = 0; this->NumIndepVars = 0; if(this->GenCell!=0) { this->GenCell->Delete(); } this->SetVectorsSelection(0); delete this->DataSets; } static int tmp_count=0; // Evaluate u,v,w at x,y,z,t int vtkGenericInterpolatedVelocityField::FunctionValues(double* x, double* f) { vtkGenericDataSet* ds; if(!this->LastDataSet && !this->DataSets->empty()) { ds = (*this->DataSets)[0]; this->LastDataSet = ds; } else { ds = this->LastDataSet; } int retVal = this->FunctionValues(ds, x, f); if (!retVal) { tmp_count = 0; for(DataSetsTypeBase::iterator i = this->DataSets->begin(); i != this->DataSets->end(); ++i) { ds = *i; if(ds && ds != this->LastDataSet) { this->ClearLastCell(); retVal = this->FunctionValues(ds, x, f); if (retVal) { this->LastDataSet = ds; return retVal; } } } this->ClearLastCell(); return 0; } tmp_count++; return retVal; } const double vtkGenericInterpolatedVelocityField::TOLERANCE_SCALE = 1.0E-8; // Evaluate u,v,w at x,y,z,t int vtkGenericInterpolatedVelocityField::FunctionValues( vtkGenericDataSet* dataset, double* x, double* f) { int i, subId; vtkGenericAttribute *vectors=0; double dist2; int ret; int attrib; for(i=0; i<3; i++) { f[i] = 0; } // See if a dataset has been specified and if there are input vectors int validState=dataset!=0; if(validState) { if(this->VectorsSelection!=0) { attrib=dataset->GetAttributes()->FindAttribute(this->VectorsSelection); validState=attrib>=0; if(validState) { vectors=dataset->GetAttributes()->GetAttribute(attrib); validState=(vectors->GetType()==vtkDataSetAttributes::VECTORS)||(vectors->GetCentering()==vtkPointCentered); } } else { // Find the first attribute, point centered and with vector type. attrib=0; validState=0; int c=dataset->GetAttributes()->GetNumberOfAttributes(); while(attrib<c&&!validState) { validState=(dataset->GetAttributes()->GetAttribute(attrib)->GetType()==vtkDataSetAttributes::VECTORS)&&(dataset->GetAttributes()->GetAttribute(attrib)->GetCentering()==vtkPointCentered); ++attrib; } if(validState) { vectors=dataset->GetAttributes()->GetAttribute(attrib-1); } } } if (!validState) { vtkErrorMacro(<<"Can't evaluate dataset!"); return 0; } double tol2 = dataset->GetLength() * vtkGenericInterpolatedVelocityField::TOLERANCE_SCALE; int found = 0; if (this->Caching) { // See if the point is in the cached cell if (this->GenCell==0 || this->GenCell->IsAtEnd() || !(ret=this->GenCell->GetCell()->EvaluatePosition(x, 0, subId, this->LastPCoords, dist2)) || ret == -1) { // if not, find and get it if (this->GenCell!=0 && !this->GenCell->IsAtEnd()) { this->CacheMiss++; found=dataset->FindCell(x,this->GenCell,tol2,subId, this->LastPCoords); } } else { this->CacheHit++; found = 1; } } if (!found) { // if the cell is not found, do a global search (ignore initial // cell if there is one) if(this->GenCell==0) { this->GenCell=dataset->NewCellIterator(); } found=dataset->FindCell(x,this->GenCell,tol2,subId,this->LastPCoords); if(!found) { return 0; } } this->GenCell->GetCell()->InterpolateTuple(vectors,this->LastPCoords,f); return 1; } //----------------------------------------------------------------------------- void vtkGenericInterpolatedVelocityField::AddDataSet(vtkGenericDataSet* dataset) { if (!dataset) { return; } this->DataSets->push_back(dataset); } //----------------------------------------------------------------------------- // Description: // Set the last cell id to -1 so that the next search does not // start from the previous cell void vtkGenericInterpolatedVelocityField::ClearLastCell() { if(this->GenCell!=0) { if(!this->GenCell->IsAtEnd()) { this->GenCell->Next(); } } } //----------------------------------------------------------------------------- // Description: // Return the cell cached from last evaluation. vtkGenericAdaptorCell *vtkGenericInterpolatedVelocityField::GetLastCell() { vtkGenericAdaptorCell *result; if(this->GenCell!=0 && !this->GenCell->IsAtEnd()) { result=this->GenCell->GetCell(); } else { result=0; } return result; } //----------------------------------------------------------------------------- int vtkGenericInterpolatedVelocityField::GetLastLocalCoordinates(double pcoords[3]) { int j; // If last cell is valid, fill p with the local coordinates // and return true if (this->GenCell!=0 && !this->GenCell->IsAtEnd()) { for (j=0; j < 3; j++) { pcoords[j] = this->LastPCoords[j]; } return 1; } // otherwise, return false else { return 0; } } void vtkGenericInterpolatedVelocityField::CopyParameters( vtkGenericInterpolatedVelocityField* from) { this->Caching = from->Caching; } void vtkGenericInterpolatedVelocityField::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); if ( this->VectorsSelection ) { os << indent << "VectorsSelection: " << this->VectorsSelection << endl; } else { os << indent << "VectorsSelection: (none)" << endl; } if ( this->GenCell ) { os << indent << "Last cell: " << this->GenCell << endl; } else { os << indent << "Last cell: (none)" << endl; } os << indent << "Cache hit: " << this->CacheHit << endl; os << indent << "Cache miss: " << this->CacheMiss << endl; os << indent << "Caching: "; if ( this->Caching ) { os << "on." << endl; } else { os << "off." << endl; } os << indent << "VectorsSelection: " << (this->VectorsSelection?this->VectorsSelection:"(none)") << endl; os << indent << "LastDataSet : " << this->LastDataSet << endl; } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// // FILE: narrayiterator.hpp // DATE: 2014-07-30 // AUTH: Trevor Wilson <kmdreko@gmail.com> // DESC: Defines an N-dimensional templated matrix iterator class //////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2019 Trevor Wilson // // 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. #ifndef WILT_NARRAYITERATOR_HPP #define WILT_NARRAYITERATOR_HPP #include <cstddef> #include <iterator> #include <type_traits> #include "util.hpp" #include "point.hpp" namespace wilt { // - defined in "narray.hpp" template <class T, std::size_t N> class NArray; namespace detail { // - defined below template <std::size_t N> void addValueToPosition(Point<N>& pos, const pos_t* sizes, pos_t value); template <std::size_t N> void addOneToPosition(Point<N>& pos, const pos_t* sizes); template <std::size_t N> void subValueFromPosition(Point<N>& pos, const pos_t* sizes, pos_t value); template <std::size_t N> void subOneFromPosition(Point<N>& pos, const pos_t* sizes); } // namespace detail //! @class NArrayIterator //! //! The iterator class retains its own reference to the array data, meaning //! the NArray it is constructed from may be deleted and the iterator will //! still iterate over the data template <class T, std::size_t N, std::size_t M> class NArrayIterator { public: //////////////////////////////////////////////////////////////////////////// // ASSERTS //////////////////////////////////////////////////////////////////////////// static_assert(N > 0, "source size must be greater than 0"); static_assert(M < N, "result size must be less than source size"); public: //////////////////////////////////////////////////////////////////////////// // TYPE DEFINITIONS //////////////////////////////////////////////////////////////////////////// using iterator_category = std::random_access_iterator_tag; using value_type = typename NArray<T, M>::exposed_type; using difference_type = std::ptrdiff_t; using pointer = std::remove_reference<value_type>*; using reference = value_type; private: //////////////////////////////////////////////////////////////////////////// // PRIVATE MEMBERS //////////////////////////////////////////////////////////////////////////// const wilt::NArray<T, N>* array_; Point<N-M> position_; public: //////////////////////////////////////////////////////////////////////////// // CONSTRUCTORS //////////////////////////////////////////////////////////////////////////// //! @brief Default constructor. Useless NArrayIterator() : array_(nullptr), position_() { } NArrayIterator(const wilt::NArray<T, N>& arr) : array_(&arr), position_() { } //! @brief NArray constructor from an array and offset //! @param[in] arr - array whose data to reference //! @param[in] pos - data offset value, defaults to 0 NArrayIterator(const wilt::NArray<T, N>& arr, const Point<N-M>& pos) : array_(&arr), position_(pos) { } //! @brief Copy constructor //! @param[in] iter - iterator to copy from NArrayIterator(const NArrayIterator<T, N, M>& iter) : array_(iter.array_), position_(iter.position_) { } //! @brief Copy constructor with offset //! @param[in] iter - iterator to copy from //! @param[in] pos - data offset value NArrayIterator(const NArrayIterator<T, N, M>& iter, const Point<N-M>& pos) : array_(iter.array_), position_(pos) { } public: //////////////////////////////////////////////////////////////////////////// // ASSIGNMENT OPERATORS //////////////////////////////////////////////////////////////////////////// //! @brief assignment operator //! @param[in] iter - iterator to copy from //! @return reference to this object NArrayIterator<T, N, M>& operator= (const NArrayIterator<T, N, M>& iter) { array_ = iter.array_; position_ = iter.position_; return *this; } //! @brief in-place addition operator, offsets data by +pos //! @param[in] pos - value to offset //! @return reference to this object NArrayIterator<T, N, M>& operator+= (const ptrdiff_t pos) { wilt::detail::addValueToPosition(position_, array_->sizes().data(), pos); return *this; } //! @brief in-place addition operator, offsets data by -pos //! @param[in] pos - value to offset //! @return reference to this object NArrayIterator<T, N, M>& operator-= (const ptrdiff_t pos) { wilt::detail::subValueFromPosition(position_, array_->sizes().data(), pos); return *this; } public: //////////////////////////////////////////////////////////////////////////// // ACCESS FUNCTIONS //////////////////////////////////////////////////////////////////////////// //! @brief de-reference operator, invalid if <begin or >=end //! @return reference to data at the iterator position value_type operator* () const { return at_(position_); } //! @brief index operator //! @param[in] pos - data offset value //! @return reference to data at the iterator position + offset value_type operator[] (pos_t pos) const { auto newposition = position_; wilt::detail::addValueToPosition(newposition, array_->sizes().data(), pos); return at_(newposition); } //! @brief gets the position of the iterator //! @return point corresponding to the position in the NArray currently //! pointing to Point<N-M> position() const { return position_; } public: //////////////////////////////////////////////////////////////////////////// // COMPARISON FUNCTIONS //////////////////////////////////////////////////////////////////////////// //! @brief equal operator, determines both if it references the same //! NArray data and if at same position //! @param[in] iter - iterator to compare //! @return true if iterators are the same, false otherwise bool operator== (const NArrayIterator<T, N, M>& iter) const { assert(array_ == iter.array_); return position_ == iter.position_; } //! @brief not equal operator, determines both if it references the //! same NArray data and if at same position //! @param[in] iter - iterator to compare //! @return false if iterators are the same, true otherwise bool operator!= (const NArrayIterator<T, N, M>& iter) const { assert(array_ == iter.array_); return !(*this == iter); } //! @brief less than operator, is only calculated from data offset, //! does not determine if they share a data-space //! @param[in] iter - iterator to compare //! @return true if data offset is less than that of iter bool operator< (const NArrayIterator<T, N, M>& iter) const { assert(array_ == iter.array_); // simple lexigraphical comparison for (std::size_t i = 0; i < N-M; ++i) { if (position_[i] < iter.position_[i]) return true; if (position_[i] > iter.position_[i]) return false; } return false; } //! @brief greater than operator, is only calculated from data offset, //! does not determine if they share a data-space //! @param[in] iter - iterator to compare //! @return true if data offset is greater than that of iter bool operator> (const NArrayIterator<T, N, M>& iter) const { assert(array_ == iter.array_); return iter < *this; } //! @brief less than or equal operator, is only calculated from data //! offset, does not determine if they share a data-space //! @param[in] iter - iterator to compare //! @return true if data offset is less than or equal to that of iter bool operator<= (const NArrayIterator<T, N, M>& iter) const { assert(array_ == iter.array_); return !(iter < *this); } //! @brief greater than or equal operator, is only calculated from data //! offset, does not determine if they share a data-space //! @param[in] iter - iterator to compare //! @return true if data offset is greater than or equal to that of iter bool operator>= (const NArrayIterator<T, N, M>& iter) const { assert(array_ == iter.array_); return !(*this < iter); } public: //////////////////////////////////////////////////////////////////////////// // MODIFIER FUNCTIONS //////////////////////////////////////////////////////////////////////////// //! @brief increments the data offset value //! @return reference to this object NArrayIterator<T, N, M>& operator++ () { wilt::detail::addOneToPosition(position_, array_->sizes().data()); return *this; } //! @brief decrements the data offset value //! @return reference to this object NArrayIterator<T, N, M>& operator-- () { wilt::detail::subOneFromPosition(position_, array_->sizes().data()); return *this; } //! @brief increments the data offset value //! @return copy of this object before incrementing NArrayIterator<T, N, M> operator++ (int) { auto oldposition = position_; ++(*this); return NArrayIterator<T, N, M>(*this, oldposition); } //! @brief decrements the data offset value //! @return copy of this object before decrementing NArrayIterator<T, N, M> operator-- (int) { auto oldposition = position_; --(*this); return NArrayIterator<T, N, M>(*this, oldposition); } //! @brief the difference of two iterators //! @param[in] iter - the iterator to diff //! @return the difference of the two data offset values difference_type operator- (const NArrayIterator<T, N, M>& iter) const { assert(array_ == iter.array_); pos_t diff = 0; for (std::size_t i = 0; i < N-M; ++i) { diff *= array_->sizes()[i]; diff += (position_[i] - iter.position_[i]); } return diff; } //! @brief addition operator //! @param[in] pos - the offset to add //! @return this iterator plus the offset NArrayIterator<T, N, M> operator+ (const ptrdiff_t pos) { auto newiter = *this; newiter += pos; return newiter; } //! @brief subtraction operator //! @param[in] pos - the offset to subtract //! @return this iterator minus the offset NArrayIterator<T, N, M> operator- (const ptrdiff_t pos) { auto newiter = *this; newiter -= pos; return newiter; } private: //////////////////////////////////////////////////////////////////////////// // PRIVATE FUNCTIONS //////////////////////////////////////////////////////////////////////////// //! @brief gets the pointer at the data offset //! @param[in] pos - data offset value //! @return pointer to data at the offset value_type at_(const Point<N-M>& pos) const { return array_->subarrayAtUnchecked(pos); } }; // class NArrayIterator namespace detail { template <std::size_t N> void addValueToPosition(Point<N>& pos, const pos_t* sizes, pos_t value) { for (std::size_t i = N-1; i > 0; --i) { pos[i] += value; if (pos[i] < sizes[i]) return; value = pos[i] / sizes[i]; pos[i] = pos[i] % sizes[i]; } pos[0] += value; } template <std::size_t N> void addOneToPosition(Point<N>& pos, const pos_t* sizes) { for (std::size_t i = N-1; i > 0; --i) { pos[i] += 1; if (pos[i] < sizes[i]) return; pos[i] = 0; } pos[0] += 1; } template <std::size_t N> void subValueFromPosition(Point<N>& pos, const pos_t* sizes, pos_t value) { for (std::size_t i = N-1; i > 0; --i) { pos[i] -= value; if (pos[i] >= 0) return; value = -(pos[i] / sizes[i]); pos[i] = (pos[i] % sizes[i]) + sizes[i]; } pos[0] -= value; } template <std::size_t N> void subOneFromPosition(Point<N>& pos, const pos_t* sizes) { for (std::size_t i = N-1; i > 0; --i) { pos[i] -= 1; if (pos[i] >= 0) return; pos[i] = sizes[i]-1; } pos[0] -= 1; } } // namespace detail } // namespace wilt #endif // !WILT_NARRAYITERATOR_HPP <commit_msg>fix missing include<commit_after>//////////////////////////////////////////////////////////////////////////////// // FILE: narrayiterator.hpp // DATE: 2014-07-30 // AUTH: Trevor Wilson <kmdreko@gmail.com> // DESC: Defines an N-dimensional templated matrix iterator class //////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2019 Trevor Wilson // // 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. #ifndef WILT_NARRAYITERATOR_HPP #define WILT_NARRAYITERATOR_HPP #include <cassert> #include <cstddef> #include <iterator> #include <type_traits> #include "util.hpp" #include "point.hpp" namespace wilt { // - defined in "narray.hpp" template <class T, std::size_t N> class NArray; namespace detail { // - defined below template <std::size_t N> void addValueToPosition(Point<N>& pos, const pos_t* sizes, pos_t value); template <std::size_t N> void addOneToPosition(Point<N>& pos, const pos_t* sizes); template <std::size_t N> void subValueFromPosition(Point<N>& pos, const pos_t* sizes, pos_t value); template <std::size_t N> void subOneFromPosition(Point<N>& pos, const pos_t* sizes); } // namespace detail //! @class NArrayIterator //! //! The iterator class retains its own reference to the array data, meaning //! the NArray it is constructed from may be deleted and the iterator will //! still iterate over the data template <class T, std::size_t N, std::size_t M> class NArrayIterator { public: //////////////////////////////////////////////////////////////////////////// // ASSERTS //////////////////////////////////////////////////////////////////////////// static_assert(N > 0, "source size must be greater than 0"); static_assert(M < N, "result size must be less than source size"); public: //////////////////////////////////////////////////////////////////////////// // TYPE DEFINITIONS //////////////////////////////////////////////////////////////////////////// using iterator_category = std::random_access_iterator_tag; using value_type = typename NArray<T, M>::exposed_type; using difference_type = std::ptrdiff_t; using pointer = std::remove_reference<value_type>*; using reference = value_type; private: //////////////////////////////////////////////////////////////////////////// // PRIVATE MEMBERS //////////////////////////////////////////////////////////////////////////// const wilt::NArray<T, N>* array_; Point<N-M> position_; public: //////////////////////////////////////////////////////////////////////////// // CONSTRUCTORS //////////////////////////////////////////////////////////////////////////// //! @brief Default constructor. Useless NArrayIterator() : array_(nullptr), position_() { } NArrayIterator(const wilt::NArray<T, N>& arr) : array_(&arr), position_() { } //! @brief NArray constructor from an array and offset //! @param[in] arr - array whose data to reference //! @param[in] pos - data offset value, defaults to 0 NArrayIterator(const wilt::NArray<T, N>& arr, const Point<N-M>& pos) : array_(&arr), position_(pos) { } //! @brief Copy constructor //! @param[in] iter - iterator to copy from NArrayIterator(const NArrayIterator<T, N, M>& iter) : array_(iter.array_), position_(iter.position_) { } //! @brief Copy constructor with offset //! @param[in] iter - iterator to copy from //! @param[in] pos - data offset value NArrayIterator(const NArrayIterator<T, N, M>& iter, const Point<N-M>& pos) : array_(iter.array_), position_(pos) { } public: //////////////////////////////////////////////////////////////////////////// // ASSIGNMENT OPERATORS //////////////////////////////////////////////////////////////////////////// //! @brief assignment operator //! @param[in] iter - iterator to copy from //! @return reference to this object NArrayIterator<T, N, M>& operator= (const NArrayIterator<T, N, M>& iter) { array_ = iter.array_; position_ = iter.position_; return *this; } //! @brief in-place addition operator, offsets data by +pos //! @param[in] pos - value to offset //! @return reference to this object NArrayIterator<T, N, M>& operator+= (const ptrdiff_t pos) { wilt::detail::addValueToPosition(position_, array_->sizes().data(), pos); return *this; } //! @brief in-place addition operator, offsets data by -pos //! @param[in] pos - value to offset //! @return reference to this object NArrayIterator<T, N, M>& operator-= (const ptrdiff_t pos) { wilt::detail::subValueFromPosition(position_, array_->sizes().data(), pos); return *this; } public: //////////////////////////////////////////////////////////////////////////// // ACCESS FUNCTIONS //////////////////////////////////////////////////////////////////////////// //! @brief de-reference operator, invalid if <begin or >=end //! @return reference to data at the iterator position value_type operator* () const { return at_(position_); } //! @brief index operator //! @param[in] pos - data offset value //! @return reference to data at the iterator position + offset value_type operator[] (pos_t pos) const { auto newposition = position_; wilt::detail::addValueToPosition(newposition, array_->sizes().data(), pos); return at_(newposition); } //! @brief gets the position of the iterator //! @return point corresponding to the position in the NArray currently //! pointing to Point<N-M> position() const { return position_; } public: //////////////////////////////////////////////////////////////////////////// // COMPARISON FUNCTIONS //////////////////////////////////////////////////////////////////////////// //! @brief equal operator, determines both if it references the same //! NArray data and if at same position //! @param[in] iter - iterator to compare //! @return true if iterators are the same, false otherwise bool operator== (const NArrayIterator<T, N, M>& iter) const { assert(array_ == iter.array_); return position_ == iter.position_; } //! @brief not equal operator, determines both if it references the //! same NArray data and if at same position //! @param[in] iter - iterator to compare //! @return false if iterators are the same, true otherwise bool operator!= (const NArrayIterator<T, N, M>& iter) const { assert(array_ == iter.array_); return !(*this == iter); } //! @brief less than operator, is only calculated from data offset, //! does not determine if they share a data-space //! @param[in] iter - iterator to compare //! @return true if data offset is less than that of iter bool operator< (const NArrayIterator<T, N, M>& iter) const { assert(array_ == iter.array_); // simple lexigraphical comparison for (std::size_t i = 0; i < N-M; ++i) { if (position_[i] < iter.position_[i]) return true; if (position_[i] > iter.position_[i]) return false; } return false; } //! @brief greater than operator, is only calculated from data offset, //! does not determine if they share a data-space //! @param[in] iter - iterator to compare //! @return true if data offset is greater than that of iter bool operator> (const NArrayIterator<T, N, M>& iter) const { assert(array_ == iter.array_); return iter < *this; } //! @brief less than or equal operator, is only calculated from data //! offset, does not determine if they share a data-space //! @param[in] iter - iterator to compare //! @return true if data offset is less than or equal to that of iter bool operator<= (const NArrayIterator<T, N, M>& iter) const { assert(array_ == iter.array_); return !(iter < *this); } //! @brief greater than or equal operator, is only calculated from data //! offset, does not determine if they share a data-space //! @param[in] iter - iterator to compare //! @return true if data offset is greater than or equal to that of iter bool operator>= (const NArrayIterator<T, N, M>& iter) const { assert(array_ == iter.array_); return !(*this < iter); } public: //////////////////////////////////////////////////////////////////////////// // MODIFIER FUNCTIONS //////////////////////////////////////////////////////////////////////////// //! @brief increments the data offset value //! @return reference to this object NArrayIterator<T, N, M>& operator++ () { wilt::detail::addOneToPosition(position_, array_->sizes().data()); return *this; } //! @brief decrements the data offset value //! @return reference to this object NArrayIterator<T, N, M>& operator-- () { wilt::detail::subOneFromPosition(position_, array_->sizes().data()); return *this; } //! @brief increments the data offset value //! @return copy of this object before incrementing NArrayIterator<T, N, M> operator++ (int) { auto oldposition = position_; ++(*this); return NArrayIterator<T, N, M>(*this, oldposition); } //! @brief decrements the data offset value //! @return copy of this object before decrementing NArrayIterator<T, N, M> operator-- (int) { auto oldposition = position_; --(*this); return NArrayIterator<T, N, M>(*this, oldposition); } //! @brief the difference of two iterators //! @param[in] iter - the iterator to diff //! @return the difference of the two data offset values difference_type operator- (const NArrayIterator<T, N, M>& iter) const { assert(array_ == iter.array_); pos_t diff = 0; for (std::size_t i = 0; i < N-M; ++i) { diff *= array_->sizes()[i]; diff += (position_[i] - iter.position_[i]); } return diff; } //! @brief addition operator //! @param[in] pos - the offset to add //! @return this iterator plus the offset NArrayIterator<T, N, M> operator+ (const ptrdiff_t pos) { auto newiter = *this; newiter += pos; return newiter; } //! @brief subtraction operator //! @param[in] pos - the offset to subtract //! @return this iterator minus the offset NArrayIterator<T, N, M> operator- (const ptrdiff_t pos) { auto newiter = *this; newiter -= pos; return newiter; } private: //////////////////////////////////////////////////////////////////////////// // PRIVATE FUNCTIONS //////////////////////////////////////////////////////////////////////////// //! @brief gets the pointer at the data offset //! @param[in] pos - data offset value //! @return pointer to data at the offset value_type at_(const Point<N-M>& pos) const { return array_->subarrayAtUnchecked(pos); } }; // class NArrayIterator namespace detail { template <std::size_t N> void addValueToPosition(Point<N>& pos, const pos_t* sizes, pos_t value) { for (std::size_t i = N-1; i > 0; --i) { pos[i] += value; if (pos[i] < sizes[i]) return; value = pos[i] / sizes[i]; pos[i] = pos[i] % sizes[i]; } pos[0] += value; } template <std::size_t N> void addOneToPosition(Point<N>& pos, const pos_t* sizes) { for (std::size_t i = N-1; i > 0; --i) { pos[i] += 1; if (pos[i] < sizes[i]) return; pos[i] = 0; } pos[0] += 1; } template <std::size_t N> void subValueFromPosition(Point<N>& pos, const pos_t* sizes, pos_t value) { for (std::size_t i = N-1; i > 0; --i) { pos[i] -= value; if (pos[i] >= 0) return; value = -(pos[i] / sizes[i]); pos[i] = (pos[i] % sizes[i]) + sizes[i]; } pos[0] -= value; } template <std::size_t N> void subOneFromPosition(Point<N>& pos, const pos_t* sizes) { for (std::size_t i = N-1; i > 0; --i) { pos[i] -= 1; if (pos[i] >= 0) return; pos[i] = sizes[i]-1; } pos[0] -= 1; } } // namespace detail } // namespace wilt #endif // !WILT_NARRAYITERATOR_HPP <|endoftext|>
<commit_before>#include "event_handler.h" #include <string> #include <vector> #include <utility> #include <memory> #include <iostream> #include <iomanip> #include <errno.h> #include <sys/stat.h> #include <CoreServices/CoreServices.h> #include "flags.h" #include "recent_file_cache.h" #include "rename_buffer.h" #include "../../message.h" #include "../../log.h" using std::vector; using std::string; using std::shared_ptr; using std::move; using std::ostream; using std::hex; using std::dec; using std::endl; class EventFunctor { public: EventFunctor(EventHandler &handler, string &event_path, FSEventStreamEventFlags flags) : handler{handler}, cache{handler.cache}, rename_buffer{handler.rename_buffer}, event_path{event_path}, flags{flags}, stat_performed{false} { flag_created = (flags & CREATE_FLAGS) != 0; flag_deleted = (flags & DELETED_FLAGS) != 0; flag_modified = (flags & MODIFY_FLAGS) != 0; flag_renamed = (flags & RENAME_FLAGS) != 0; flag_file = (flags & IS_FILE) != 0; flag_directory = (flags & IS_DIRECTORY) != 0; } void operator()() { report(); determine_entry_kinds(); LOGGER << "Entry kinds: current_kind=" << current_kind << " former_kind=" << former_kind << "." << endl; check_cache(); LOGGER << "Cache status: seen_before=" << seen_before << " was_different_entry=" << was_different_entry << "." << endl; if (emit_if_unambiguous()) return; if (emit_if_absent()) return; emit_if_present(); } private: // Log the raw and interpreted flag information. void report() { ostream &logline = LOGGER; logline << "Native event received at [" << event_path << "]:" << endl; logline << " event flags " << hex << flags << dec << " ="; if ((flags & kFSEventStreamEventFlagMustScanSubDirs) != 0) logline << " MustScanSubDirs"; if ((flags & kFSEventStreamEventFlagUserDropped) != 0) logline << " UserDropped"; if ((flags & kFSEventStreamEventFlagKernelDropped) != 0) logline << " KernelDropped"; if ((flags & kFSEventStreamEventFlagEventIdsWrapped) != 0) logline << " EventIdsWrapped"; if ((flags & kFSEventStreamEventFlagMustScanSubDirs) != 0) logline << " MustScanSubDirs"; if ((flags & kFSEventStreamEventFlagHistoryDone) != 0) logline << " HistoryDone"; if ((flags & kFSEventStreamEventFlagRootChanged) != 0) logline << " RootChanged"; if ((flags & kFSEventStreamEventFlagMount) != 0) logline << " Mount"; if ((flags & kFSEventStreamEventFlagUnmount) != 0) logline << " Unmount"; if ((flags & kFSEventStreamEventFlagMustScanSubDirs) != 0) logline << " MustScanSubDirs"; if ((flags & kFSEventStreamEventFlagItemCreated) != 0) logline << " ItemCreated"; if ((flags & kFSEventStreamEventFlagItemRemoved) != 0) logline << " ItemRemoved"; if ((flags & kFSEventStreamEventFlagItemInodeMetaMod) != 0) logline << " ItemInodeMetaMod"; if ((flags & kFSEventStreamEventFlagItemRenamed) != 0) logline << " ItemRenamed"; if ((flags & kFSEventStreamEventFlagItemModified) != 0) logline << " ItemModified"; if ((flags & kFSEventStreamEventFlagItemFinderInfoMod) != 0) logline << " ItemFinderInfoMod"; if ((flags & kFSEventStreamEventFlagItemChangeOwner) != 0) logline << " ItemChangeOwner"; if ((flags & kFSEventStreamEventFlagItemXattrMod) != 0) logline << " ItemXattrMod"; if ((flags & kFSEventStreamEventFlagItemIsFile) != 0) logline << " ItemIsFile"; if ((flags & kFSEventStreamEventFlagItemIsDir) != 0) logline << " ItemIsDir"; if ((flags & kFSEventStreamEventFlagItemIsSymlink) != 0) logline << " ItemIsSymlink"; if ((flags & kFSEventStreamEventFlagOwnEvent) != 0) logline << " OwnEvent"; if ((flags & kFSEventStreamEventFlagItemIsHardlink) != 0) logline << " ItemIsHardlink"; if ((flags & kFSEventStreamEventFlagItemIsLastHardlink) != 0) logline << " ItemIsLastHardlink"; logline << endl; logline << " interpreted as" << " file=" << flag_file << " directory=" << flag_directory << " created=" << flag_created << " deleted=" << flag_deleted << " modified=" << flag_modified << " renamed=" << flag_renamed << endl; } // Use the event flags and, if necessary, lstat() result to determine the current and previous kinds of // this entry. void determine_entry_kinds() { if (flag_file && !flag_directory) { former_kind = current_kind = KIND_FILE; return; } if (flag_directory && !flag_file) { former_kind = current_kind = KIND_DIRECTORY; return; } // Flags are ambiguous. Try to check lstat(). ensure_lstat(); if (!is_present) { // Check the cache to see what this entry was the last time it produced an event. shared_ptr<CacheEntry> entry = cache.at_path(event_path); former_kind = entry ? entry->entry_kind : KIND_UNKNOWN; // Because both flags are set on the event, it must have changed from one to the other over the lifespan // of this entry. if (former_kind == KIND_FILE) current_kind = KIND_DIRECTORY; if (former_kind == KIND_DIRECTORY) current_kind = KIND_FILE; return; } // We know what the entry is now. Because both flags have been set on the event, it must have been different before. if ((path_stat.st_mode & S_IFREG) != 0) { former_kind = KIND_DIRECTORY; current_kind = KIND_FILE; } else if ((path_stat.st_mode & S_IFDIR) != 0) { former_kind = KIND_FILE; current_kind = KIND_DIRECTORY; } // Leave both as KIND_UNKNOWN. } // Check the recently-seen entry cache for this entry. void check_cache() { shared_ptr<CacheEntry> maybe = cache.at_path(event_path); seen_before = maybe && maybe->entry_kind == current_kind; was_different_entry = current_kind != former_kind && maybe; } // Emit messages for events that have unambiguous flags. bool emit_if_unambiguous() { ensure_lstat(); if (flag_created && !(flag_deleted || flag_modified || flag_renamed)) { LOGGER << "Unambiguous creation." << endl; cache.does_exist(event_path, current_kind, path_stat.st_ino, path_stat.st_size); handler.enqueue_creation(event_path, current_kind); return true; } if (flag_deleted && !(flag_created || flag_modified || flag_renamed)) { LOGGER << "Unambiguous deletion." << endl; cache.does_not_exist(event_path); handler.enqueue_deletion(event_path, current_kind); return true; } if (flag_modified && !(flag_created || flag_deleted || flag_renamed)) { LOGGER << "Unambiguous modification." << endl; cache.does_exist(event_path, current_kind, path_stat.st_ino, path_stat.st_size); handler.enqueue_modification(event_path, current_kind); return true; } if (flag_renamed && !(flag_created || flag_deleted || flag_modified)) { LOGGER << "Unambiguous rename." << endl; if (is_present) { rename_buffer.observe_present_entry(event_path, current_kind, path_stat.st_ino, path_stat.st_size); } else { shared_ptr<CacheEntry> entry = cache.at_path(event_path); if (entry != nullptr) { rename_buffer.observe_absent_entry(event_path, current_kind, entry->inode, entry->size); } else { rename_buffer.observe_absent_entry(event_path, current_kind); } } return true; } return false; } // Emit messages based on the last observed state of this entry if it no longer exists. bool emit_if_absent() { ensure_lstat(); if (is_present) return false; LOGGER << "Entry is no longer present." << endl; shared_ptr<CacheEntry> entry = cache.at_path(event_path); cache.does_not_exist(event_path); if (flag_renamed) { if (entry != nullptr) { rename_buffer.observe_absent_entry(event_path, current_kind, entry->inode, entry->size); } else { rename_buffer.observe_absent_entry(event_path, current_kind); } return true; } if (!seen_before) { if (was_different_entry) { // Entry was last seen as a directory, but the latest event has it flagged as a file (or vice versa). // The directory must have been deleted. handler.enqueue_deletion(event_path, former_kind); } // Entry has not been seen before, so we must have missed its creation event. handler.enqueue_creation(event_path, former_kind); } // It isn't there now, so it must have been deleted. handler.enqueue_deletion(event_path, current_kind); return true; } // Emit messages based on the event flags and the current lstat() output. bool emit_if_present() { ensure_lstat(); if (!is_present) return false; LOGGER << "Entry is still present." << endl; cache.does_exist(event_path, current_kind, path_stat.st_ino, path_stat.st_size); if (flag_renamed) { rename_buffer.observe_present_entry(event_path, current_kind, path_stat.st_ino, path_stat.st_size); return true; } if (seen_before) { // This is *not* the first time an event at this path has been seen. if (flag_deleted) { // Rapid creation and deletion. There may be a lost modification event just before deletion or just after // recreation. handler.enqueue_deletion(event_path, former_kind); handler.enqueue_creation(event_path, current_kind); } else { // Modification of an existing entry. handler.enqueue_modification(event_path, current_kind); } } else { // This *is* the first time an event has been seen at this path. if (flag_deleted) { // The only way for the deletion flag to be set on an entry we haven't seen before is for the entry to // be rapidly created, deleted, and created again. handler.enqueue_creation(event_path, former_kind); handler.enqueue_deletion(event_path, former_kind); handler.enqueue_creation(event_path, current_kind); } else { // Otherwise, it must have been created. This may conceal a separate modification event just after // the entry's creation. handler.enqueue_creation(event_path, current_kind); } } return true; } // Call lstat() on the entry path if it has not already been called. After this function returns, // path_stat and is_present will be populated. void ensure_lstat() { if (stat_performed) return; if (lstat(event_path.c_str(), &path_stat) != 0) { errno_t stat_errno = errno; if (stat_errno == ENOENT) { is_present = false; } // Ignore lstat() errors on entries that: // (a) we aren't allowed to see // (b) are at paths with too many symlinks or looping symlinks // (c) have names that are too long // (d) have a path component that is (no longer) a directory // Log any other errno that we see. if (stat_errno != ENOENT && stat_errno != EACCES && stat_errno != ELOOP && stat_errno != ENAMETOOLONG && stat_errno != ENOTDIR) { LOGGER << "lstat(" << event_path << ") failed with errno " << errno << "." << endl; } } else { is_present = true; } stat_performed = true; } EventHandler &handler; RecentFileCache &cache; RenameBuffer &rename_buffer; string &event_path; FSEventStreamEventFlags flags; bool flag_created; bool flag_deleted; bool flag_modified; bool flag_renamed; bool flag_file; bool flag_directory; bool stat_performed; struct stat path_stat; bool is_present; EntryKind former_kind = KIND_UNKNOWN; EntryKind current_kind = KIND_UNKNOWN; bool seen_before; bool was_different_entry; }; EventHandler::EventHandler(vector<Message> &messages, RecentFileCache &cache, ChannelID channel_id) : messages{messages}, channel_id{channel_id}, cache{cache}, rename_buffer(this) { // } void EventHandler::handle(string &event_path, FSEventStreamEventFlags flags) { EventFunctor callable(*this, event_path, flags); callable(); } void EventHandler::enqueue_creation(string event_path, const EntryKind &kind) { string empty_path; FileSystemPayload payload(channel_id, ACTION_CREATED, kind, move(event_path), move(empty_path)); Message event_message(move(payload)); LOGGER << "Emitting filesystem message " << event_message << endl; messages.push_back(move(event_message)); } void EventHandler::enqueue_modification(string event_path, const EntryKind &kind) { string empty_path; FileSystemPayload payload(channel_id, ACTION_MODIFIED, kind, move(event_path), move(empty_path)); Message event_message(move(payload)); LOGGER << "Emitting filesystem message " << event_message << endl; messages.push_back(move(event_message)); } void EventHandler::enqueue_deletion(string event_path, const EntryKind &kind) { string empty_path; FileSystemPayload payload(channel_id, ACTION_DELETED, kind, move(event_path), move(empty_path)); Message event_message(move(payload)); LOGGER << "Emitting filesystem message " << event_message << endl; messages.push_back(move(event_message)); } void EventHandler::enqueue_rename(string old_path, string new_path, const EntryKind &kind) { FileSystemPayload payload(channel_id, ACTION_RENAMED, kind, move(old_path), move(new_path)); Message event_message(move(payload)); LOGGER << "Emitting filesystem message " << event_message << endl; messages.push_back(move(event_message)); } <commit_msg>Always lstat() and check the cache<commit_after>#include "event_handler.h" #include <string> #include <vector> #include <utility> #include <memory> #include <iostream> #include <iomanip> #include <errno.h> #include <sys/stat.h> #include <CoreServices/CoreServices.h> #include "flags.h" #include "recent_file_cache.h" #include "rename_buffer.h" #include "../../message.h" #include "../../log.h" using std::vector; using std::string; using std::shared_ptr; using std::move; using std::ostream; using std::hex; using std::dec; using std::endl; class EventFunctor { public: EventFunctor(EventHandler &handler, string &event_path, FSEventStreamEventFlags flags) : handler{handler}, cache{handler.cache}, rename_buffer{handler.rename_buffer}, event_path{event_path}, flags{flags}, stat_performed{false} { flag_created = (flags & CREATE_FLAGS) != 0; flag_deleted = (flags & DELETED_FLAGS) != 0; flag_modified = (flags & MODIFY_FLAGS) != 0; flag_renamed = (flags & RENAME_FLAGS) != 0; flag_file = (flags & IS_FILE) != 0; flag_directory = (flags & IS_DIRECTORY) != 0; } void operator()() { report(); ensure_lstat(); check_cache(); determine_entry_kinds(); LOGGER << "Entry kinds: current_kind=" << current_kind << " former_kind=" << former_kind << "." << endl; LOGGER << "Cache status: seen_before=" << seen_before << " was_different_entry=" << was_different_entry << "." << endl; if (emit_if_unambiguous()) return; if (emit_if_absent()) return; emit_if_present(); } private: // Log the raw and interpreted flag information. void report() { ostream &logline = LOGGER; logline << "Native event received at [" << event_path << "]:" << endl; logline << " event flags " << hex << flags << dec << " ="; if ((flags & kFSEventStreamEventFlagMustScanSubDirs) != 0) logline << " MustScanSubDirs"; if ((flags & kFSEventStreamEventFlagUserDropped) != 0) logline << " UserDropped"; if ((flags & kFSEventStreamEventFlagKernelDropped) != 0) logline << " KernelDropped"; if ((flags & kFSEventStreamEventFlagEventIdsWrapped) != 0) logline << " EventIdsWrapped"; if ((flags & kFSEventStreamEventFlagMustScanSubDirs) != 0) logline << " MustScanSubDirs"; if ((flags & kFSEventStreamEventFlagHistoryDone) != 0) logline << " HistoryDone"; if ((flags & kFSEventStreamEventFlagRootChanged) != 0) logline << " RootChanged"; if ((flags & kFSEventStreamEventFlagMount) != 0) logline << " Mount"; if ((flags & kFSEventStreamEventFlagUnmount) != 0) logline << " Unmount"; if ((flags & kFSEventStreamEventFlagMustScanSubDirs) != 0) logline << " MustScanSubDirs"; if ((flags & kFSEventStreamEventFlagItemCreated) != 0) logline << " ItemCreated"; if ((flags & kFSEventStreamEventFlagItemRemoved) != 0) logline << " ItemRemoved"; if ((flags & kFSEventStreamEventFlagItemInodeMetaMod) != 0) logline << " ItemInodeMetaMod"; if ((flags & kFSEventStreamEventFlagItemRenamed) != 0) logline << " ItemRenamed"; if ((flags & kFSEventStreamEventFlagItemModified) != 0) logline << " ItemModified"; if ((flags & kFSEventStreamEventFlagItemFinderInfoMod) != 0) logline << " ItemFinderInfoMod"; if ((flags & kFSEventStreamEventFlagItemChangeOwner) != 0) logline << " ItemChangeOwner"; if ((flags & kFSEventStreamEventFlagItemXattrMod) != 0) logline << " ItemXattrMod"; if ((flags & kFSEventStreamEventFlagItemIsFile) != 0) logline << " ItemIsFile"; if ((flags & kFSEventStreamEventFlagItemIsDir) != 0) logline << " ItemIsDir"; if ((flags & kFSEventStreamEventFlagItemIsSymlink) != 0) logline << " ItemIsSymlink"; if ((flags & kFSEventStreamEventFlagOwnEvent) != 0) logline << " OwnEvent"; if ((flags & kFSEventStreamEventFlagItemIsHardlink) != 0) logline << " ItemIsHardlink"; if ((flags & kFSEventStreamEventFlagItemIsLastHardlink) != 0) logline << " ItemIsLastHardlink"; logline << endl; logline << " interpreted as" << " file=" << flag_file << " directory=" << flag_directory << " created=" << flag_created << " deleted=" << flag_deleted << " modified=" << flag_modified << " renamed=" << flag_renamed << endl; } // Call lstat() on the entry path if it has not already been called. After this function returns, // path_stat and is_present will be populated. void ensure_lstat() { if (stat_performed) return; if (lstat(event_path.c_str(), &path_stat) != 0) { errno_t stat_errno = errno; if (stat_errno == ENOENT) { is_present = false; } // Ignore lstat() errors on entries that: // (a) we aren't allowed to see // (b) are at paths with too many symlinks or looping symlinks // (c) have names that are too long // (d) have a path component that is (no longer) a directory // Log any other errno that we see. if (stat_errno != ENOENT && stat_errno != EACCES && stat_errno != ELOOP && stat_errno != ENAMETOOLONG && stat_errno != ENOTDIR) { LOGGER << "lstat(" << event_path << ") failed with errno " << errno << "." << endl; } } else { is_present = true; } stat_performed = true; } // Check the recently-seen entry cache for this entry. void check_cache() { former_entry = cache.at_path(event_path); seen_before = former_entry && former_entry->entry_kind == current_kind; was_different_entry = current_kind != former_kind && former_entry; } // Use the event flags and, if necessary, lstat() result to determine the current and previous kinds of // this entry. void determine_entry_kinds() { // Check the cache to see what this entry was the last time it produced an event. former_kind = former_entry ? former_entry->entry_kind : KIND_UNKNOWN; if (flag_file && !flag_directory) { current_kind = KIND_FILE; if (former_kind == KIND_UNKNOWN) former_kind = KIND_FILE; return; } if (flag_directory && !flag_file) { former_kind = current_kind = KIND_DIRECTORY; if (former_kind == KIND_UNKNOWN) former_kind = KIND_DIRECTORY; return; } // Flags are ambiguous. Try to check lstat() results. if (is_present) { // We know what the entry is now. Because both flags have been set on the event, it must have been different before. if ((path_stat.st_mode & S_IFREG) != 0) { former_kind = KIND_DIRECTORY; current_kind = KIND_FILE; } else if ((path_stat.st_mode & S_IFDIR) != 0) { former_kind = KIND_FILE; current_kind = KIND_DIRECTORY; } return; } // Because both flags are set on the event, it must have changed from one to the other over the lifespan // of this entry. if (former_kind == KIND_FILE) current_kind = KIND_DIRECTORY; if (former_kind == KIND_DIRECTORY) current_kind = KIND_FILE; // Leave both as KIND_UNKNOWN. } // Emit messages for events that have unambiguous flags. bool emit_if_unambiguous() { if (flag_created && !(flag_deleted || flag_modified || flag_renamed)) { LOGGER << "Unambiguous creation." << endl; if (is_present) { cache.does_exist(event_path, current_kind, path_stat.st_ino, path_stat.st_size); } handler.enqueue_creation(event_path, current_kind); return true; } if (flag_deleted && !(flag_created || flag_modified || flag_renamed)) { LOGGER << "Unambiguous deletion." << endl; cache.does_not_exist(event_path); handler.enqueue_deletion(event_path, current_kind); return true; } if (flag_modified && !(flag_created || flag_deleted || flag_renamed)) { LOGGER << "Unambiguous modification." << endl; if (is_present) { cache.does_exist(event_path, current_kind, path_stat.st_ino, path_stat.st_size); } handler.enqueue_modification(event_path, current_kind); return true; } if (flag_renamed && !(flag_created || flag_deleted || flag_modified)) { LOGGER << "Unambiguous rename." << endl; if (is_present) { rename_buffer.observe_present_entry(event_path, current_kind, path_stat.st_ino, path_stat.st_size); } else { shared_ptr<CacheEntry> entry = cache.at_path(event_path); if (entry != nullptr) { rename_buffer.observe_absent_entry(event_path, current_kind, entry->inode, entry->size); } else { rename_buffer.observe_absent_entry(event_path, current_kind); } } return true; } return false; } // Emit messages based on the last observed state of this entry if it no longer exists. bool emit_if_absent() { if (is_present) return false; LOGGER << "Entry is no longer present." << endl; shared_ptr<CacheEntry> entry = cache.at_path(event_path); cache.does_not_exist(event_path); if (flag_renamed) { if (entry != nullptr) { rename_buffer.observe_absent_entry(event_path, current_kind, entry->inode, entry->size); } else { rename_buffer.observe_absent_entry(event_path, current_kind); } return true; } if (!seen_before) { if (was_different_entry) { // Entry was last seen as a directory, but the latest event has it flagged as a file (or vice versa). // The directory must have been deleted. handler.enqueue_deletion(event_path, former_kind); } // Entry has not been seen before, so we must have missed its creation event. handler.enqueue_creation(event_path, former_kind); } // It isn't there now, so it must have been deleted. handler.enqueue_deletion(event_path, current_kind); return true; } // Emit messages based on the event flags and the current lstat() output. bool emit_if_present() { if (!is_present) return false; LOGGER << "Entry is still present." << endl; cache.does_exist(event_path, current_kind, path_stat.st_ino, path_stat.st_size); if (flag_renamed) { rename_buffer.observe_present_entry(event_path, current_kind, path_stat.st_ino, path_stat.st_size); return true; } if (seen_before) { // This is *not* the first time an event at this path has been seen. if (flag_deleted) { // Rapid creation and deletion. There may be a lost modification event just before deletion or just after // recreation. handler.enqueue_deletion(event_path, former_kind); handler.enqueue_creation(event_path, current_kind); } else { // Modification of an existing entry. handler.enqueue_modification(event_path, current_kind); } } else { // This *is* the first time an event has been seen at this path. if (flag_deleted) { // The only way for the deletion flag to be set on an entry we haven't seen before is for the entry to // be rapidly created, deleted, and created again. handler.enqueue_creation(event_path, former_kind); handler.enqueue_deletion(event_path, former_kind); handler.enqueue_creation(event_path, current_kind); } else { // Otherwise, it must have been created. This may conceal a separate modification event just after // the entry's creation. handler.enqueue_creation(event_path, current_kind); } } return true; } EventHandler &handler; RecentFileCache &cache; RenameBuffer &rename_buffer; string &event_path; FSEventStreamEventFlags flags; bool flag_created; bool flag_deleted; bool flag_modified; bool flag_renamed; bool flag_file; bool flag_directory; bool stat_performed; struct stat path_stat; bool is_present; EntryKind former_kind = KIND_UNKNOWN; EntryKind current_kind = KIND_UNKNOWN; shared_ptr<CacheEntry> former_entry; bool seen_before; bool was_different_entry; }; EventHandler::EventHandler(vector<Message> &messages, RecentFileCache &cache, ChannelID channel_id) : messages{messages}, channel_id{channel_id}, cache{cache}, rename_buffer(this) { // } void EventHandler::handle(string &event_path, FSEventStreamEventFlags flags) { EventFunctor callable(*this, event_path, flags); callable(); } void EventHandler::enqueue_creation(string event_path, const EntryKind &kind) { string empty_path; FileSystemPayload payload(channel_id, ACTION_CREATED, kind, move(event_path), move(empty_path)); Message event_message(move(payload)); LOGGER << "Emitting filesystem message " << event_message << endl; messages.push_back(move(event_message)); } void EventHandler::enqueue_modification(string event_path, const EntryKind &kind) { string empty_path; FileSystemPayload payload(channel_id, ACTION_MODIFIED, kind, move(event_path), move(empty_path)); Message event_message(move(payload)); LOGGER << "Emitting filesystem message " << event_message << endl; messages.push_back(move(event_message)); } void EventHandler::enqueue_deletion(string event_path, const EntryKind &kind) { string empty_path; FileSystemPayload payload(channel_id, ACTION_DELETED, kind, move(event_path), move(empty_path)); Message event_message(move(payload)); LOGGER << "Emitting filesystem message " << event_message << endl; messages.push_back(move(event_message)); } void EventHandler::enqueue_rename(string old_path, string new_path, const EntryKind &kind) { FileSystemPayload payload(channel_id, ACTION_RENAMED, kind, move(old_path), move(new_path)); Message event_message(move(payload)); LOGGER << "Emitting filesystem message " << event_message << endl; messages.push_back(move(event_message)); } <|endoftext|>
<commit_before><commit_msg>Isolated reading and writing of images from main loop (CIFAR)<commit_after><|endoftext|>
<commit_before>/*** Copyright (C) 2013 Aniket Deole <aniket.deole@gmail.com> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 2.1, 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 warranties of MERCHANTABILITY, SATISFACTORY QUALITY, 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, see <http://www.gnu.org/licenses/>. ***/ #include <gtkmm/box.h> #include <gtkmm/widget.h> #include <iostream> #include "maintoolbar.hh" MainToolbar::MainToolbar () { //Create the toolbar and add it to a container widget: Gtk::ToolButton* button = Gtk::manage(new Gtk::ToolButton()); // TODO Change this later to set_icon_widget // button->set_icon_name("dialog-cancel"); button->set_label ("Close"); button->signal_clicked().connect(sigc::mem_fun(*this, &MainToolbar::exitNotify) ); add(*button); Gtk::SeparatorToolItem* sti = Gtk::manage (new Gtk::SeparatorToolItem ()); sti->set_expand (false); sti->set_draw (true); add (*sti); button = Gtk::manage(new Gtk::ToolButton()); button->set_size_request (40, 40); button->set_label ("New Note"); button->signal_clicked().connect(sigc::mem_fun(*this, &MainToolbar::newNote) ); add(*button); button = Gtk::manage(new Gtk::ToolButton()); button->set_size_request (40, 40); button->set_label ("New Notebook"); button->signal_clicked().connect(sigc::mem_fun(*this, &MainToolbar::newNotebook) ); add(*button); sti = Gtk::manage (new Gtk::SeparatorToolItem ()); sti->set_expand (true); sti->set_can_focus (false); add (*sti); Gtk::ToolItem* searchEntryContainer = Gtk::manage (new Gtk::ToolItem ()); searchEntry = Gtk::manage (new Gtk::Entry ()); searchEntry->set_text ("Search"); searchEntry->set_icon_from_icon_name ("system-search"); searchEntry->signal_changed ().connect (sigc::mem_fun (*this, &MainToolbar::searchCallback)); searchEntry->signal_activate ().connect (sigc::mem_fun (*this, &MainToolbar::searchEntryClicked)); searchEntryActive = false; addCss (searchEntry, "searchEntry", ".searchEntry { color: #888; \n}\n"); searchEntryContainer->add (*searchEntry); add (*searchEntryContainer); button = Gtk::manage(new Gtk::ToolButton()); button->set_size_request (40, 40); button->set_label ("Maximize"); add (*button); Glib::RefPtr<Gtk::StyleContext> sc = get_style_context(); sc->add_class("primary-toolbar"); show_all (); } MainToolbar::~MainToolbar () { } void MainToolbar::exitNotify () { exit (0); } void MainToolbar::newNote () { app->nlpv->newNote (); } void MainToolbar::newNotebook () { app->lpv->newNotebook (); } void MainToolbar::searchCallback () { if (searchEntry->get_text().empty ()){ return; } app->nlpv->noteSearch (searchEntry->get_text ()); } void MainToolbar::searchEntryClicked () { if (!searchEntryActive) { searchEntry->set_text (""); searchEntryActive = true; } }<commit_msg>Remove label from search Entry.<commit_after>/*** Copyright (C) 2013 Aniket Deole <aniket.deole@gmail.com> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 2.1, 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 warranties of MERCHANTABILITY, SATISFACTORY QUALITY, 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, see <http://www.gnu.org/licenses/>. ***/ #include <gtkmm/box.h> #include <gtkmm/widget.h> #include <iostream> #include "maintoolbar.hh" MainToolbar::MainToolbar () { //Create the toolbar and add it to a container widget: Gtk::ToolButton* button = Gtk::manage(new Gtk::ToolButton()); // TODO Change this later to set_icon_widget // button->set_icon_name("dialog-cancel"); button->set_label ("Close"); button->signal_clicked().connect(sigc::mem_fun(*this, &MainToolbar::exitNotify) ); add(*button); Gtk::SeparatorToolItem* sti = Gtk::manage (new Gtk::SeparatorToolItem ()); sti->set_expand (false); sti->set_draw (true); add (*sti); button = Gtk::manage(new Gtk::ToolButton()); button->set_size_request (40, 40); button->set_label ("New Note"); button->signal_clicked().connect(sigc::mem_fun(*this, &MainToolbar::newNote) ); add(*button); button = Gtk::manage(new Gtk::ToolButton()); button->set_size_request (40, 40); button->set_label ("New Notebook"); button->signal_clicked().connect(sigc::mem_fun(*this, &MainToolbar::newNotebook) ); add(*button); sti = Gtk::manage (new Gtk::SeparatorToolItem ()); sti->set_expand (true); sti->set_can_focus (false); sti->set_use_action_appearance (false); sti->set_visible (true); add (*sti); Gtk::ToolItem* searchEntryContainer = Gtk::manage (new Gtk::ToolItem ()); searchEntry = Gtk::manage (new Gtk::Entry ()); searchEntry->set_text (""); searchEntry->set_icon_from_icon_name ("system-search"); searchEntry->signal_changed ().connect (sigc::mem_fun (*this, &MainToolbar::searchCallback)); searchEntry->signal_activate ().connect (sigc::mem_fun (*this, &MainToolbar::searchEntryClicked)); searchEntryActive = false; addCss (searchEntry, "searchEntry", ".searchEntry { color: #888; \n}\n"); searchEntryContainer->add (*searchEntry); add (*searchEntryContainer); button = Gtk::manage(new Gtk::ToolButton()); button->set_size_request (40, 40); button->set_label ("Maximize"); add (*button); Glib::RefPtr<Gtk::StyleContext> sc = get_style_context(); sc->add_class("primary-toolbar"); show_all (); } MainToolbar::~MainToolbar () { } void MainToolbar::exitNotify () { exit (0); } void MainToolbar::newNote () { app->nlpv->newNote (); } void MainToolbar::newNotebook () { app->lpv->newNotebook (); } void MainToolbar::searchCallback () { if (searchEntry->get_text().empty ()){ return; } app->nlpv->noteSearch (searchEntry->get_text ()); } void MainToolbar::searchEntryClicked () { if (!searchEntryActive) { searchEntry->set_text (""); searchEntryActive = true; } }<|endoftext|>
<commit_before>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 * * (c) 2006-2011 MGH, INRIA, USTL, UJF, CNRS * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Lesser General Public License as published by * * the Free Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. * * * * This library 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 Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this library; if not, write to the Free Software Foundation, * * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * ******************************************************************************* * SOFA :: Modules * * * * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ #ifndef SOFA_COMPONENT_MAPPING_IDENTITYMAPPING_INL #define SOFA_COMPONENT_MAPPING_IDENTITYMAPPING_INL #include <SofaBaseMechanics/IdentityMapping.h> #include <sofa/defaulttype/RigidTypes.h> #include <sofa/defaulttype/VecTypes.h> namespace sofa { namespace component { namespace mapping { template<class TIn, class TOut> void IdentityMapping<TIn, TOut>::init() { if ((stateFrom = dynamic_cast< core::behavior::BaseMechanicalState *>(this->fromModel.get()))) maskFrom = &stateFrom->forceMask; if ((stateTo = dynamic_cast< core::behavior::BaseMechanicalState *>(this->toModel.get()))) maskTo = &stateTo->forceMask; stateTo->resize( stateFrom->getSize() ); Inherit::init(); } template <class TIn, class TOut> void IdentityMapping<TIn, TOut>::apply(const core::MechanicalParams * /*mparams*/, Data<VecCoord>& dOut, const Data<InVecCoord>& dIn) { helper::WriteOnlyAccessor< Data<VecCoord> > out = dOut; helper::ReadAccessor< Data<InVecCoord> > in = dIn; // out.resize(in.size()); for(unsigned int i=0; i<out.size(); i++) { helper::eq(out[i], in[i]); } } template <class TIn, class TOut> void IdentityMapping<TIn, TOut>::applyJ(const core::MechanicalParams * /*mparams*/, Data<VecDeriv>& dOut, const Data<InVecDeriv>& dIn) { helper::WriteOnlyAccessor< Data<VecDeriv> > out = dOut; helper::ReadAccessor< Data<InVecDeriv> > in = dIn; // out.resize(in.size()); if ( !(maskTo->isInUse()) ) { for(unsigned int i=0; i<out.size(); i++) { helper::eq(out[i], in[i]); } } else { typedef helper::ParticleMask ParticleMask; const ParticleMask::InternalStorage &indices=maskTo->getEntries(); ParticleMask::InternalStorage::const_iterator it; for (it=indices.begin(); it!=indices.end(); it++) { const int i=(int)(*it); helper::eq(out[i], in[i]); } } } template<class TIn, class TOut> void IdentityMapping<TIn, TOut>::applyJT(const core::MechanicalParams * /*mparams*/, Data<InVecDeriv>& dOut, const Data<VecDeriv>& dIn) { helper::WriteAccessor< Data<InVecDeriv> > out = dOut; helper::ReadAccessor< Data<VecDeriv> > in = dIn; if ( !(maskTo->isInUse()) ) { maskFrom->setInUse(false); for(unsigned int i=0; i<in.size(); i++) { helper::peq(out[i], in[i]); } } else { typedef helper::ParticleMask ParticleMask; const ParticleMask::InternalStorage &indices=maskTo->getEntries(); ParticleMask::InternalStorage::const_iterator it; for (it=indices.begin(); it!=indices.end(); it++) { const int i=(int)(*it); helper::peq(out[i], in[i]); maskFrom->insertEntry(i); } } } template <class TIn, class TOut> void IdentityMapping<TIn, TOut>::applyJT(const core::ConstraintParams * /*cparams*/, Data<InMatrixDeriv>& dOut, const Data<MatrixDeriv>& dIn) { InMatrixDeriv& out = *dOut.beginEdit(); const MatrixDeriv& in = dIn.getValue(); typename Out::MatrixDeriv::RowConstIterator rowItEnd = in.end(); for (typename Out::MatrixDeriv::RowConstIterator rowIt = in.begin(); rowIt != rowItEnd; ++rowIt) { typename Out::MatrixDeriv::ColConstIterator colIt = rowIt.begin(); typename Out::MatrixDeriv::ColConstIterator colItEnd = rowIt.end(); // Creates a constraints if the input constraint is not empty. if (colIt != colItEnd) { typename In::MatrixDeriv::RowIterator o = out.writeLine(rowIt.index()); while (colIt != colItEnd) { InDeriv data; helper::eq(data, colIt.val()); o.addCol(colIt.index(), data); ++colIt; } } } dOut.endEdit(); } template <class TIn, class TOut> void IdentityMapping<TIn, TOut>::handleTopologyChange() { if ( stateTo && stateFrom && stateTo->getSize() != stateFrom->getSize()) this->init(); } template <class TIn, class TOut> const sofa::defaulttype::BaseMatrix* IdentityMapping<TIn, TOut>::getJ() { const unsigned int outStateSize = this->toModel->read(core::ConstVecCoordId::position())->getValue().size(); const unsigned int inStateSize = this->fromModel->read(core::ConstVecCoordId::position())->getValue().size(); assert(outStateSize == inStateSize); if (matrixJ.get() == 0 || updateJ) { updateJ = false; if (matrixJ.get() == 0 || (unsigned int)matrixJ->rowBSize() != outStateSize || (unsigned int)matrixJ->colBSize() != inStateSize) { matrixJ.reset(new MatrixType(outStateSize * NOut, inStateSize * NIn)); } else { matrixJ->clear(); } bool isMaskInUse = maskTo->isInUse(); typedef helper::ParticleMask ParticleMask; const ParticleMask::InternalStorage& indices = maskTo->getEntries(); ParticleMask::InternalStorage::const_iterator it = indices.begin(); for(unsigned i = 0; i < outStateSize && !(isMaskInUse && it == indices.end()); i++) { if (isMaskInUse) { if(i != *it) { continue; } ++it; } MBloc& block = *matrixJ->wbloc(i, i, true); IdentityMappingMatrixHelper<NOut, NIn, Real>::setMatrix(block); } } return matrixJ.get(); } template<int N, int M, class Real> struct IdentityMappingMatrixHelper { template <class Matrix> static void setMatrix(Matrix& mat) { for(int r = 0; r < N; ++r) { for(int c = 0; c < M; ++c) { mat[r][c] = (Real) 0; } if( r<M ) mat[r][r] = (Real) 1.0; } } }; template <class TIn, class TOut> const typename IdentityMapping<TIn, TOut>::js_type* IdentityMapping<TIn, TOut>::getJs() { if( !eigen.compressedMatrix.nonZeros() || updateJ ) { updateJ = false; assert( this->fromModel->getSize() == this->toModel->getSize()); const unsigned n = this->fromModel->getSize(); // each block (input i, output j) has only its top-left // principal submatrix filled with identity const unsigned rows = n * NOut; const unsigned cols = n * NIn; eigen.compressedMatrix.resize( rows, cols ); eigen.compressedMatrix.setZero(); eigen.compressedMatrix.reserve( rows ); for(unsigned i = 0 ; i < n; ++i) { for(unsigned r = 0; r < std::min<unsigned>(NIn, NOut); ++r) { const unsigned row = NOut * i + r; eigen.compressedMatrix.startVec( row ); const unsigned col = NIn * i + r; eigen.compressedMatrix.insertBack( row, col ) = 1; } } eigen.compressedMatrix.finalize(); } // std::cout << eigen.compressedMatrix << std::endl; return &js; } } // namespace mapping } // namespace component } // namespace sofa #endif <commit_msg>IdentityMapping: fixing non-mechanical output resize<commit_after>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 * * (c) 2006-2011 MGH, INRIA, USTL, UJF, CNRS * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Lesser General Public License as published by * * the Free Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. * * * * This library 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 Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this library; if not, write to the Free Software Foundation, * * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * ******************************************************************************* * SOFA :: Modules * * * * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ #ifndef SOFA_COMPONENT_MAPPING_IDENTITYMAPPING_INL #define SOFA_COMPONENT_MAPPING_IDENTITYMAPPING_INL #include <SofaBaseMechanics/IdentityMapping.h> #include <sofa/defaulttype/RigidTypes.h> #include <sofa/defaulttype/VecTypes.h> namespace sofa { namespace component { namespace mapping { template<class TIn, class TOut> void IdentityMapping<TIn, TOut>::init() { if ((stateFrom = dynamic_cast< core::behavior::BaseMechanicalState *>(this->fromModel.get()))) maskFrom = &stateFrom->forceMask; if ((stateTo = dynamic_cast< core::behavior::BaseMechanicalState *>(this->toModel.get()))) maskTo = &stateTo->forceMask; this->toModel->resize( this->fromModel->getSize() ); Inherit::init(); } template <class TIn, class TOut> void IdentityMapping<TIn, TOut>::apply(const core::MechanicalParams * /*mparams*/, Data<VecCoord>& dOut, const Data<InVecCoord>& dIn) { helper::WriteOnlyAccessor< Data<VecCoord> > out = dOut; helper::ReadAccessor< Data<InVecCoord> > in = dIn; // out.resize(in.size()); for(unsigned int i=0; i<out.size(); i++) { helper::eq(out[i], in[i]); } } template <class TIn, class TOut> void IdentityMapping<TIn, TOut>::applyJ(const core::MechanicalParams * /*mparams*/, Data<VecDeriv>& dOut, const Data<InVecDeriv>& dIn) { helper::WriteOnlyAccessor< Data<VecDeriv> > out = dOut; helper::ReadAccessor< Data<InVecDeriv> > in = dIn; // out.resize(in.size()); if ( !(maskTo->isInUse()) ) { for(unsigned int i=0; i<out.size(); i++) { helper::eq(out[i], in[i]); } } else { typedef helper::ParticleMask ParticleMask; const ParticleMask::InternalStorage &indices=maskTo->getEntries(); ParticleMask::InternalStorage::const_iterator it; for (it=indices.begin(); it!=indices.end(); it++) { const int i=(int)(*it); helper::eq(out[i], in[i]); } } } template<class TIn, class TOut> void IdentityMapping<TIn, TOut>::applyJT(const core::MechanicalParams * /*mparams*/, Data<InVecDeriv>& dOut, const Data<VecDeriv>& dIn) { helper::WriteAccessor< Data<InVecDeriv> > out = dOut; helper::ReadAccessor< Data<VecDeriv> > in = dIn; if ( !(maskTo->isInUse()) ) { maskFrom->setInUse(false); for(unsigned int i=0; i<in.size(); i++) { helper::peq(out[i], in[i]); } } else { typedef helper::ParticleMask ParticleMask; const ParticleMask::InternalStorage &indices=maskTo->getEntries(); ParticleMask::InternalStorage::const_iterator it; for (it=indices.begin(); it!=indices.end(); it++) { const int i=(int)(*it); helper::peq(out[i], in[i]); maskFrom->insertEntry(i); } } } template <class TIn, class TOut> void IdentityMapping<TIn, TOut>::applyJT(const core::ConstraintParams * /*cparams*/, Data<InMatrixDeriv>& dOut, const Data<MatrixDeriv>& dIn) { InMatrixDeriv& out = *dOut.beginEdit(); const MatrixDeriv& in = dIn.getValue(); typename Out::MatrixDeriv::RowConstIterator rowItEnd = in.end(); for (typename Out::MatrixDeriv::RowConstIterator rowIt = in.begin(); rowIt != rowItEnd; ++rowIt) { typename Out::MatrixDeriv::ColConstIterator colIt = rowIt.begin(); typename Out::MatrixDeriv::ColConstIterator colItEnd = rowIt.end(); // Creates a constraints if the input constraint is not empty. if (colIt != colItEnd) { typename In::MatrixDeriv::RowIterator o = out.writeLine(rowIt.index()); while (colIt != colItEnd) { InDeriv data; helper::eq(data, colIt.val()); o.addCol(colIt.index(), data); ++colIt; } } } dOut.endEdit(); } template <class TIn, class TOut> void IdentityMapping<TIn, TOut>::handleTopologyChange() { if ( stateTo && stateFrom && stateTo->getSize() != stateFrom->getSize()) this->init(); } template <class TIn, class TOut> const sofa::defaulttype::BaseMatrix* IdentityMapping<TIn, TOut>::getJ() { const unsigned int outStateSize = this->toModel->read(core::ConstVecCoordId::position())->getValue().size(); const unsigned int inStateSize = this->fromModel->read(core::ConstVecCoordId::position())->getValue().size(); assert(outStateSize == inStateSize); if (matrixJ.get() == 0 || updateJ) { updateJ = false; if (matrixJ.get() == 0 || (unsigned int)matrixJ->rowBSize() != outStateSize || (unsigned int)matrixJ->colBSize() != inStateSize) { matrixJ.reset(new MatrixType(outStateSize * NOut, inStateSize * NIn)); } else { matrixJ->clear(); } bool isMaskInUse = maskTo->isInUse(); typedef helper::ParticleMask ParticleMask; const ParticleMask::InternalStorage& indices = maskTo->getEntries(); ParticleMask::InternalStorage::const_iterator it = indices.begin(); for(unsigned i = 0; i < outStateSize && !(isMaskInUse && it == indices.end()); i++) { if (isMaskInUse) { if(i != *it) { continue; } ++it; } MBloc& block = *matrixJ->wbloc(i, i, true); IdentityMappingMatrixHelper<NOut, NIn, Real>::setMatrix(block); } } return matrixJ.get(); } template<int N, int M, class Real> struct IdentityMappingMatrixHelper { template <class Matrix> static void setMatrix(Matrix& mat) { for(int r = 0; r < N; ++r) { for(int c = 0; c < M; ++c) { mat[r][c] = (Real) 0; } if( r<M ) mat[r][r] = (Real) 1.0; } } }; template <class TIn, class TOut> const typename IdentityMapping<TIn, TOut>::js_type* IdentityMapping<TIn, TOut>::getJs() { if( !eigen.compressedMatrix.nonZeros() || updateJ ) { updateJ = false; assert( this->fromModel->getSize() == this->toModel->getSize()); const unsigned n = this->fromModel->getSize(); // each block (input i, output j) has only its top-left // principal submatrix filled with identity const unsigned rows = n * NOut; const unsigned cols = n * NIn; eigen.compressedMatrix.resize( rows, cols ); eigen.compressedMatrix.setZero(); eigen.compressedMatrix.reserve( rows ); for(unsigned i = 0 ; i < n; ++i) { for(unsigned r = 0; r < std::min<unsigned>(NIn, NOut); ++r) { const unsigned row = NOut * i + r; eigen.compressedMatrix.startVec( row ); const unsigned col = NIn * i + r; eigen.compressedMatrix.insertBack( row, col ) = 1; } } eigen.compressedMatrix.finalize(); } // std::cout << eigen.compressedMatrix << std::endl; return &js; } } // namespace mapping } // namespace component } // namespace sofa #endif <|endoftext|>
<commit_before>#include <QTime> #include <QTimer> #include <QMouseEvent> #include <QMenu> #include <QAction> #include <QSettings> #include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); setAttribute(Qt::WA_TranslucentBackground); setWindowFlags(Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint | windowFlags()); connect(this, &MainWindow::customContextMenuRequested, this, &MainWindow::showContextMenu); QTimer *timer = new QTimer(this); connect(timer, &QTimer::timeout, this, &MainWindow::updateTime); timer->start(1); updateTime(); } MainWindow::~MainWindow() { delete ui; } void MainWindow::updateTime() { QTime currentTime = QTime::currentTime(); QString currentTimeText = currentTime.toString("hh:mm:ss.zzz"); if (currentTime.second() % 2 == 0) currentTimeText[2] = ' '; else currentTimeText[5] = ' '; if (currentTime.second() % 3 == 0) currentTimeText[8] = ' '; ui->lcdNumber->display(currentTimeText); } void MainWindow::showContextMenu(const QPoint &pos) { QMenu contextMenu; contextMenu.addAction(QString("Exit"),this,SLOT(close())); contextMenu.exec(mapToGlobal(pos)); } void MainWindow::mouseReleaseEvent(QMouseEvent *e) { if (e->button() == Qt::RightButton) emit customContextMenuRequested(e->pos()); else QMainWindow::mouseReleaseEvent(e); } void MainWindow::mouseMoveEvent(QMouseEvent *e) { m_mousepos = e->pos(); } void MainWindow::mousePressEvent(QMouseEvent *e) { this->move(e->globalPos()-m_mousepos); } void MainWindow::closeEvent(QCloseEvent *e) { QSettings settings; settings.setValue("MainGeometry", saveGeometry()); settings.setValue("MainState", saveState()); e->accept(); } <commit_msg>reads prefs upon startup and restores settings<commit_after>#include <QTime> #include <QTimer> #include <QMouseEvent> #include <QMenu> #include <QAction> #include <QSettings> #include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); setAttribute(Qt::WA_TranslucentBackground); setWindowFlags(Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint | windowFlags()); connect(this, &MainWindow::customContextMenuRequested, this, &MainWindow::showContextMenu); QTimer *timer = new QTimer(this); connect(timer, &QTimer::timeout, this, &MainWindow::updateTime); timer->start(1); //1 → 1 ms granularity QSettings sts; restoreGeometry(sts.value("MainGeometry")); restoreState(sts.value("MainState")); updateTime(); } MainWindow::~MainWindow() { delete ui; } void MainWindow::updateTime() { QTime currentTime = QTime::currentTime(); QString currentTimeText = currentTime.toString("hh:mm:ss.zzz"); if (currentTime.second() % 2 == 0) currentTimeText[2] = ' '; else currentTimeText[5] = ' '; if (currentTime.second() % 3 == 0) currentTimeText[8] = ' '; ui->lcdNumber->display(currentTimeText); } void MainWindow::showContextMenu(const QPoint &pos) { QMenu contextMenu; contextMenu.addAction(QString("Exit"),this,SLOT(close())); contextMenu.exec(mapToGlobal(pos)); } void MainWindow::mouseReleaseEvent(QMouseEvent *e) { if (e->button() == Qt::RightButton) emit customContextMenuRequested(e->pos()); else QMainWindow::mouseReleaseEvent(e); } void MainWindow::mouseMoveEvent(QMouseEvent *e) { m_mousepos = e->pos(); } void MainWindow::mousePressEvent(QMouseEvent *e) { this->move(e->globalPos()-m_mousepos); } void MainWindow::closeEvent(QCloseEvent *e) { QSettings settings; settings.setValue("MainGeometry", saveGeometry()); settings.setValue("MainState", saveState()); e->accept(); } <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2000 The Apache Software Foundation. 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. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ #if !defined(TRANSENAMEMAP_HPP) #define TRANSENAMEMAP_HPP #include <xercesc/util/TransService.hpp> #include <xercesc/util/XMLString.hpp> XERCES_CPP_NAMESPACE_BEGIN // // This class is really private to the TransService class. However, some // compilers are too dumb to allow us to hide this class there in the Cpp // file that uses it. // class ENameMap { public : // ----------------------------------------------------------------------- // Destructor // ----------------------------------------------------------------------- ~ENameMap() { delete [] fEncodingName; } // ----------------------------------------------------------------------- // Virtual factory method // ----------------------------------------------------------------------- virtual XMLTranscoder* makeNew ( const unsigned int blockSize ) const = 0; // ----------------------------------------------------------------------- // Getter methods // ----------------------------------------------------------------------- const XMLCh* getKey() const { return fEncodingName; } protected : // ----------------------------------------------------------------------- // Hidden constructors // ----------------------------------------------------------------------- ENameMap(const XMLCh* const encodingName) : fEncodingName(XMLString::replicate(encodingName)) { } private : // ----------------------------------------------------------------------- // Unimplemented constructors and operators // ----------------------------------------------------------------------- ENameMap(); ENameMap(const ENameMap&); void operator=(const ENameMap&); // ----------------------------------------------------------------------- // Private data members // // fEncodingName // This is the encoding name for the transcoder that is controlled // by this map instance. // ----------------------------------------------------------------------- XMLCh* fEncodingName; }; template <class TType> class ENameMapFor : public ENameMap { public : // ----------------------------------------------------------------------- // Constructors and Destructor // ----------------------------------------------------------------------- ENameMapFor(const XMLCh* const encodingName); ~ENameMapFor(); // ----------------------------------------------------------------------- // Implementation of virtual factory method // ----------------------------------------------------------------------- virtual XMLTranscoder* makeNew(const unsigned int blockSize) const; private : // ----------------------------------------------------------------------- // Unimplemented constructors and operators // ----------------------------------------------------------------------- ENameMapFor(); ENameMapFor(const ENameMapFor<TType>&); void operator=(const ENameMapFor<TType>&); }; template <class TType> class EEndianNameMapFor : public ENameMap { public : // ----------------------------------------------------------------------- // Constructors and Destructor // ----------------------------------------------------------------------- EEndianNameMapFor(const XMLCh* const encodingName, const bool swapped); ~EEndianNameMapFor(); // ----------------------------------------------------------------------- // Implementation of virtual factory method // ----------------------------------------------------------------------- virtual XMLTranscoder* makeNew(const unsigned int blockSize) const; private : // ----------------------------------------------------------------------- // Unimplemented constructors and operators // ----------------------------------------------------------------------- EEndianNameMapFor(const EEndianNameMapFor<TType>&); void operator=(const EEndianNameMapFor<TType>&); // ----------------------------------------------------------------------- // Private data members // // fSwapped // Indicates whether the endianess of the encoding is opposite of // that of the local host. // ----------------------------------------------------------------------- bool fSwapped; }; XERCES_CPP_NAMESPACE_END #if !defined(XERCES_TMPLSINC) #include <xercesc/util/TransENameMap.c> #endif #endif <commit_msg>[Bug 12350] Xerces compilation problems on Tandem (HP Nonstop). Patch from Duncan Stodart.<commit_after>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2000 The Apache Software Foundation. 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. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ #if !defined(TRANSENAMEMAP_HPP) #define TRANSENAMEMAP_HPP #include <xercesc/util/TransService.hpp> #include <xercesc/util/XMLString.hpp> XERCES_CPP_NAMESPACE_BEGIN // // This class is really private to the TransService class. However, some // compilers are too dumb to allow us to hide this class there in the Cpp // file that uses it. // class ENameMap { public : // ----------------------------------------------------------------------- // Destructor // ----------------------------------------------------------------------- virtual ~ENameMap() { delete [] fEncodingName; } // ----------------------------------------------------------------------- // Virtual factory method // ----------------------------------------------------------------------- virtual XMLTranscoder* makeNew ( const unsigned int blockSize ) const = 0; // ----------------------------------------------------------------------- // Getter methods // ----------------------------------------------------------------------- const XMLCh* getKey() const { return fEncodingName; } protected : // ----------------------------------------------------------------------- // Hidden constructors // ----------------------------------------------------------------------- ENameMap(const XMLCh* const encodingName) : fEncodingName(XMLString::replicate(encodingName)) { } private : // ----------------------------------------------------------------------- // Unimplemented constructors and operators // ----------------------------------------------------------------------- ENameMap(); ENameMap(const ENameMap&); void operator=(const ENameMap&); // ----------------------------------------------------------------------- // Private data members // // fEncodingName // This is the encoding name for the transcoder that is controlled // by this map instance. // ----------------------------------------------------------------------- XMLCh* fEncodingName; }; template <class TType> class ENameMapFor : public ENameMap { public : // ----------------------------------------------------------------------- // Constructors and Destructor // ----------------------------------------------------------------------- ENameMapFor(const XMLCh* const encodingName); ~ENameMapFor(); // ----------------------------------------------------------------------- // Implementation of virtual factory method // ----------------------------------------------------------------------- virtual XMLTranscoder* makeNew(const unsigned int blockSize) const; private : // ----------------------------------------------------------------------- // Unimplemented constructors and operators // ----------------------------------------------------------------------- ENameMapFor(); ENameMapFor(const ENameMapFor<TType>&); void operator=(const ENameMapFor<TType>&); }; template <class TType> class EEndianNameMapFor : public ENameMap { public : // ----------------------------------------------------------------------- // Constructors and Destructor // ----------------------------------------------------------------------- EEndianNameMapFor(const XMLCh* const encodingName, const bool swapped); ~EEndianNameMapFor(); // ----------------------------------------------------------------------- // Implementation of virtual factory method // ----------------------------------------------------------------------- virtual XMLTranscoder* makeNew(const unsigned int blockSize) const; private : // ----------------------------------------------------------------------- // Unimplemented constructors and operators // ----------------------------------------------------------------------- EEndianNameMapFor(const EEndianNameMapFor<TType>&); void operator=(const EEndianNameMapFor<TType>&); // ----------------------------------------------------------------------- // Private data members // // fSwapped // Indicates whether the endianess of the encoding is opposite of // that of the local host. // ----------------------------------------------------------------------- bool fSwapped; }; XERCES_CPP_NAMESPACE_END #if !defined(XERCES_TMPLSINC) #include <xercesc/util/TransENameMap.c> #endif #endif <|endoftext|>
<commit_before> #include <plexum/graph.h> int main(int argc, char** argv) { return 0; } <commit_msg>remove sandbox.cc<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: vclxaccessiblecomponent.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: pb $ $Date: 2002-03-05 08:22:34 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _TOOLKIT_AWT_VCLXAccessibleComponent_HXX_ #define _TOOLKIT_AWT_VCLXAccessibleComponent_HXX_ #ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLE_HPP_ #include <drafts/com/sun/star/accessibility/XAccessible.hpp> #endif #ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLECONTEXT_HPP_ #include <drafts/com/sun/star/accessibility/XAccessibleContext.hpp> #endif #ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLEEXTENDEDCOMPONENT_HPP_ #include <drafts/com/sun/star/accessibility/XAccessibleExtendedComponent.hpp> #endif #ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLEEVENTBROADCASTER_HPP_ #include <drafts/com/sun/star/accessibility/XAccessibleEventBroadcaster.hpp> #endif #ifndef _COM_SUN_STAR_AWT_XWINDOW_HPP_ #include <com/sun/star/awt/XWindow.hpp> #endif #ifndef _CPPUHELPER_COMPBASE4_HXX_ #include <cppuhelper/compbase4.hxx> #endif #include <tools/gen.hxx> // Size #include <tools/link.hxx> // Size class Window; class VCLXWindow; class VclSimpleEvent; class VclWindowEvent; namespace utl { class AccessibleStateSetHelper; } class MutexHelper_Impl { protected: ::osl::Mutex maMutex; }; typedef cppu::WeakComponentImplHelper4< ::drafts::com::sun::star::accessibility::XAccessible, ::drafts::com::sun::star::accessibility::XAccessibleContext, ::drafts::com::sun::star::accessibility::XAccessibleExtendedComponent, ::drafts::com::sun::star::accessibility::XAccessibleEventBroadcaster > VCLXAccessibleComponentBase; // ---------------------------------------------------- // class VCLXAccessibleComponent // ---------------------------------------------------- class VCLXAccessibleComponent : public MutexHelper_Impl, public VCLXAccessibleComponentBase { private: ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow> mxWindow; VCLXWindow* mpVCLXindow; ::cppu::OInterfaceContainerHelper maEventListeners; ULONG nDummy1; ULONG nDummy2; void* pDummy1; void* pDummy2; protected: ::osl::Mutex& GetMutex() { return maMutex; } DECL_LINK( WindowEventListener, VclSimpleEvent* ); virtual void ProcessWindowEvent( const VclWindowEvent& rVclWindowEvent ); virtual void FillAccessibleStateSet( utl::AccessibleStateSetHelper& rStateSet ); void NotifyAccessibleEvent( sal_Int16 nEventId, const ::com::sun::star::uno::Any& rOldValue, const ::com::sun::star::uno::Any& rNewValue ); public: VCLXAccessibleComponent( VCLXWindow* pVCLXindow ); ~VCLXAccessibleComponent(); VCLXWindow* GetVCLXWindow() const { return mpVCLXindow; } Window* GetWindow() const; virtual void SAL_CALL disposing(); // ::drafts::com::sun::star::accessibility::XAccessible ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessibleContext > SAL_CALL getAccessibleContext( ) throw (::com::sun::star::uno::RuntimeException); // ::drafts::com::sun::star::accessibility::XAccessibleEventBroadcaster void SAL_CALL addEventListener( const ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessibleEventListener >& xListener ) throw (::com::sun::star::uno::RuntimeException); void SAL_CALL removeEventListener( const ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessibleEventListener >& xListener ) throw (::com::sun::star::uno::RuntimeException); // ::drafts::com::sun::star::accessibility::XAccessibleContext sal_Int32 SAL_CALL getAccessibleChildCount( ) throw (::com::sun::star::uno::RuntimeException); ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleChild( sal_Int32 i ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException); ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleParent( ) throw (::com::sun::star::uno::RuntimeException); sal_Int32 SAL_CALL getAccessibleIndexInParent( ) throw (::com::sun::star::uno::RuntimeException); sal_Int16 SAL_CALL getAccessibleRole( ) throw (::com::sun::star::uno::RuntimeException); ::rtl::OUString SAL_CALL getAccessibleDescription( ) throw (::com::sun::star::uno::RuntimeException); ::rtl::OUString SAL_CALL getAccessibleName( ) throw (::com::sun::star::uno::RuntimeException); ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessibleRelationSet > SAL_CALL getAccessibleRelationSet( ) throw (::com::sun::star::uno::RuntimeException); ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessibleStateSet > SAL_CALL getAccessibleStateSet( ) throw (::com::sun::star::uno::RuntimeException); ::com::sun::star::lang::Locale SAL_CALL getLocale( ) throw (::drafts::com::sun::star::accessibility::IllegalAccessibleComponentStateException, ::com::sun::star::uno::RuntimeException); // ::drafts::com::sun::star::accessibility::XAccessibleComponent sal_Bool SAL_CALL contains( const ::com::sun::star::awt::Point& aPoint ) throw (::com::sun::star::uno::RuntimeException); ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleAt( const ::com::sun::star::awt::Point& aPoint ) throw (::com::sun::star::uno::RuntimeException); ::com::sun::star::awt::Rectangle SAL_CALL getBounds( ) throw (::com::sun::star::uno::RuntimeException); ::com::sun::star::awt::Size SAL_CALL getSize( ) throw (::com::sun::star::uno::RuntimeException); ::com::sun::star::awt::Point SAL_CALL getLocation( ) throw (::com::sun::star::uno::RuntimeException); ::com::sun::star::awt::Point SAL_CALL getLocationOnScreen( ) throw (::com::sun::star::uno::RuntimeException); sal_Bool SAL_CALL isShowing( ) throw (::com::sun::star::uno::RuntimeException); sal_Bool SAL_CALL isVisible( ) throw (::com::sun::star::uno::RuntimeException); sal_Bool SAL_CALL isFocusTraversable( ) throw (::com::sun::star::uno::RuntimeException); void SAL_CALL addFocusListener( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XFocusListener >& xListener ) throw (::com::sun::star::uno::RuntimeException); void SAL_CALL removeFocusListener( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XFocusListener >& xListener ) throw (::com::sun::star::uno::RuntimeException); void SAL_CALL grabFocus( ) throw (::com::sun::star::uno::RuntimeException); ::com::sun::star::uno::Any SAL_CALL getAccessibleKeyBinding( ) throw (::com::sun::star::uno::RuntimeException); // ::drafts::com::sun::star::accessibility::XAccessibleExtendedComponent virtual sal_Int32 SAL_CALL getForeground( ) throw (::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL getBackground( ) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::awt::XFont > SAL_CALL getFont( ) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::awt::FontDescriptor SAL_CALL getFontMetrics( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XFont >& xFont ) throw (::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL isEnabled( ) throw (::com::sun::star::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getTitledBorderText( ) throw (::com::sun::star::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getToolTipText( ) throw (::com::sun::star::uno::RuntimeException); }; /* ---------------------------------------------------------- Accessibility only for the Window hierarchy! Maybe derived classes must overwrite these Accessibility interfaces: // XAccessibleContext: sal_Int16 getAccessibleRole() => VCL Window::GetAccessibleRole() OUString getAccessibleDescription() => VCL Window::GetAccessibleDescription OUString getAccessibleName() => VCL Window::GetAccessibleText() => Most windows return Window::GetText() Reference< XAccessibleRelationSet > getAccessibleRelationSet() Reference< XAccessibleStateSet > getAccessibleStateSet() => overload FillAccessibleStateSet( ... ) // ::drafts::com::sun::star::accessibility::XAccessibleComponent sal_Bool isFocusTraversable() Any getAccessibleKeyBinding() ---------------------------------------------------------- */ #endif // _TOOLKIT_AWT_VCLXAccessibleComponent_HXX_ <commit_msg>fix: #97876# syntax changes<commit_after>/************************************************************************* * * $RCSfile: vclxaccessiblecomponent.hxx,v $ * * $Revision: 1.9 $ * * last change: $Author: pb $ $Date: 2002-03-22 08:24:32 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _TOOLKIT_AWT_VCLXACCESSIBLECOMPONENT_HXX_ #define _TOOLKIT_AWT_VCLXACCESSIBLECOMPONENT_HXX_ #ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLE_HPP_ #include <drafts/com/sun/star/accessibility/XAccessible.hpp> #endif #ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLECONTEXT_HPP_ #include <drafts/com/sun/star/accessibility/XAccessibleContext.hpp> #endif #ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLEEXTENDEDCOMPONENT_HPP_ #include <drafts/com/sun/star/accessibility/XAccessibleExtendedComponent.hpp> #endif #ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLEEVENTBROADCASTER_HPP_ #include <drafts/com/sun/star/accessibility/XAccessibleEventBroadcaster.hpp> #endif #ifndef _COM_SUN_STAR_AWT_XWINDOW_HPP_ #include <com/sun/star/awt/XWindow.hpp> #endif #ifndef _CPPUHELPER_COMPBASE4_HXX_ #include <cppuhelper/compbase4.hxx> #endif #include <tools/gen.hxx> // Size #include <tools/link.hxx> // Size class Window; class VCLXWindow; class VclSimpleEvent; class VclWindowEvent; namespace utl { class AccessibleStateSetHelper; } class MutexHelper_Impl { protected: ::osl::Mutex maMutex; }; typedef cppu::WeakComponentImplHelper4< ::drafts::com::sun::star::accessibility::XAccessible, ::drafts::com::sun::star::accessibility::XAccessibleContext, ::drafts::com::sun::star::accessibility::XAccessibleExtendedComponent, ::drafts::com::sun::star::accessibility::XAccessibleEventBroadcaster > VCLXAccessibleComponentBase; // ---------------------------------------------------- // class VCLXAccessibleComponent // ---------------------------------------------------- class VCLXAccessibleComponent : public MutexHelper_Impl, public VCLXAccessibleComponentBase { private: ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow> mxWindow; VCLXWindow* mpVCLXindow; ::cppu::OInterfaceContainerHelper maEventListeners; ULONG nDummy1; ULONG nDummy2; void* pDummy1; void* pDummy2; protected: ::osl::Mutex& GetMutex() { return maMutex; } DECL_LINK( WindowEventListener, VclSimpleEvent* ); virtual void ProcessWindowEvent( const VclWindowEvent& rVclWindowEvent ); virtual void FillAccessibleStateSet( utl::AccessibleStateSetHelper& rStateSet ); void NotifyAccessibleEvent( sal_Int16 nEventId, const ::com::sun::star::uno::Any& rOldValue, const ::com::sun::star::uno::Any& rNewValue ); public: VCLXAccessibleComponent( VCLXWindow* pVCLXindow ); ~VCLXAccessibleComponent(); VCLXWindow* GetVCLXWindow() const { return mpVCLXindow; } Window* GetWindow() const; virtual void SAL_CALL disposing(); // ::drafts::com::sun::star::accessibility::XAccessible ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessibleContext > SAL_CALL getAccessibleContext( ) throw (::com::sun::star::uno::RuntimeException); // ::drafts::com::sun::star::accessibility::XAccessibleEventBroadcaster void SAL_CALL addEventListener( const ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessibleEventListener >& xListener ) throw (::com::sun::star::uno::RuntimeException); void SAL_CALL removeEventListener( const ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessibleEventListener >& xListener ) throw (::com::sun::star::uno::RuntimeException); // ::drafts::com::sun::star::accessibility::XAccessibleContext sal_Int32 SAL_CALL getAccessibleChildCount( ) throw (::com::sun::star::uno::RuntimeException); ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleChild( sal_Int32 i ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException); ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleParent( ) throw (::com::sun::star::uno::RuntimeException); sal_Int32 SAL_CALL getAccessibleIndexInParent( ) throw (::com::sun::star::uno::RuntimeException); sal_Int16 SAL_CALL getAccessibleRole( ) throw (::com::sun::star::uno::RuntimeException); ::rtl::OUString SAL_CALL getAccessibleDescription( ) throw (::com::sun::star::uno::RuntimeException); ::rtl::OUString SAL_CALL getAccessibleName( ) throw (::com::sun::star::uno::RuntimeException); ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessibleRelationSet > SAL_CALL getAccessibleRelationSet( ) throw (::com::sun::star::uno::RuntimeException); ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessibleStateSet > SAL_CALL getAccessibleStateSet( ) throw (::com::sun::star::uno::RuntimeException); ::com::sun::star::lang::Locale SAL_CALL getLocale( ) throw (::drafts::com::sun::star::accessibility::IllegalAccessibleComponentStateException, ::com::sun::star::uno::RuntimeException); // ::drafts::com::sun::star::accessibility::XAccessibleComponent sal_Bool SAL_CALL contains( const ::com::sun::star::awt::Point& aPoint ) throw (::com::sun::star::uno::RuntimeException); ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleAt( const ::com::sun::star::awt::Point& aPoint ) throw (::com::sun::star::uno::RuntimeException); ::com::sun::star::awt::Rectangle SAL_CALL getBounds( ) throw (::com::sun::star::uno::RuntimeException); ::com::sun::star::awt::Size SAL_CALL getSize( ) throw (::com::sun::star::uno::RuntimeException); ::com::sun::star::awt::Point SAL_CALL getLocation( ) throw (::com::sun::star::uno::RuntimeException); ::com::sun::star::awt::Point SAL_CALL getLocationOnScreen( ) throw (::com::sun::star::uno::RuntimeException); sal_Bool SAL_CALL isShowing( ) throw (::com::sun::star::uno::RuntimeException); sal_Bool SAL_CALL isVisible( ) throw (::com::sun::star::uno::RuntimeException); sal_Bool SAL_CALL isFocusTraversable( ) throw (::com::sun::star::uno::RuntimeException); void SAL_CALL addFocusListener( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XFocusListener >& xListener ) throw (::com::sun::star::uno::RuntimeException); void SAL_CALL removeFocusListener( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XFocusListener >& xListener ) throw (::com::sun::star::uno::RuntimeException); void SAL_CALL grabFocus( ) throw (::com::sun::star::uno::RuntimeException); ::com::sun::star::uno::Any SAL_CALL getAccessibleKeyBinding( ) throw (::com::sun::star::uno::RuntimeException); // ::drafts::com::sun::star::accessibility::XAccessibleExtendedComponent virtual sal_Int32 SAL_CALL getForeground( ) throw (::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL getBackground( ) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::awt::XFont > SAL_CALL getFont( ) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::awt::FontDescriptor SAL_CALL getFontMetrics( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XFont >& xFont ) throw (::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL isEnabled( ) throw (::com::sun::star::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getTitledBorderText( ) throw (::com::sun::star::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getToolTipText( ) throw (::com::sun::star::uno::RuntimeException); }; /* ---------------------------------------------------------- Accessibility only for the Window hierarchy! Maybe derived classes must overwrite these Accessibility interfaces: // XAccessibleContext: sal_Int16 getAccessibleRole() => VCL Window::GetAccessibleRole() OUString getAccessibleDescription() => VCL Window::GetAccessibleDescription OUString getAccessibleName() => VCL Window::GetAccessibleText() => Most windows return Window::GetText() Reference< XAccessibleRelationSet > getAccessibleRelationSet() Reference< XAccessibleStateSet > getAccessibleStateSet() => overload FillAccessibleStateSet( ... ) // ::drafts::com::sun::star::accessibility::XAccessibleComponent sal_Bool isFocusTraversable() Any getAccessibleKeyBinding() ---------------------------------------------------------- */ #endif // _TOOLKIT_AWT_VCLXACCESSIBLECOMPONENT_HXX_ <|endoftext|>
<commit_before>// // Copyright Renga Software LLC, 2016. All rights reserved. // // Renga Software LLC PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // Renga Software LLC DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // #include "stdafx.h" #include "EntityPropertyViewBuilder.h" EntityPropertyViewBuilder::EntityPropertyViewBuilder( ParameterContainerAccess parametersAccess, PropertyContainerAccess propertiesAccess, QuantityContainerAccess quantitiesAccess, bool disableProperties) : PropertyViewBuilderBase(disableProperties), m_parametersAccess(parametersAccess), m_propertiesAccess(propertiesAccess), m_quantitiesAccess(quantitiesAccess) { } void EntityPropertyViewBuilder::createParameters(PropertyManager& mngr, PropertyList& propertyList) { // TODO: remove this condition, devide class free functions auto pParameters = m_parametersAccess(); if (pParameters == nullptr) return; auto properties = createParametersInternal(mngr, *pParameters); propertyList.splice(propertyList.end(), properties); } void EntityPropertyViewBuilder::createQuantities(PropertyManager& mngr, PropertyList& propertyList) { // TODO: remove this condition, devide class free functions auto pQuantities = m_quantitiesAccess(); if (pQuantities == nullptr) return; auto properties = createQuantitiesInternal(mngr, *pQuantities); propertyList.splice(propertyList.end(), properties); } PropertyList EntityPropertyViewBuilder::createProperties(PropertyManager& mngr) { auto pProperties = m_propertiesAccess(); if (pProperties == nullptr) return PropertyList{}; return createPropertiesInternal(mngr, pProperties); } <commit_msg>Bugfix: check access lambdas before use them to get data from Renga<commit_after>// // Copyright Renga Software LLC, 2016. All rights reserved. // // Renga Software LLC PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // Renga Software LLC DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // #include "stdafx.h" #include "EntityPropertyViewBuilder.h" EntityPropertyViewBuilder::EntityPropertyViewBuilder( ParameterContainerAccess parametersAccess, PropertyContainerAccess propertiesAccess, QuantityContainerAccess quantitiesAccess, bool disableProperties) : PropertyViewBuilderBase(disableProperties), m_parametersAccess(parametersAccess), m_propertiesAccess(propertiesAccess), m_quantitiesAccess(quantitiesAccess) { } void EntityPropertyViewBuilder::createParameters(PropertyManager& mngr, PropertyList& propertyList) { // TODO: remove this condition, devide class free functions if (!m_parametersAccess) return; auto pParameters = m_parametersAccess(); if (pParameters == nullptr) return; auto properties = createParametersInternal(mngr, *pParameters); propertyList.splice(propertyList.end(), properties); } void EntityPropertyViewBuilder::createQuantities(PropertyManager& mngr, PropertyList& propertyList) { // TODO: remove this condition, devide class free functions if (!m_quantitiesAccess) return; auto pQuantities = m_quantitiesAccess(); if (pQuantities == nullptr) return; auto properties = createQuantitiesInternal(mngr, *pQuantities); propertyList.splice(propertyList.end(), properties); } PropertyList EntityPropertyViewBuilder::createProperties(PropertyManager& mngr) { if (!m_propertiesAccess) return {}; auto pProperties = m_propertiesAccess(); if (pProperties == nullptr) return {}; return createPropertiesInternal(mngr, pProperties); } <|endoftext|>
<commit_before>#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup() { ofSetLogLevel(OF_LOG_VERBOSE); ofSetLogLevel("ofThread", OF_LOG_ERROR); ofEnableAlphaBlending(); doDrawInfo = true; targetWidth = 640; targetHeight = 480; #if defined(TARGET_OPENGLES) consoleListener.setup(this); omxCameraSettings.width = targetWidth; omxCameraSettings.height = targetHeight; omxCameraSettings.framerate = 15; omxCameraSettings.enableTexture = true; videoGrabber.setup(omxCameraSettings); filterCollection.setup(); ofSetVerticalSync(false); #else videoGrabber.setDeviceID(0); videoGrabber.setDesiredFrameRate(30); videoGrabber.setup(targetWidth, targetHeight); ofSetVerticalSync(true); #endif doShader = true; shader.load("shaderExample"); fbo.allocate(targetWidth, targetHeight); fbo.begin(); ofClear(0, 0, 0, 0); fbo.end(); // selfberry colorGifEncoder.setup(targetWidth, targetHeight, .2, 256); ofAddListener(ofxGifEncoder::OFX_GIF_SAVE_FINISHED, this, &ofApp::onGifSaved); videoTexture.allocate(targetWidth, targetHeight, GL_RGB); bufferDir = "buffer"; timeZero = ofGetElapsedTimeMicros(); frameNumber = 0; slotRecording = 255; slotAmount = 4; if (dirSRC.doesDirectoryExist(bufferDir)) { dirSRC.removeDirectory(bufferDir, true); } if (!dirSRC.doesDirectoryExist("slot1")) { dirSRC.createDirectory("slot1"); } if (!dirSRC.doesDirectoryExist("slot2")) { dirSRC.createDirectory("slot2"); } if (!dirSRC.doesDirectoryExist("slot3")) { dirSRC.createDirectory("slot3"); } if (!dirSRC.doesDirectoryExist("slot4")) { dirSRC.createDirectory("slot4"); } if (!dirSRC.doesDirectoryExist("tmp")) { dirSRC.createDirectory("tmp"); } if (!dirSRC.doesDirectoryExist("gif")) { dirSRC.createDirectory("gif"); } dirSRC.createDirectory(bufferDir); indexSavedPhoto = 0; isRecording = false; amountOfFrames = 10; maxFrames = 10; if (settings.loadFile("settings.xml") == false) { ofLog() << "XML ERROR, possibly quit"; } settings.pushTag("settings"); /*if (settings.getValue("log", 1) == 0) { ofLogLevel(OF_LOG_SILENT); } fps = settings.getValue("fps", 15); maxFrames = settings.getValue("frameAmount", 15); bufferDir = settings.getValue("bufferDir", "buffer"); outputDir = settings.getValue("outputDir", "output"); if (settings.getValue("fullScreen", 0) == 1) { ofToggleFullscreen(); }*/ slotDir = "slot"; for (int i = 0; i < settings.getNumTags("slot"); i++) { settings.pushTag("slot", i); videoGrid[i].init(settings.getValue("id", i), settings.getValue("x", 700), settings.getValue("y", 500), &slotDir, settings.getValue("key", 0)); settings.popTag(); } lastSpot = 0; currentDisplaySlot = 2; bkgLayer.loadImage("ui.png"); } //-------------------------------------------------------------- void ofApp::update() { #if defined(TARGET_OPENGLES) #else videoGrabber.update(); #endif if (!doShader ) { ofLogNotice("update() !doShader return"); return; } if (!videoGrabber.isFrameNew()) { ofLogNotice("update() !videoGrabber.isFrameNew return"); return; } //ofLogNotice("update() fbo begin"); fbo.begin(); ofClear(1, 1, 0, 0); shader.begin(); shader.setUniform1f("time", ofGetElapsedTimef()); shader.setUniform2f("resolution", ofGetWidth(), ofGetHeight()); #if defined(TARGET_OPENGLES) shader.setUniformTexture("tex0", videoGrabber.getTextureReference(), videoGrabber.getTextureID()); videoGrabber.draw(); #else shader.setUniformTexture("tex0", videoGrabber.getTexture(), 0 );// 0 or 1? videoGrabber.draw(0, 0); #endif shader.end(); fbo.end(); //ofLogNotice("update() fbo end"); if (isRecording == true) { ofLogNotice("update() rec"); dirSRC.createDirectory(bufferDir); dirSRC.listDir(bufferDir); recordedFramesAmount = dirSRC.size(); ofLogNotice("AMOUNT OF FILES: " + ofToString(recordedFramesAmount) + "/" + ofToString(maxFrames)); if (recordedFramesAmount == maxFrames) { isRecording = false; indexSavedPhoto = 0; ofLogNotice("update() stop recording"); } else { if (videoGrabber.isFrameNew()) { ofLogNotice("update() isFrameNew"); string filename; if (indexSavedPhoto < 10) filename = "slot" + ofToString(currentDisplaySlot) + "//seq00" + ofToString(indexSavedPhoto) + ".tga"; if (indexSavedPhoto >= 10 && indexSavedPhoto < 100) filename = "slot" + ofToString(currentDisplaySlot) + "//seq0" + ofToString(indexSavedPhoto) + ".tga"; if (indexSavedPhoto >= 100 && indexSavedPhoto < 1000) filename = "slot" + ofToString(currentDisplaySlot) + "//seq" + ofToString(indexSavedPhoto) + ".tga"; // fbo to pixels fbo.readToPixels(pix); fbo.draw(0, 0, targetWidth, targetHeight); ofLogNotice("AMOUNT OF FILES: " + ofToString(recordedFramesAmount) + "/" + ofToString(maxFrames)); //pix.resize(targetWidth, targetHeight, OF_INTERPOLATE_NEAREST_NEIGHBOR); savedImage.setFromPixels(pix); savedImage.setImageType(OF_IMAGE_COLOR); savedImage.saveImage(filename); /*switch (currentDisplaySlot) { case 2: savedImage.saveImage("slot2//" + filename + ".tga"); break; case 3: savedImage.saveImage("slot3//" + filename + ".tga"); break; case 4: savedImage.saveImage("slot4//" + filename + ".tga"); break; } */ ofLogNotice("update() currentDisplaySlot " + ofToString(currentDisplaySlot)); savedImage.saveImage(bufferDir + "//" + filename + ".tga"); //omxCameraSettings.width, omxCameraSettings.height // add frame to gif encoder colorGifEncoder.addFrame( pix.getPixels(), targetWidth, targetHeight, pix.getBitsPerPixel()/*, .1f duration */ ); recordedFramesAmount++; pix.clear(); savedImage.clear(); indexSavedPhoto++; if (indexSavedPhoto == amountOfFrames) { ofLogNotice("Stop recording: " + ofToString(indexSavedPhoto) + "/" + ofToString(amountOfFrames)); isRecording = false; indexSavedPhoto = 0; saveGif(); } } } } for (i = 1; i < slotAmount; i++) { videoGrid[i].loadFrameNumber(frameNumber); } frameNumber++; if (frameNumber == maxFrames) { frameNumber = 0; } } void ofApp::saveGif() { string fileName = ofToString(ofGetMonth()) + "-" + ofToString(ofGetDay()) + "-" + ofToString(ofGetHours()) + "-" + ofToString(ofGetMinutes()) + "-" + ofToString(ofGetSeconds()); ofLogNotice("saveGif: " + fileName); colorGifEncoder.save("gif//" + fileName + ".gif"); ofLogNotice("saveGif end"); } void ofApp::onGifSaved(string & fileName) { cout << "gif saved as " << fileName << endl; ofLogNotice("onGifSaved: " + fileName); colorGifEncoder.reset(); ofLogNotice("onGifSaved reset"); } //-------------------------------------------------------------- void ofApp::draw() { ofClear(0, 0, 0, 0); stringstream info; info << "APP FPS: " << ofGetFrameRate() << "\n"; info << "SHADER ENABLED: " << doShader << "\n"; if (doShader) { #if defined(TARGET_OPENGLES) fbo.draw(330, 13); #else videoGrabber.draw(330, 13); #endif } else { #if defined(TARGET_OPENGLES) videoGrabber.draw(); info << "Camera Resolution: " << videoGrabber.getWidth() << "x" << videoGrabber.getHeight() << " @ " << videoGrabber.getFrameRate() << "FPS" << "\n"; info << "CURRENT FILTER: " << filterCollection.getCurrentFilterName() << "\n"; #else videoGrabber.draw(0, 0); #endif } for (int i = 1; i < slotAmount; i++) { videoGrid[i].draw(); } info << "\n"; info << "VERT: changement de filtre" << "\n"; info << "ROUGE: enregistrer" << "\n"; bkgLayer.draw(0, 0); if (doDrawInfo) { ofDrawBitmapStringHighlight(info.str(), 50, 940, ofColor::black, ofColor::yellow); } } //-------------------------------------------------------------- void ofApp::keyPressed(int key) { //ofLog(OF_LOG_VERBOSE, "%c keyPressed", key); ofLogNotice("PRESSED KEY: " + ofToString(key)); /*RED 13 10 WHITE 127 126 YELLOW 54 GREEN 357 65 BLUE 50*/ switch (key) { case 65: case 357: #if defined(TARGET_OPENGLES) videoGrabber.setImageFilter(filterCollection.getNextFilter()); #endif break; case 10: case 13: if (!isRecording) { isRecording = true; indexSavedPhoto = 0; currentDisplaySlot++; if (currentDisplaySlot > 4) currentDisplaySlot = 2; bufferDir = ofToString(ofGetMonth()) + "-" + ofToString(ofGetDay()) + "-" + ofToString(ofGetHours()) + "-" + ofToString(ofGetMinutes()) + "-" + ofToString(ofGetSeconds()); } break; case 126: doDrawInfo = !doDrawInfo; currentDisplaySlot++; if (currentDisplaySlot > 4) currentDisplaySlot = 2; break; case 67: // jaune currentDisplaySlot = 3; case 66: // bleu currentDisplaySlot = 4; #if defined(TARGET_OPENGLES) videoGrabber.setImageFilter(filterCollection.getNextFilter()); #endif case 50: case 359: doShader = !doShader; break; } } #if defined(TARGET_OPENGLES) void ofApp::onCharacterReceived(KeyListenerEventData& e) { keyPressed((int)e.character); } #endif <commit_msg>slots<commit_after>#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup() { ofSetLogLevel(OF_LOG_VERBOSE); ofSetLogLevel("ofThread", OF_LOG_ERROR); ofEnableAlphaBlending(); doDrawInfo = true; targetWidth = 640; targetHeight = 480; #if defined(TARGET_OPENGLES) consoleListener.setup(this); omxCameraSettings.width = targetWidth; omxCameraSettings.height = targetHeight; omxCameraSettings.framerate = 15; omxCameraSettings.enableTexture = true; videoGrabber.setup(omxCameraSettings); filterCollection.setup(); ofSetVerticalSync(false); #else videoGrabber.setDeviceID(0); videoGrabber.setDesiredFrameRate(30); videoGrabber.setup(targetWidth, targetHeight); ofSetVerticalSync(true); #endif doShader = true; shader.load("shaderExample"); fbo.allocate(targetWidth, targetHeight); fbo.begin(); ofClear(0, 0, 0, 0); fbo.end(); // selfberry colorGifEncoder.setup(targetWidth, targetHeight, .2, 256); ofAddListener(ofxGifEncoder::OFX_GIF_SAVE_FINISHED, this, &ofApp::onGifSaved); videoTexture.allocate(targetWidth, targetHeight, GL_RGB); bufferDir = "buffer"; timeZero = ofGetElapsedTimeMicros(); frameNumber = 0; slotRecording = 255; slotAmount = 4; if (dirSRC.doesDirectoryExist(bufferDir)) { dirSRC.removeDirectory(bufferDir, true); } if (!dirSRC.doesDirectoryExist("slot1")) { dirSRC.createDirectory("slot1"); } if (!dirSRC.doesDirectoryExist("slot2")) { dirSRC.createDirectory("slot2"); } if (!dirSRC.doesDirectoryExist("slot3")) { dirSRC.createDirectory("slot3"); } if (!dirSRC.doesDirectoryExist("slot4")) { dirSRC.createDirectory("slot4"); } if (!dirSRC.doesDirectoryExist("tmp")) { dirSRC.createDirectory("tmp"); } if (!dirSRC.doesDirectoryExist("gif")) { dirSRC.createDirectory("gif"); } dirSRC.createDirectory(bufferDir); indexSavedPhoto = 0; isRecording = false; amountOfFrames = 10; maxFrames = 10; if (settings.loadFile("settings.xml") == false) { ofLog() << "XML ERROR, possibly quit"; } settings.pushTag("settings"); /*if (settings.getValue("log", 1) == 0) { ofLogLevel(OF_LOG_SILENT); } fps = settings.getValue("fps", 15); maxFrames = settings.getValue("frameAmount", 15); bufferDir = settings.getValue("bufferDir", "buffer"); outputDir = settings.getValue("outputDir", "output"); if (settings.getValue("fullScreen", 0) == 1) { ofToggleFullscreen(); }*/ slotDir = "slot"; for (int i = 0; i < settings.getNumTags("slot"); i++) { settings.pushTag("slot", i); videoGrid[i].init(settings.getValue("id", i), settings.getValue("x", 700), settings.getValue("y", 500), &slotDir, settings.getValue("key", 0)); settings.popTag(); } lastSpot = 0; currentDisplaySlot = 1; bkgLayer.loadImage("ui.png"); } //-------------------------------------------------------------- void ofApp::update() { #if defined(TARGET_OPENGLES) #else videoGrabber.update(); #endif if (!doShader ) { ofLogNotice("update() !doShader return"); return; } if (!videoGrabber.isFrameNew()) { ofLogNotice("update() !videoGrabber.isFrameNew return"); return; } //ofLogNotice("update() fbo begin"); fbo.begin(); ofClear(1, 1, 0, 0); shader.begin(); shader.setUniform1f("time", ofGetElapsedTimef()); shader.setUniform2f("resolution", ofGetWidth(), ofGetHeight()); #if defined(TARGET_OPENGLES) shader.setUniformTexture("tex0", videoGrabber.getTextureReference(), videoGrabber.getTextureID()); videoGrabber.draw(); #else shader.setUniformTexture("tex0", videoGrabber.getTexture(), 0 );// 0 or 1? videoGrabber.draw(0, 0); #endif shader.end(); fbo.end(); //ofLogNotice("update() fbo end"); if (isRecording == true) { ofLogNotice("update() rec"); dirSRC.createDirectory(bufferDir); dirSRC.listDir(bufferDir); recordedFramesAmount = dirSRC.size(); ofLogNotice("AMOUNT OF FILES: " + ofToString(recordedFramesAmount) + "/" + ofToString(maxFrames)); if (recordedFramesAmount == maxFrames) { isRecording = false; indexSavedPhoto = 0; ofLogNotice("update() stop recording"); } else { if (videoGrabber.isFrameNew()) { ofLogNotice("update() isFrameNew"); string filename; if (indexSavedPhoto < 10) filename = "slot" + ofToString(currentDisplaySlot) + "//seq00" + ofToString(indexSavedPhoto) + ".tga"; if (indexSavedPhoto >= 10 && indexSavedPhoto < 100) filename = "slot" + ofToString(currentDisplaySlot) + "//seq0" + ofToString(indexSavedPhoto) + ".tga"; if (indexSavedPhoto >= 100 && indexSavedPhoto < 1000) filename = "slot" + ofToString(currentDisplaySlot) + "//seq" + ofToString(indexSavedPhoto) + ".tga"; // fbo to pixels fbo.readToPixels(pix); fbo.draw(0, 0, targetWidth, targetHeight); ofLogNotice("AMOUNT OF FILES: " + ofToString(recordedFramesAmount) + "/" + ofToString(maxFrames)); //pix.resize(targetWidth, targetHeight, OF_INTERPOLATE_NEAREST_NEIGHBOR); savedImage.setFromPixels(pix); savedImage.setImageType(OF_IMAGE_COLOR); savedImage.saveImage(filename); ofLogNotice("update() currentDisplaySlot " + ofToString(currentDisplaySlot)); savedImage.saveImage(bufferDir + "//" + filename + ".tga"); //omxCameraSettings.width, omxCameraSettings.height // add frame to gif encoder colorGifEncoder.addFrame( pix.getPixels(), targetWidth, targetHeight, pix.getBitsPerPixel()/*, .1f duration */ ); recordedFramesAmount++; pix.clear(); savedImage.clear(); indexSavedPhoto++; if (indexSavedPhoto == amountOfFrames) { ofLogNotice("Stop recording: " + ofToString(indexSavedPhoto) + "/" + ofToString(amountOfFrames)); isRecording = false; indexSavedPhoto = 0; saveGif(); } } } } for (i = 1; i < slotAmount; i++) { videoGrid[i].loadFrameNumber(frameNumber); } frameNumber++; if (frameNumber == maxFrames) { frameNumber = 0; } } void ofApp::saveGif() { string fileName = ofToString(ofGetMonth()) + "-" + ofToString(ofGetDay()) + "-" + ofToString(ofGetHours()) + "-" + ofToString(ofGetMinutes()) + "-" + ofToString(ofGetSeconds()); ofLogNotice("saveGif: " + fileName); colorGifEncoder.save("gif//" + fileName + ".gif"); ofLogNotice("saveGif end"); } void ofApp::onGifSaved(string & fileName) { cout << "gif saved as " << fileName << endl; ofLogNotice("onGifSaved: " + fileName); colorGifEncoder.reset(); ofLogNotice("onGifSaved reset"); } //-------------------------------------------------------------- void ofApp::draw() { ofClear(0, 0, 0, 0); stringstream info; info << "APP FPS: " << ofGetFrameRate() << "\n"; info << "SHADER ENABLED: " << doShader << "\n"; if (doShader) { #if defined(TARGET_OPENGLES) fbo.draw(330, 13); #else videoGrabber.draw(330, 13); #endif } else { #if defined(TARGET_OPENGLES) videoGrabber.draw(); info << "Camera Resolution: " << videoGrabber.getWidth() << "x" << videoGrabber.getHeight() << " @ " << videoGrabber.getFrameRate() << "FPS" << "\n"; info << "CURRENT FILTER: " << filterCollection.getCurrentFilterName() << "\n"; #else videoGrabber.draw(0, 0); #endif } for (int i = 1; i < slotAmount; i++) { videoGrid[i].draw(); } info << "\n"; info << "VERT: changement de filtre" << "\n"; info << "ROUGE: enregistrer" << "\n"; bkgLayer.draw(0, 0); if (doDrawInfo) { ofDrawBitmapStringHighlight(info.str(), 50, 940, ofColor::black, ofColor::yellow); } } //-------------------------------------------------------------- void ofApp::keyPressed(int key) { //ofLog(OF_LOG_VERBOSE, "%c keyPressed", key); ofLogNotice("PRESSED KEY: " + ofToString(key)); /*RED 13 10 WHITE 127 126 YELLOW 54 GREEN 357 65 BLUE 50*/ switch (key) { case 65: case 357: #if defined(TARGET_OPENGLES) videoGrabber.setImageFilter(filterCollection.getNextFilter()); #endif break; case 10: case 13: if (!isRecording) { isRecording = true; indexSavedPhoto = 0; currentDisplaySlot++; if (currentDisplaySlot > 4) currentDisplaySlot = 1; bufferDir = ofToString(ofGetMonth()) + "-" + ofToString(ofGetDay()) + "-" + ofToString(ofGetHours()) + "-" + ofToString(ofGetMinutes()) + "-" + ofToString(ofGetSeconds()); } break; case 126: doDrawInfo = !doDrawInfo; currentDisplaySlot++; if (currentDisplaySlot > 4) currentDisplaySlot = 1; break; case 67: // jaune currentDisplaySlot = 3; case 66: // bleu currentDisplaySlot = 4; case 50: case 359: currentDisplaySlot = 1; //doShader = !doShader; break; } } #if defined(TARGET_OPENGLES) void ofApp::onCharacterReceived(KeyListenerEventData& e) { keyPressed((int)e.character); } #endif <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: TestLinearExtractor3D.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. =========================================================================*/ // .SECTION Thanks // This test was written by Philippe Pebay, Kitware SAS 2011 #include "vtkIdTypeArray.h" #include "vtkInformation.h" #include "vtkLinearExtractor.h" #include "vtkMultiBlockDataSet.h" #include "vtkSelection.h" #include "vtkSelectionNode.h" #include "vtkSmartPointer.h" #include "vtkTestUtilities.h" #include "vtkUnstructuredGrid.h" #include "vtkUnstructuredGridReader.h" // ------------------------------------------------------------------------------------------------ static void PrintSelectionNodes( vtkSelection* sel, const char* tag = NULL) { if( tag ) { cout << tag << endl; } // Iterate over nodes vtkIdType numNodes = sel->GetNumberOfNodes(); for( int iNode = 0; iNode < numNodes; ++ iNode ) { cout << ( tag ? "\t" : "" ) << "Node: " << iNode << endl; // Iterate over selection list for this node vtkIdType listSize = sel->GetNode( iNode )->GetSelectionList()->GetNumberOfTuples(); for( int iVal = 0; iVal < listSize; ++ iVal ) { cout << ( tag ? "\t" : "" ) << "\t" << iVal << "\t" << sel->GetNode( iNode )->GetSelectionList()->GetVariantValue( iVal ) << endl; } // for iVal } // for iNode } //---------------------------------------------------------------------------- int TestLinearExtractor3D( int argc, char * argv [] ) { // Read 3D unstructured input mesh char* fileName = vtkTestUtilities::ExpandDataFileName( argc, argv, "Data/AngularSector.vtk"); vtkSmartPointer<vtkUnstructuredGridReader> reader = vtkSmartPointer<vtkUnstructuredGridReader>::New(); reader->SetFileName( fileName ); reader->Update(); // Create multi-block mesh for linear extractor vtkSmartPointer<vtkMultiBlockDataSet> mesh = vtkSmartPointer<vtkMultiBlockDataSet>::New(); mesh->SetNumberOfBlocks( 1 ); mesh->GetMetaData( static_cast<unsigned>( 0 ) )->Set( vtkCompositeDataSet::NAME(), "Mesh" ); mesh->SetBlock( 0, reader->GetOutput() ); // ***************************************************************************** // 1. Selection along inner segment with endpoints (0,0,0) and (.23, 04,.04) // ***************************************************************************** // Create selection along one line segment vtkSmartPointer<vtkLinearExtractor> le1 = vtkSmartPointer<vtkLinearExtractor>::New(); le1->SetInput( mesh ); le1->SetStartPoint( .0, .0, .0 ); le1->SetEndPoint( .23, .04, .04 ); le1->IncludeVerticesOff(); le1->SetVertexEliminationTolerance( 2.3e-16 ); le1->Update(); vtkSelection* s1 = le1->GetOutput(); PrintSelectionNodes( s1 , "Selection (0,0,0)-(0.23,0.04,0.04)" ); // ***************************************************************************** // 2. Selection along boundary segment with endpoints (0,0,0) and (.23,0,0) // ***************************************************************************** // Create selection along one line segment vtkSmartPointer<vtkLinearExtractor> le2 = vtkSmartPointer<vtkLinearExtractor>::New(); le2->SetInput( mesh ); le2->SetStartPoint( .0, .0, .0 ); le2->SetEndPoint( .23, .0, .0 ); le2->IncludeVerticesOff(); le2->SetVertexEliminationTolerance( 1.e-12 ); le2->Update(); vtkSelection* s2 = le2->GetOutput(); PrintSelectionNodes( s2 , "Selection (0,0,0)-(0.23,0,0)" ); // ***************************************************************************** // 3. Selection along broken line through (.23,0,0), (0,0,0), and (.23,.04,.04) // ***************************************************************************** // Create list of points to define broken line vtkSmartPointer<vtkPoints> points3 = vtkSmartPointer<vtkPoints>::New(); points3->InsertNextPoint( .23, .0, .0 ); points3->InsertNextPoint( .0, .0, .0 ); points3->InsertNextPoint( .23, .04, .04 ); // Create selection along this broken line vtkSmartPointer<vtkLinearExtractor> le3 = vtkSmartPointer<vtkLinearExtractor>::New(); le3->SetInput( mesh ); le3->SetPoints( points3 ); le3->IncludeVerticesOff(); le3->SetVertexEliminationTolerance( 1.e-8 ); le3->Update(); vtkSelection* s3 = le3->GetOutput(); PrintSelectionNodes( s3 , "Selection (0.23,0,0)-(0,0,0)-(0.23,0.04,0.04)" ); int retVal = 1; return !retVal; } <commit_msg>An other test case (broken line with elements common to lines)<commit_after>/*========================================================================= Program: Visualization Toolkit Module: TestLinearExtractor3D.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. =========================================================================*/ // .SECTION Thanks // This test was written by Philippe Pebay, Kitware SAS 2011 #include "vtkIdTypeArray.h" #include "vtkInformation.h" #include "vtkLinearExtractor.h" #include "vtkMultiBlockDataSet.h" #include "vtkSelection.h" #include "vtkSelectionNode.h" #include "vtkSmartPointer.h" #include "vtkTestUtilities.h" #include "vtkUnstructuredGrid.h" #include "vtkUnstructuredGridReader.h" // ------------------------------------------------------------------------------------------------ static void PrintSelectionNodes( vtkSelection* sel, const char* tag = NULL) { if( tag ) { cout << tag << endl; } // Iterate over nodes vtkIdType numNodes = sel->GetNumberOfNodes(); for( int iNode = 0; iNode < numNodes; ++ iNode ) { cout << ( tag ? "\t" : "" ) << "Node: " << iNode << endl; // Iterate over selection list for this node vtkIdType listSize = sel->GetNode( iNode )->GetSelectionList()->GetNumberOfTuples(); for( int iVal = 0; iVal < listSize; ++ iVal ) { cout << ( tag ? "\t" : "" ) << "\t" << iVal << "\t" << sel->GetNode( iNode )->GetSelectionList()->GetVariantValue( iVal ) << endl; } // for iVal } // for iNode } //---------------------------------------------------------------------------- int TestLinearExtractor3D( int argc, char * argv [] ) { // Read 3D unstructured input mesh char* fileName = vtkTestUtilities::ExpandDataFileName( argc, argv, "Data/AngularSector.vtk"); vtkSmartPointer<vtkUnstructuredGridReader> reader = vtkSmartPointer<vtkUnstructuredGridReader>::New(); reader->SetFileName( fileName ); reader->Update(); // Create multi-block mesh for linear extractor vtkSmartPointer<vtkMultiBlockDataSet> mesh = vtkSmartPointer<vtkMultiBlockDataSet>::New(); mesh->SetNumberOfBlocks( 1 ); mesh->GetMetaData( static_cast<unsigned>( 0 ) )->Set( vtkCompositeDataSet::NAME(), "Mesh" ); mesh->SetBlock( 0, reader->GetOutput() ); // ***************************************************************************** // 1. Selection along inner segment with endpoints (0,0,0) and (.23, 04,.04) // ***************************************************************************** // Create selection along one line segment vtkSmartPointer<vtkLinearExtractor> le1 = vtkSmartPointer<vtkLinearExtractor>::New(); le1->SetInput( mesh ); le1->SetStartPoint( .0, .0, .0 ); le1->SetEndPoint( .23, .04, .04 ); le1->IncludeVerticesOff(); le1->SetVertexEliminationTolerance( 1.e-12 ); le1->Update(); vtkSelection* s1 = le1->GetOutput(); PrintSelectionNodes( s1 , "Selection (0,0,0)-(0.23,0.04,0.04)" ); // ***************************************************************************** // 2. Selection along boundary segment with endpoints (0,0,0) and (.23,0,0) // ***************************************************************************** // Create selection along one line segment vtkSmartPointer<vtkLinearExtractor> le2 = vtkSmartPointer<vtkLinearExtractor>::New(); le2->SetInput( mesh ); le2->SetStartPoint( .0, .0, .0 ); le2->SetEndPoint( .23, .0, .0 ); le2->IncludeVerticesOff(); le2->SetVertexEliminationTolerance( 1.e-12 ); le2->Update(); vtkSelection* s2 = le2->GetOutput(); PrintSelectionNodes( s2 , "Selection (0,0,0)-(0.23,0,0)" ); // ***************************************************************************** // 3. Selection along broken line through (.23,0,0), (0,0,0), (.23,.04,.04) // ***************************************************************************** // Create list of points to define broken line vtkSmartPointer<vtkPoints> points3 = vtkSmartPointer<vtkPoints>::New(); points3->InsertNextPoint( .23, .0, .0 ); points3->InsertNextPoint( .0, .0, .0 ); points3->InsertNextPoint( .23, .04, .04 ); // Create selection along this broken line vtkSmartPointer<vtkLinearExtractor> le3 = vtkSmartPointer<vtkLinearExtractor>::New(); le3->SetInput( mesh ); le3->SetPoints( points3 ); le3->IncludeVerticesOff(); le3->SetVertexEliminationTolerance( 1.e-12 ); le3->Update(); vtkSelection* s3 = le3->GetOutput(); PrintSelectionNodes( s3 , "Selection (0.23,0,0)-(0,0,0)-(0.23,0.04,0.04)" ); // ***************************************************************************** // 4. Selection along broken line through (.23,0,0), (.1,0,0), (.23,.01,.0033) // ***************************************************************************** // Create list of points to define broken line vtkSmartPointer<vtkPoints> points4 = vtkSmartPointer<vtkPoints>::New(); points4->InsertNextPoint( .23, .0, .0 ); points4->InsertNextPoint( .1, .0, .0 ); points4->InsertNextPoint( .23, .01, .0033 ); // Create selection along this broken line vtkSmartPointer<vtkLinearExtractor> le4 = vtkSmartPointer<vtkLinearExtractor>::New(); le4->SetInput( mesh ); le4->SetPoints( points4 ); le4->IncludeVerticesOff(); le4->SetVertexEliminationTolerance( 1.e-12 ); le4->Update(); vtkSelection* s4 = le4->GetOutput(); PrintSelectionNodes( s4 , "Selection (0.23,0,0)-(0.1,0,0)-(0.23,0.01,0.0033)" ); int retVal = 1; return !retVal; } <|endoftext|>
<commit_before>/* * Software License Agreement (BSD License) * * Copyright (c) 2010, Willow Garage, 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 Willow Garage, 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. * * * \author Nico Blodow (blodow@cs.tum.edu), Julius Kammerl (julius@kammerl.de) * */ #include "pcl/octree/octree.h" #include <pcl/visualization/pcl_visualizer.h> #include <pcl/io/pcd_io.h> #include <iostream> #include <vtkCubeSource.h> ///////////////////////////////////////////////////////////////////////////// // Create a vtkSmartPointer object containing a cube vtkSmartPointer<vtkPolyData> GetCuboid (double minX, double maxX, double minY, double maxY, double minZ, double maxZ) { vtkSmartPointer < vtkCubeSource > cube = vtkSmartPointer<vtkCubeSource>::New (); cube->SetBounds (minX, maxX, minY, maxY, minZ, maxZ); return cube->GetOutput (); } ///////////////////////////////////////////////////////////////////////////// // Create vtkActorCollection of vtkSmartPointers describing octree cubes void GetOctreeActors (std::vector<pcl::PointXYZ, Eigen::aligned_allocator<pcl::PointXYZ> >& voxelCenters, double voxelSideLen, vtkSmartPointer<vtkActorCollection> coll) { vtkSmartPointer < vtkAppendPolyData > treeWireframe = vtkSmartPointer<vtkAppendPolyData>::New (); size_t i; double s = voxelSideLen/2.0; for (i = 0; i < voxelCenters.size (); i++) { double x = voxelCenters[i].x; double y = voxelCenters[i].y; double z = voxelCenters[i].z; treeWireframe->AddInput (GetCuboid (x - s, x + s, y - s, y + s, z - s, z + s)); } vtkSmartPointer < vtkActor > treeActor = vtkSmartPointer<vtkActor>::New (); vtkSmartPointer < vtkDataSetMapper > mapper = vtkSmartPointer<vtkDataSetMapper>::New (); mapper->SetInput (treeWireframe->GetOutput ()); treeActor->SetMapper (mapper); treeActor->GetProperty ()->SetRepresentationToWireframe (); treeActor->GetProperty ()->SetColor (0.0, 0.0, 1.0); treeActor->GetProperty ()->SetLineWidth (2); coll->AddItem (treeActor); } //////////////////////////////////////////////////////////////////////////////// // Create a vtkPolyData object from a set of vtkPoints vtkDataSet* createDataSetFromVTKPoints (vtkPoints *points) { vtkCellArray *verts = vtkCellArray::New (); vtkPolyData *data = vtkPolyData::New (); // Iterate through the points for (vtkIdType i = 0; i < points->GetNumberOfPoints (); i++) verts->InsertNextCell ((vtkIdType)1, &i); data->SetPoints (points); data->SetVerts (verts); return data; } ///////////////////////////////////////////////////////////////////////////// // Create vtkActorCollection of vtkSmartPointers describing input points void GetPointActors (pcl::PointCloud<pcl::PointXYZ>& cloud, vtkSmartPointer<vtkActorCollection> coll) { vtkPolyData* points_poly; size_t i; vtkPoints *octreeLeafPoints = vtkPoints::New (); // add all points from octree to vtkPoint object for (i=0; i< cloud.points.size(); i++) { octreeLeafPoints->InsertNextPoint (cloud.points[i].x, cloud.points[i].y, cloud.points[i].z); } points_poly = (vtkPolyData*)createDataSetFromVTKPoints(octreeLeafPoints); vtkSmartPointer<vtkActor> pointsActor = vtkSmartPointer<vtkActor>::New (); vtkSmartPointer<vtkDataSetMapper> mapper = vtkSmartPointer<vtkDataSetMapper>::New (); mapper->SetInput (points_poly); pointsActor->SetMapper (mapper); pointsActor->GetProperty ()->SetColor (1.0, 0.0, 0.0); pointsActor->GetProperty ()->SetPointSize (4); coll->AddItem (pointsActor); } void printHelp (int argc, char **argv) { std::cout << "Syntax is " << argv[0] << " <file_name.pcd> <octree resolution> \n"; std::cout << "Example: ./octree_viewer ../../test/bunny.pcd 0.02 \n"; exit(1); } ///////////////////////////////////////////////////////////////////////////// // MAIN /* ---[ */ int main (int argc, char** argv) { if (argc!=3) { printHelp(argc, argv); } pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ>); pcl::io::loadPCDFile (argv[1], *cloud); vtkSmartPointer<vtkActorCollection> coll = vtkActorCollection::New (); vtkRenderer* ren = vtkRenderer::New (); // create octree from pointcloud pcl::octree::OctreePointCloud<pcl::PointXYZ> octree (atof (argv[2])); octree.setInputCloud (cloud); octree.addPointsFromInputCloud (); // get vector of voxel centers from octree double voxelSideLen; std::vector<pcl::PointXYZ, Eigen::aligned_allocator<pcl::PointXYZ> > voxelCenters; octree.getOccupiedVoxelCenters (voxelCenters); voxelSideLen = sqrt (octree.getVoxelSquaredSideLen ()); // delete octree octree.deleteTree(); // generate voxel boxes GetOctreeActors ( voxelCenters, voxelSideLen, coll); // visualize point input GetPointActors ( *cloud, coll); vtkActor* a; coll->InitTraversal (); a = coll->GetNextActor (); while(a!=0) { ren->AddActor (a); a = coll->GetNextActor (); } // Create Renderer and Interractor ren->SetBackground (1.0, 1.0, 1.0); vtkRenderWindowInteractor* iren = vtkRenderWindowInteractor::New (); vtkSmartPointer<vtkRenderWindow> win = vtkSmartPointer<vtkRenderWindow>::New (); win->AddRenderer (ren); iren->SetRenderWindow (win); iren->Start (); } <commit_msg>no window is opened in octree_viewer on Windows<commit_after>/* * Software License Agreement (BSD License) * * Copyright (c) 2010, Willow Garage, 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 Willow Garage, 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. * * * \author Nico Blodow (blodow@cs.tum.edu), Julius Kammerl (julius@kammerl.de) * */ #include "pcl/octree/octree.h" #include <pcl/visualization/pcl_visualizer.h> #include <pcl/io/pcd_io.h> #include <iostream> #include <vtkCubeSource.h> ///////////////////////////////////////////////////////////////////////////// // Create a vtkSmartPointer object containing a cube vtkSmartPointer<vtkPolyData> GetCuboid (double minX, double maxX, double minY, double maxY, double minZ, double maxZ) { vtkSmartPointer < vtkCubeSource > cube = vtkSmartPointer<vtkCubeSource>::New (); cube->SetBounds (minX, maxX, minY, maxY, minZ, maxZ); return cube->GetOutput (); } ///////////////////////////////////////////////////////////////////////////// // Create vtkActorCollection of vtkSmartPointers describing octree cubes void GetOctreeActors (std::vector<pcl::PointXYZ, Eigen::aligned_allocator<pcl::PointXYZ> >& voxelCenters, double voxelSideLen, vtkSmartPointer<vtkActorCollection> coll) { vtkSmartPointer < vtkAppendPolyData > treeWireframe = vtkSmartPointer<vtkAppendPolyData>::New (); size_t i; double s = voxelSideLen/2.0; for (i = 0; i < voxelCenters.size (); i++) { double x = voxelCenters[i].x; double y = voxelCenters[i].y; double z = voxelCenters[i].z; treeWireframe->AddInput (GetCuboid (x - s, x + s, y - s, y + s, z - s, z + s)); } vtkSmartPointer < vtkActor > treeActor = vtkSmartPointer<vtkActor>::New (); vtkSmartPointer < vtkDataSetMapper > mapper = vtkSmartPointer<vtkDataSetMapper>::New (); mapper->SetInput (treeWireframe->GetOutput ()); treeActor->SetMapper (mapper); treeActor->GetProperty ()->SetRepresentationToWireframe (); treeActor->GetProperty ()->SetColor (0.0, 0.0, 1.0); treeActor->GetProperty ()->SetLineWidth (2); coll->AddItem (treeActor); } //////////////////////////////////////////////////////////////////////////////// // Create a vtkPolyData object from a set of vtkPoints vtkDataSet* createDataSetFromVTKPoints (vtkPoints *points) { vtkCellArray *verts = vtkCellArray::New (); vtkPolyData *data = vtkPolyData::New (); // Iterate through the points for (vtkIdType i = 0; i < points->GetNumberOfPoints (); i++) verts->InsertNextCell ((vtkIdType)1, &i); data->SetPoints (points); data->SetVerts (verts); return data; } ///////////////////////////////////////////////////////////////////////////// // Create vtkActorCollection of vtkSmartPointers describing input points void GetPointActors (pcl::PointCloud<pcl::PointXYZ>& cloud, vtkSmartPointer<vtkActorCollection> coll) { vtkPolyData* points_poly; size_t i; vtkPoints *octreeLeafPoints = vtkPoints::New (); // add all points from octree to vtkPoint object for (i=0; i< cloud.points.size(); i++) { octreeLeafPoints->InsertNextPoint (cloud.points[i].x, cloud.points[i].y, cloud.points[i].z); } points_poly = (vtkPolyData*)createDataSetFromVTKPoints(octreeLeafPoints); vtkSmartPointer<vtkActor> pointsActor = vtkSmartPointer<vtkActor>::New (); vtkSmartPointer<vtkDataSetMapper> mapper = vtkSmartPointer<vtkDataSetMapper>::New (); mapper->SetInput (points_poly); pointsActor->SetMapper (mapper); pointsActor->GetProperty ()->SetColor (1.0, 0.0, 0.0); pointsActor->GetProperty ()->SetPointSize (4); coll->AddItem (pointsActor); } void printHelp (int argc, char **argv) { std::cout << "Syntax is " << argv[0] << " <file_name.pcd> <octree resolution> \n"; std::cout << "Example: ./octree_viewer ../../test/bunny.pcd 0.02 \n"; exit(1); } ///////////////////////////////////////////////////////////////////////////// // MAIN /* ---[ */ int main (int argc, char** argv) { if (argc!=3) { printHelp(argc, argv); } pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ>); pcl::io::loadPCDFile (argv[1], *cloud); vtkSmartPointer<vtkActorCollection> coll = vtkActorCollection::New (); vtkRenderer* ren = vtkRenderer::New (); // create octree from pointcloud pcl::octree::OctreePointCloud<pcl::PointXYZ> octree (atof (argv[2])); octree.setInputCloud (cloud); octree.addPointsFromInputCloud (); // get vector of voxel centers from octree double voxelSideLen; std::vector<pcl::PointXYZ, Eigen::aligned_allocator<pcl::PointXYZ> > voxelCenters; octree.getOccupiedVoxelCenters (voxelCenters); voxelSideLen = sqrt (octree.getVoxelSquaredSideLen ()); // delete octree octree.deleteTree(); // generate voxel boxes GetOctreeActors ( voxelCenters, voxelSideLen, coll); // visualize point input GetPointActors ( *cloud, coll); vtkActor* a; coll->InitTraversal (); a = coll->GetNextActor (); while(a!=0) { ren->AddActor (a); a = coll->GetNextActor (); } // Create Renderer and Interractor ren->SetBackground (1.0, 1.0, 1.0); vtkRenderWindowInteractor* iren = vtkRenderWindowInteractor::New (); vtkSmartPointer<vtkRenderWindow> win = vtkSmartPointer<vtkRenderWindow>::New (); win->AddRenderer (ren); iren->SetRenderWindow (win); win->Render (); iren->Start (); } <|endoftext|>
<commit_before> #include <boost/asio.hpp> #include "vtrc-common/vtrc-mutex-typedefs.h" #include "vtrc-bind.h" #include "vtrc-function.h" #include "vtrc-protocol-layer-s.h" #include "vtrc-monotonic-timer.h" #include "vtrc-data-queue.h" #include "vtrc-hash-iface.h" #include "vtrc-transformer-iface.h" #include "vtrc-transport-iface.h" #include "vtrc-common/vtrc-rpc-service-wrapper.h" #include "vtrc-common/vtrc-exception.h" #include "vtrc-common/vtrc-rpc-controller.h" #include "vtrc-common/vtrc-call-context.h" #include "vtrc-application.h" #include "protocol/vtrc-errors.pb.h" #include "protocol/vtrc-auth.pb.h" #include "protocol/vtrc-rpc-lowlevel.pb.h" #include "vtrc-chrono.h" #include "vtrc-atomic.h" #include "vtrc-common/vtrc-random-device.h" #include "vtrc-common/vtrc-delayed-call.h" namespace vtrc { namespace server { namespace gpb = google::protobuf; namespace bsys = boost::system; namespace basio = boost::asio; namespace { enum init_stage_enum { stage_begin = 1 ,stage_client_select = 2 ,stage_client_ready = 3 }; typedef std::map < std::string, common::rpc_service_wrapper_sptr > service_map; typedef vtrc_rpc_lowlevel::lowlevel_unit lowlevel_unit_type; typedef vtrc::shared_ptr<lowlevel_unit_type> lowlevel_unit_sptr; } namespace data_queue = common::data_queue; struct protocol_layer_s::impl { typedef impl this_type; typedef protocol_layer_s parent_type; application &app_; common::transport_iface *connection_; protocol_layer_s *parent_; bool ready_; service_map services_; shared_mutex services_lock_; std::string client_id_; common::delayed_call keepalive_calls_; typedef vtrc::function<void (void)> stage_function_type; stage_function_type stage_function_; vtrc::atomic<unsigned> current_calls_; const unsigned maximum_calls_; impl( application &a, common::transport_iface *c, unsigned maximum_calls) :app_(a) ,connection_(c) ,ready_(false) ,current_calls_(0) ,maximum_calls_(maximum_calls) ,keepalive_calls_(a.get_io_service( )) { stage_function_ = vtrc::bind( &this_type::on_client_selection, this ); /// client has only 10 seconds for init connection /// todo: think about setting for this timeout value keepalive_calls_.call_from_now( vtrc::bind( &this_type::on_keepavive, this, _1 ), boost::posix_time::seconds( 10 )); } common::rpc_service_wrapper_sptr get_service( const std::string &name ) { upgradable_lock lk( services_lock_ ); common::rpc_service_wrapper_sptr result; service_map::iterator f( services_.find( name ) ); if( f != services_.end( ) ) { result = f->second; } else { result = app_.get_service_by_name( connection_, name ); if( result ) { upgrade_to_unique ulk( lk ); services_.insert( std::make_pair( name, result ) ); } } return result; } bool pop_check_init_message( ) { } void pop_message( ) { parent_->pop_message( ); } void on_keepavive( const boost::system::error_code &error ) { if( !error ) { /// timeout for client init vtrc_auth::init_capsule cap; cap.mutable_error( )->set_code( vtrc_errors::ERR_TIMEOUT ); cap.set_ready( false ); send_and_close( cap ); } } bool check_message_hash( const std::string &mess ) { return parent_->check_message( mess ); } void send_proto_message( const gpb::Message &mess ) { std::string s(mess.SerializeAsString( )); connection_->write( s.c_str( ), s.size( ) ); } void send_proto_message( const gpb::Message &mess, common::closure_type closure, bool on_send) { std::string s(mess.SerializeAsString( )); connection_->write( s.c_str( ), s.size( ), closure, on_send ); } void send_and_close( const gpb::Message &mess ) { send_proto_message( mess, vtrc::bind( &this_type::close_client, this, _1, connection_->shared_from_this( )), true ); } void set_client_ready( ) { keepalive_calls_.cancel( ); stage_function_ = vtrc::bind( &this_type::on_rcp_call_ready, this ); parent_->set_ready( true ); } void close_client( const bsys::error_code & /*err*/, common::connection_iface_sptr /*inst*/) { connection_->close( ); } void on_client_transformer( ) { using namespace common::transformers; vtrc_auth::init_capsule capsule; bool check = get_pop_message( capsule ); if( !check ) { connection_->close( ); return; } if( !capsule.ready( ) ) { connection_->close( ); return; } vtrc_auth::transformer_setup tsetup; tsetup.ParseFromString( capsule.body( ) ); std::string key(app_.get_session_key( connection_, client_id_ )); create_key( key, tsetup.salt1( ), tsetup.salt2( ), key ); common::transformer_iface *new_transformer = erseefor::create( key.c_str( ), key.size( ) ); parent_->change_transformer( new_transformer ); capsule.Clear( ); capsule.set_ready( true ); capsule.set_text( "Kiva nahda sinut!" ); set_client_ready( ); send_proto_message( capsule ); } void setup_transformer( unsigned id ) { using namespace common::transformers; vtrc_auth::transformer_setup ts; vtrc_auth::init_capsule capsule; if( id == vtrc_auth::TRANSFORM_NONE ) { capsule.set_ready( true ); capsule.set_text( "Kiva nahda sinut!" ); set_client_ready( ); send_proto_message( capsule ); } else if( id == vtrc_auth::TRANSFORM_ERSEEFOR ) { std::string key(app_.get_session_key(connection_, client_id_)); generate_key_infos( key, // input *ts.mutable_salt1( ), // output *ts.mutable_salt2( ), // output key ); // output common::transformer_iface *new_reverter = erseefor::create( key.c_str( ), key.size( ) ); parent_->change_reverter( new_reverter ); capsule.set_ready( true ); capsule.set_body( ts.SerializeAsString( ) ); stage_function_ = vtrc::bind( &this_type::on_client_transformer, this ); send_proto_message( capsule ); } else { capsule.set_ready( false ); vtrc_errors::container *er(capsule.mutable_error( )); er->set_code( vtrc_errors::ERR_INVALID_VALUE ); er->set_category(vtrc_errors::CATEGORY_INTERNAL); er->set_additional( "Invalid transformer" ); send_and_close( capsule ); return; } } void on_client_selection( ) { vtrc_auth::init_capsule capsule; bool check = get_pop_message( capsule ); if( !check ) { connection_->close( ); return; } if( !capsule.ready( ) ) { connection_->close( ); return; } vtrc_auth::client_selection cs; cs.ParseFromString( capsule.body( ) ); common::hash_iface *new_checker( common::hash::create_by_index( cs.hash( ) ) ); common::hash_iface *new_maker( common::hash::create_by_index( cs.hash( ) ) ); if( !new_maker ) { delete new_checker; } if( !new_maker || !new_checker ) { connection_->close( ); return; } client_id_.assign( cs.id( ) ); parent_->change_hash_checker( new_checker ); parent_->change_hash_maker( new_maker ); setup_transformer( cs.transform( ) ); } bool get_pop_message( gpb::Message &capsule ) { std::string &mess(parent_->message_queue( ).front( )); bool check = check_message_hash(mess); if( !check ) { std::cout << "message bad hash " << parent_->message_queue( ).size( ) << "..."; connection_->close( ); return false; } parse_message( mess, capsule ); pop_message( ); return true; } void call_done( const boost::system::error_code & /*err*/ ) { --current_calls_; } void push_call( lowlevel_unit_sptr llu, common::connection_iface_sptr /*conn*/ ) { parent_->make_call( llu, vtrc::bind(&this_type::call_done, this, _1 )); } void send_busy( lowlevel_unit_type &llu ) { if( llu.opt( ).wait( ) ) { llu.clear_call( ); llu.clear_request( ); llu.clear_response( ); llu.mutable_error( )->set_code( vtrc_errors::ERR_BUSY ); parent_->call_rpc_method( llu ); } } void process_call( lowlevel_unit_sptr &llu ) { if( ++current_calls_ <= maximum_calls_ ) { app_.get_rpc_service( ).post( vtrc::bind( &this_type::push_call, this, llu, connection_->shared_from_this( ))); } else { --current_calls_; send_busy( *llu ); } } void push_event_answer( lowlevel_unit_sptr llu, common::connection_iface_sptr /*conn*/ ) { parent_->push_rpc_message( llu->id( ), llu ); } void process_event_cb( lowlevel_unit_sptr &llu ) { parent_->push_rpc_message( llu->id( ), llu ); } void on_rcp_call_ready( ) { typedef vtrc_rpc_lowlevel::message_info message_info; while( !parent_->message_queue( ).empty( ) ) { lowlevel_unit_sptr llu(vtrc::make_shared<lowlevel_unit_type>()); if(!get_pop_message( *llu )) { std::cout << "bad hash message!\n"; return; } if( llu->has_info( ) ) { switch (llu->info( ).message_type( )) { case message_info::MESSAGE_CALL: process_call( llu ); break; case message_info::MESSAGE_EVENT: case message_info::MESSAGE_CALLBACK: case message_info::MESSAGE_INSERTION_CALL: process_event_cb( llu ); break; default: break; } } } } void parse_message( const std::string &block, gpb::Message &mess ) { parent_->parse_message( block, mess ); } std::string first_message( ) { vtrc_auth::init_capsule cap; vtrc_auth::init_protocol hello_mess; cap.set_text( "Tervetuloa!" ); cap.set_ready( true ); hello_mess.add_hash_supported( vtrc_auth::HASH_NONE ); hello_mess.add_hash_supported( vtrc_auth::HASH_CRC_16 ); hello_mess.add_hash_supported( vtrc_auth::HASH_CRC_32 ); hello_mess.add_hash_supported( vtrc_auth::HASH_CRC_64 ); hello_mess.add_hash_supported( vtrc_auth::HASH_SHA2_256 ); hello_mess.add_transform_supported( vtrc_auth::TRANSFORM_NONE ); hello_mess.add_transform_supported( vtrc_auth::TRANSFORM_ERSEEFOR ); cap.set_body( hello_mess.SerializeAsString( ) ); return cap.SerializeAsString( ); } void init( ) { static const std::string data(first_message( )); connection_->write(data.c_str( ), data.size( )); } void data_ready( ) { stage_function_( ); } }; protocol_layer_s::protocol_layer_s( application &a, common::transport_iface *connection, unsigned maximym_calls, size_t mess_len) :common::protocol_layer(connection, false, mess_len) ,impl_(new impl(a, connection, maximym_calls)) { impl_->parent_ = this; } protocol_layer_s::~protocol_layer_s( ) { delete impl_; } void protocol_layer_s::init( ) { impl_->init( ); } void protocol_layer_s::close( ) { } void protocol_layer_s::on_data_ready( ) { impl_->data_ready( ); } common::rpc_service_wrapper_sptr protocol_layer_s::get_service_by_name( const std::string &name) { return impl_->get_service(name); } }} <commit_msg>proto<commit_after> #include <boost/asio.hpp> #include "vtrc-common/vtrc-mutex-typedefs.h" #include "vtrc-bind.h" #include "vtrc-function.h" #include "vtrc-protocol-layer-s.h" #include "vtrc-monotonic-timer.h" #include "vtrc-data-queue.h" #include "vtrc-hash-iface.h" #include "vtrc-transformer-iface.h" #include "vtrc-transport-iface.h" #include "vtrc-common/vtrc-rpc-service-wrapper.h" #include "vtrc-common/vtrc-exception.h" #include "vtrc-common/vtrc-rpc-controller.h" #include "vtrc-common/vtrc-call-context.h" #include "vtrc-application.h" #include "protocol/vtrc-errors.pb.h" #include "protocol/vtrc-auth.pb.h" #include "protocol/vtrc-rpc-lowlevel.pb.h" #include "vtrc-chrono.h" #include "vtrc-atomic.h" #include "vtrc-common/vtrc-random-device.h" #include "vtrc-common/vtrc-delayed-call.h" namespace vtrc { namespace server { namespace gpb = google::protobuf; namespace bsys = boost::system; namespace basio = boost::asio; namespace { enum init_stage_enum { stage_begin = 1 ,stage_client_select = 2 ,stage_client_ready = 3 }; typedef std::map < std::string, common::rpc_service_wrapper_sptr > service_map; typedef vtrc_rpc_lowlevel::lowlevel_unit lowlevel_unit_type; typedef vtrc::shared_ptr<lowlevel_unit_type> lowlevel_unit_sptr; } namespace data_queue = common::data_queue; struct protocol_layer_s::impl { typedef impl this_type; typedef protocol_layer_s parent_type; application &app_; common::transport_iface *connection_; protocol_layer_s *parent_; bool ready_; service_map services_; shared_mutex services_lock_; std::string client_id_; common::delayed_call keepalive_calls_; typedef vtrc::function<void (void)> stage_function_type; stage_function_type stage_function_; vtrc::atomic<unsigned> current_calls_; const unsigned maximum_calls_; impl( application &a, common::transport_iface *c, unsigned maximum_calls) :app_(a) ,connection_(c) ,ready_(false) ,current_calls_(0) ,maximum_calls_(maximum_calls) ,keepalive_calls_(a.get_io_service( )) { stage_function_ = vtrc::bind( &this_type::on_client_selection, this ); /// client has only 10 seconds for init connection /// todo: think about setting for this timeout value keepalive_calls_.call_from_now( vtrc::bind( &this_type::on_keepavive, this, _1 ), boost::posix_time::seconds( 10 )); } common::rpc_service_wrapper_sptr get_service( const std::string &name ) { upgradable_lock lk( services_lock_ ); common::rpc_service_wrapper_sptr result; service_map::iterator f( services_.find( name ) ); if( f != services_.end( ) ) { result = f->second; } else { result = app_.get_service_by_name( connection_, name ); if( result ) { upgrade_to_unique ulk( lk ); services_.insert( std::make_pair( name, result ) ); } } return result; } bool pop_check_init_message( ) { } void pop_message( ) { parent_->pop_message( ); } void on_keepavive( const boost::system::error_code &error ) { if( !error ) { /// timeout for client init vtrc_auth::init_capsule cap; cap.mutable_error( )->set_code( vtrc_errors::ERR_TIMEOUT ); cap.set_ready( false ); send_and_close( cap ); } } bool check_message_hash( const std::string &mess ) { return parent_->check_message( mess ); } void send_proto_message( const gpb::Message &mess ) { std::string s(mess.SerializeAsString( )); connection_->write( s.c_str( ), s.size( ) ); } void send_proto_message( const gpb::Message &mess, common::closure_type closure, bool on_send) { std::string s(mess.SerializeAsString( )); connection_->write( s.c_str( ), s.size( ), closure, on_send ); } void send_and_close( const gpb::Message &mess ) { send_proto_message( mess, vtrc::bind( &this_type::close_client, this, _1, connection_->shared_from_this( )), true ); } void set_client_ready( ) { keepalive_calls_.cancel( ); stage_function_ = vtrc::bind( &this_type::on_rcp_call_ready, this ); parent_->set_ready( true ); } void close_client( const bsys::error_code & /*err*/, common::connection_iface_sptr /*inst*/) { connection_->close( ); } void on_client_transformer( ) { using namespace common::transformers; vtrc_auth::init_capsule capsule; bool check = get_pop_message( capsule ); if( !check ) { connection_->close( ); return; } if( !capsule.ready( ) ) { connection_->close( ); return; } vtrc_auth::transformer_setup tsetup; tsetup.ParseFromString( capsule.body( ) ); std::string key(app_.get_session_key( connection_, client_id_ )); create_key( key, // input tsetup.salt1( ), // input tsetup.salt2( ), // input key ); // output common::transformer_iface *new_transformer = erseefor::create( key.c_str( ), key.size( ) ); parent_->change_transformer( new_transformer ); capsule.Clear( ); capsule.set_ready( true ); capsule.set_text( "Kiva nahda sinut!" ); set_client_ready( ); send_proto_message( capsule ); } void setup_transformer( unsigned id ) { using namespace common::transformers; vtrc_auth::transformer_setup ts; vtrc_auth::init_capsule capsule; if( id == vtrc_auth::TRANSFORM_NONE ) { capsule.set_ready( true ); capsule.set_text( "Kiva nahda sinut!" ); set_client_ready( ); send_proto_message( capsule ); } else if( id == vtrc_auth::TRANSFORM_ERSEEFOR ) { std::string key(app_.get_session_key(connection_, client_id_)); generate_key_infos( key, // input *ts.mutable_salt1( ), // output *ts.mutable_salt2( ), // output key ); // output common::transformer_iface *new_reverter = erseefor::create( key.c_str( ), key.size( ) ); parent_->change_reverter( new_reverter ); capsule.set_ready( true ); capsule.set_body( ts.SerializeAsString( ) ); stage_function_ = vtrc::bind( &this_type::on_client_transformer, this ); send_proto_message( capsule ); } else { capsule.set_ready( false ); vtrc_errors::container *er(capsule.mutable_error( )); er->set_code( vtrc_errors::ERR_INVALID_VALUE ); er->set_category(vtrc_errors::CATEGORY_INTERNAL); er->set_additional( "Invalid transformer" ); send_and_close( capsule ); return; } } void on_client_selection( ) { vtrc_auth::init_capsule capsule; bool check = get_pop_message( capsule ); if( !check ) { connection_->close( ); return; } if( !capsule.ready( ) ) { connection_->close( ); return; } vtrc_auth::client_selection cs; cs.ParseFromString( capsule.body( ) ); common::hash_iface *new_checker( common::hash::create_by_index( cs.hash( ) ) ); common::hash_iface *new_maker( common::hash::create_by_index( cs.hash( ) ) ); if( !new_maker ) { delete new_checker; } if( !new_maker || !new_checker ) { connection_->close( ); return; } client_id_.assign( cs.id( ) ); parent_->change_hash_checker( new_checker ); parent_->change_hash_maker( new_maker ); setup_transformer( cs.transform( ) ); } bool get_pop_message( gpb::Message &capsule ) { std::string &mess(parent_->message_queue( ).front( )); bool check = check_message_hash(mess); if( !check ) { std::cout << "message bad hash " << parent_->message_queue( ).size( ) << "..."; connection_->close( ); return false; } parse_message( mess, capsule ); pop_message( ); return true; } void call_done( const boost::system::error_code & /*err*/ ) { --current_calls_; } void push_call( lowlevel_unit_sptr llu, common::connection_iface_sptr /*conn*/ ) { parent_->make_call( llu, vtrc::bind(&this_type::call_done, this, _1 )); } void send_busy( lowlevel_unit_type &llu ) { if( llu.opt( ).wait( ) ) { llu.clear_call( ); llu.clear_request( ); llu.clear_response( ); llu.mutable_error( )->set_code( vtrc_errors::ERR_BUSY ); parent_->call_rpc_method( llu ); } } void process_call( lowlevel_unit_sptr &llu ) { if( ++current_calls_ <= maximum_calls_ ) { app_.get_rpc_service( ).post( vtrc::bind( &this_type::push_call, this, llu, connection_->shared_from_this( ))); } else { --current_calls_; send_busy( *llu ); } } void push_event_answer( lowlevel_unit_sptr llu, common::connection_iface_sptr /*conn*/ ) { parent_->push_rpc_message( llu->id( ), llu ); } void process_event_cb( lowlevel_unit_sptr &llu ) { parent_->push_rpc_message( llu->id( ), llu ); } void on_rcp_call_ready( ) { typedef vtrc_rpc_lowlevel::message_info message_info; while( !parent_->message_queue( ).empty( ) ) { lowlevel_unit_sptr llu(vtrc::make_shared<lowlevel_unit_type>()); if(!get_pop_message( *llu )) { std::cout << "bad hash message!\n"; return; } if( llu->has_info( ) ) { switch (llu->info( ).message_type( )) { case message_info::MESSAGE_CALL: process_call( llu ); break; case message_info::MESSAGE_EVENT: case message_info::MESSAGE_CALLBACK: case message_info::MESSAGE_INSERTION_CALL: process_event_cb( llu ); break; default: break; } } } } void parse_message( const std::string &block, gpb::Message &mess ) { parent_->parse_message( block, mess ); } std::string first_message( ) { vtrc_auth::init_capsule cap; vtrc_auth::init_protocol hello_mess; cap.set_text( "Tervetuloa!" ); cap.set_ready( true ); hello_mess.add_hash_supported( vtrc_auth::HASH_NONE ); hello_mess.add_hash_supported( vtrc_auth::HASH_CRC_16 ); hello_mess.add_hash_supported( vtrc_auth::HASH_CRC_32 ); hello_mess.add_hash_supported( vtrc_auth::HASH_CRC_64 ); hello_mess.add_hash_supported( vtrc_auth::HASH_SHA2_256 ); hello_mess.add_transform_supported( vtrc_auth::TRANSFORM_NONE ); hello_mess.add_transform_supported( vtrc_auth::TRANSFORM_ERSEEFOR ); cap.set_body( hello_mess.SerializeAsString( ) ); return cap.SerializeAsString( ); } void init( ) { static const std::string data(first_message( )); connection_->write(data.c_str( ), data.size( )); } void data_ready( ) { stage_function_( ); } }; protocol_layer_s::protocol_layer_s( application &a, common::transport_iface *connection, unsigned maximym_calls, size_t mess_len) :common::protocol_layer(connection, false, mess_len) ,impl_(new impl(a, connection, maximym_calls)) { impl_->parent_ = this; } protocol_layer_s::~protocol_layer_s( ) { delete impl_; } void protocol_layer_s::init( ) { impl_->init( ); } void protocol_layer_s::close( ) { } void protocol_layer_s::on_data_ready( ) { impl_->data_ready( ); } common::rpc_service_wrapper_sptr protocol_layer_s::get_service_by_name( const std::string &name) { return impl_->get_service(name); } }} <|endoftext|>
<commit_before>#ifndef _SMP_SYSTEM_SINGLE_INTEGRATOR_HPP_ #define _SMP_SYSTEM_SINGLE_INTEGRATOR_HPP_ #include <smp/components/extenders/single_integrator.h> #include <smp/components/extenders/state_array_double.hpp> #include <smp/components/extenders/input_array_double.hpp> #include <smp/components/extenders/base.hpp> #include <iostream> #include <cmath> using namespace std; template< class typeparams, int NUM_DIMENSIONS > int smp::extender_single_integrator< typeparams, NUM_DIMENSIONS > ::ex_update_insert_vertex (vertex_t *vertex_in) { return 1; } template< class typeparams, int NUM_DIMENSIONS > int smp::extender_single_integrator< typeparams, NUM_DIMENSIONS > ::ex_update_insert_edge (edge_t *edge_in) { return 1; } template< class typeparams, int NUM_DIMENSIONS > int smp::extender_single_integrator< typeparams, NUM_DIMENSIONS > ::ex_update_delete_vertex (vertex_t *vertex_in){ return 1; } template< class typeparams, int NUM_DIMENSIONS > int smp::extender_single_integrator< typeparams, NUM_DIMENSIONS > ::ex_update_delete_edge (edge_t *edge_in) { return 1; } template< class typeparams, int NUM_DIMENSIONS > smp::extender_single_integrator< typeparams, NUM_DIMENSIONS > ::extender_single_integrator () { max_length = 1.0; } template< class typeparams, int NUM_DIMENSIONS > smp::extender_single_integrator< typeparams, NUM_DIMENSIONS > ::~extender_single_integrator () { } template< class typeparams, int NUM_DIMENSIONS > int smp::extender_single_integrator< typeparams, NUM_DIMENSIONS > ::set_max_length (double max_length_in) { if (max_length_in <= 0.0) return 0; max_length = max_length_in; return 1; } template< class typeparams, int NUM_DIMENSIONS > int smp::extender_single_integrator< typeparams, NUM_DIMENSIONS > ::extend( state_t *state_from_in, state_t *state_towards_in, int *exact_connection_out, trajectory_t *trajectory_out, list<state_t*> *intermediate_vertices_out ) { if (max_length <= 0.0) return 0; trajectory_out->list_states.clear(); trajectory_out->list_inputs.clear(); intermediate_vertices_out->clear(); double dists[NUM_DIMENSIONS]; double dist = 0.0; for (int i = 0; i < NUM_DIMENSIONS; i++) { dists[i] = (*state_towards_in)[i] - (*state_from_in)[i]; dist += dists[i] * dists[i]; } dist = sqrt(dist); state_t *state_new; input_t *input_new = new input_t; if (dist < max_length) { state_new = new state_t (*state_towards_in); (*input_new)[0] = dist; *exact_connection_out = 1; } else { state_new = new state_t; for (int i = 0; i < NUM_DIMENSIONS; i++) (*state_new)[i] = (*state_from_in)[i] + dists[i]/dist*max_length; (*input_new)[0] = max_length; *exact_connection_out = 0; } trajectory_out->list_states.push_back(state_new); trajectory_out->list_inputs.push_back(input_new); return 1; } #endif <commit_msg>TRIV: Improve style and whitespace usage<commit_after>#ifndef _SMP_SYSTEM_SINGLE_INTEGRATOR_HPP_ #define _SMP_SYSTEM_SINGLE_INTEGRATOR_HPP_ #include <smp/components/extenders/single_integrator.h> #include <smp/components/extenders/state_array_double.hpp> #include <smp/components/extenders/input_array_double.hpp> #include <smp/components/extenders/base.hpp> #include <iostream> #include <cmath> using namespace std; template< class typeparams, int NUM_DIMENSIONS > int smp::extender_single_integrator< typeparams, NUM_DIMENSIONS > ::ex_update_insert_vertex (vertex_t *vertex_in) { return 1; } template< class typeparams, int NUM_DIMENSIONS > int smp::extender_single_integrator< typeparams, NUM_DIMENSIONS > ::ex_update_insert_edge (edge_t *edge_in) { return 1; } template< class typeparams, int NUM_DIMENSIONS > int smp::extender_single_integrator< typeparams, NUM_DIMENSIONS > ::ex_update_delete_vertex (vertex_t *vertex_in){ return 1; } template< class typeparams, int NUM_DIMENSIONS > int smp::extender_single_integrator< typeparams, NUM_DIMENSIONS > ::ex_update_delete_edge (edge_t *edge_in) { return 1; } template< class typeparams, int NUM_DIMENSIONS > smp::extender_single_integrator< typeparams, NUM_DIMENSIONS > ::extender_single_integrator () { max_length = 1.0; } template< class typeparams, int NUM_DIMENSIONS > smp::extender_single_integrator< typeparams, NUM_DIMENSIONS > ::~extender_single_integrator () { } template< class typeparams, int NUM_DIMENSIONS > int smp::extender_single_integrator< typeparams, NUM_DIMENSIONS > ::set_max_length (double max_length_in) { if (max_length_in <= 0.0) return 0; max_length = max_length_in; return 1; } template< class typeparams, int NUM_DIMENSIONS > int smp::extender_single_integrator< typeparams, NUM_DIMENSIONS > ::extend( state_t *state_from_in, state_t *state_towards_in, int *exact_connection_out, trajectory_t *trajectory_out, list<state_t*> *intermediate_vertices_out ) { if (max_length <= 0.0) return 0; trajectory_out->list_states.clear(); trajectory_out->list_inputs.clear(); intermediate_vertices_out->clear(); double dists[NUM_DIMENSIONS]; double dist = 0.0; for (int i = 0; i < NUM_DIMENSIONS; i++) { dists[i] = (*state_towards_in)[i] - (*state_from_in)[i]; dist += dists[i] * dists[i]; } dist = sqrt(dist); state_t *state_new; input_t *input_new = new input_t; if (dist < max_length) { state_new = new state_t( *state_towards_in ); (*input_new)[0] = dist; *exact_connection_out = 1; } else { state_new = new state_t; for (int i = 0; i < NUM_DIMENSIONS; i++) (*state_new)[i] = (*state_from_in)[i] + dists[i]/dist*max_length; (*input_new)[0] = max_length; *exact_connection_out = 0; } trajectory_out->list_states.push_back(state_new); trajectory_out->list_inputs.push_back(input_new); return 1; } #endif <|endoftext|>
<commit_before>/* * deinvert - a voice inversion descrambler * Copyright (c) Oona Räisänen * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "src/deinvert.h" #include <getopt.h> #include <iostream> #include <string> #include "config.h" #include "src/liquid_wrappers.h" #include "src/wdsp.h" namespace deinvert { namespace { #ifdef HAVE_LIQUID const int kMaxFilterLength = 2047; int FilterLengthInSamples(float len_seconds, float samplerate) { int filter_length = 2 * std::round(samplerate * len_seconds) + 1; filter_length = filter_length < deinvert::kMaxFilterLength ? filter_length : deinvert::kMaxFilterLength; return filter_length; } #endif } void PrintUsage() { std::cout << "deinvert [OPTIONS]\n" "\n" "-f, --frequency FREQ Frequency of the inversion carrier, in Hertz.\n" "\n" "-h, --help Display this usage help.\n" "\n" "-i, --input-file FILE Use an audio file as input. All formats\n" " supported by libsndfile should work.\n" "\n" "-o, --output-file FILE Write output to a WAV file instead of stdout. An\n" " existing file will be overwritten.\n" "\n" "-p, --preset NUM Scrambler frequency preset (1-8), referring to\n" " the set of common carrier frequencies used by\n" " e.g. the Selectone ST-20B scrambler.\n" "\n" "-q, --quality NUM Filter quality, from 0 (worst and fastest) to\n" " 4 (best and slowest). The default is 2.\n" "\n" "-r, --samplerate RATE Sampling rate of raw input audio, in Hertz.\n" "\n" "-s, --split-frequency Split point for split-band inversion, in Hertz.\n" "\n" "-v, --version Display version string.\n"; } void PrintVersion() { #ifdef DEBUG std::cout << PACKAGE_STRING << "-debug by OH2EIQ" << std::endl; #else std::cout << PACKAGE_STRING << " by OH2EIQ" << std::endl; #endif } Options GetOptions(int argc, char** argv) { deinvert::Options options; static struct option long_options[] = { { "frequency", no_argument, 0, 'f'}, { "preset", 1, 0, 'p'}, { "input-file", 1, 0, 'i'}, { "help", no_argument, 0, 'h'}, { "nofilter", no_argument, 0, 'n'}, { "output-file", 1, 0, 'o'}, { "quality", 1, 0, 'q'}, { "samplerate", 1, 0, 'r'}, { "split-frequency", 1, 0, 's'}, { "version", no_argument, 0, 'v'}, {0, 0, 0, 0}}; static const std::vector<float> selectone_carriers({ 2632.f, 2718.f, 2868.f, 3023.f, 3196.f, 3339.f, 3495.f, 3729.f }); options.frequency_hi = selectone_carriers.at(0); #ifdef HAVE_LIQUID options.quality = 2; #else options.quality = 0; #endif int option_index = 0; int option_char; int selectone_num; while ((option_char = getopt_long(argc, argv, "f:hi:no:p:q:r:s:v", long_options, &option_index)) >= 0) { switch (option_char) { case 'i': #ifdef HAVE_SNDFILE options.infilename = std::string(optarg); options.input_type = deinvert::INPUT_SNDFILE; #else std::cerr << "error: deinvert was compiled without libsndfile" << std::endl; options.just_exit = true; #endif break; case 'f': options.frequency_hi = std::atoi(optarg); break; case 'n': options.quality = 0; break; case 'o': #ifdef HAVE_SNDFILE options.output_type = deinvert::OUTPUT_WAVFILE; options.outfilename = std::string(optarg); #else std::cerr << "error: deinvert was compiled without libsndfile" << std::endl; options.just_exit = true; #endif break; case 'p': selectone_num = std::atoi(optarg); if (selectone_num >= 1 && selectone_num <= 8) { options.frequency_hi = selectone_carriers.at(selectone_num - 1); } else { std::cerr << "error: please specify scrambler group from 1 to 8" << std::endl; options.just_exit = true; } break; case 'q': #ifdef HAVE_LIQUID options.quality = std::atoi(optarg); if (options.quality < 0 || options.quality > 4) { std::cerr << "error: please specify filter quality from 0 to 4" << std::endl; options.just_exit = true; } #else std::cerr << "warning: deinvert was built without liquid-dsp, " << "filtering disabled" << std::endl; #endif break; case 'r': options.samplerate = std::atoi(optarg); if (options.samplerate < 6000.f) { std::cerr << "error: sample rate must be 6000 Hz or higher" << std::endl; options.just_exit = true; } break; case 's': options.frequency_lo = std::atoi(optarg); options.is_split_band = true; break; case 'v': PrintVersion(); options.just_exit = true; break; case 'h': default: PrintUsage(); options.just_exit = true; break; } if (options.just_exit) break; } if (options.is_split_band && options.frequency_lo >= options.frequency_hi) { std::cerr << "error: split point should be below the inversion carrier" << std::endl; options.just_exit = true; } return options; } AudioReader::~AudioReader() { } bool AudioReader::eof() const { return is_eof_; } StdinReader::StdinReader(const Options& options) : samplerate_(options.samplerate) { is_eof_ = false; } StdinReader::~StdinReader() { } std::vector<float> StdinReader::ReadBlock() { int num_read = fread(buffer_, sizeof(buffer_[0]), kIOBufferSize, stdin); if (num_read < kIOBufferSize) is_eof_ = true; std::vector<float> result(num_read); for (int i = 0; i < num_read; i++) result[i] = buffer_[i] * (1.f / 32768.f); return result; } float StdinReader::samplerate() const { return samplerate_; } #ifdef HAVE_SNDFILE SndfileReader::SndfileReader(const Options& options) : info_({0, 0, 0, 0, 0, 0}), file_(sf_open(options.infilename.c_str(), SFM_READ, &info_)) { is_eof_ = false; if (file_ == nullptr) { std::cerr << options.infilename << ": " << sf_strerror(nullptr) << std::endl; is_eof_ = true; } else if (info_.samplerate < 6000.f) { std::cerr << "error: sample rate must be 6000 Hz or higher" << std::endl; is_eof_ = true; } } SndfileReader::~SndfileReader() { sf_close(file_); } std::vector<float> SndfileReader::ReadBlock() { std::vector<float> result; if (is_eof_) return result; int to_read = kIOBufferSize / info_.channels; sf_count_t num_read = sf_readf_float(file_, buffer_, to_read); if (num_read != to_read) is_eof_ = true; if (info_.channels == 1) { result = std::vector<float>(buffer_, buffer_ + num_read); } else { result = std::vector<float>(num_read); for (size_t i = 0; i < result.size(); i++) result[i] = buffer_[i * info_.channels]; } return result; } float SndfileReader::samplerate() const { return info_.samplerate; } #endif AudioWriter::~AudioWriter() { } RawPCMWriter::RawPCMWriter() : buffer_pos_(0) { } bool RawPCMWriter::push(float sample) { int16_t outsample = sample * 32767.f; buffer_[buffer_pos_] = outsample; buffer_pos_++; if (buffer_pos_ == kIOBufferSize) { fwrite(buffer_, sizeof(buffer_[0]), kIOBufferSize, stdout); buffer_pos_ = 0; } return true; } #ifdef HAVE_SNDFILE SndfileWriter::SndfileWriter(const std::string& fname, int rate) : info_({0, rate, 1, SF_FORMAT_WAV | SF_FORMAT_PCM_16, 0, 0}), file_(sf_open(fname.c_str(), SFM_WRITE, &info_)), buffer_pos_(0) { if (file_ == nullptr) { std::cerr << fname << ": " << sf_strerror(nullptr) << std::endl; } } SndfileWriter::~SndfileWriter() { write(); sf_close(file_); } bool SndfileWriter::push(float sample) { bool success = true; buffer_[buffer_pos_] = sample; if (buffer_pos_ == kIOBufferSize - 1) { success = write(); } buffer_pos_ = (buffer_pos_ + 1) % kIOBufferSize; return success; } bool SndfileWriter::write() { sf_count_t num_to_write = buffer_pos_ + 1; return (file_ != nullptr && sf_write_float(file_, buffer_, num_to_write) == num_to_write); } #endif Inverter::Inverter(float freq_prefilter, float freq_shift, float freq_postfilter, float samplerate, int quality) : #ifdef HAVE_LIQUID filter_lengths_({0.f, 0.0006f, 0.0024f, 0.0064f, 0.0128f}), filter_attenuation_({60.f, 60.f, 60.f, 80.f, 80.f}), prefilter_(FilterLengthInSamples(filter_lengths_.at(quality), samplerate), freq_prefilter / samplerate, filter_attenuation_.at(quality)), postfilter_(FilterLengthInSamples(filter_lengths_.at(quality), samplerate), freq_postfilter / samplerate, filter_attenuation_.at(quality)), oscillator_(LIQUID_VCO, freq_shift * 2.0f * M_PI / samplerate), do_filter_(quality > 0) #else oscillator_(freq_shift * 2.0f * M_PI / samplerate), do_filter_(false) #endif {} float Inverter::execute(float insample) { oscillator_.Step(); float result; #ifdef HAVE_LIQUID if (do_filter_) { prefilter_.push(insample); postfilter_.push(oscillator_.MixUp(prefilter_.execute()).real()); result = postfilter_.execute(); } else { result = oscillator_.MixUp({insample, 0.0f}).real(); } #else result = oscillator_.MixUp({insample, 0.0f}).real(); #endif return result; } } // namespace deinvert int main(int argc, char** argv) { deinvert::Options options = deinvert::GetOptions(argc, argv); if (options.just_exit) return EXIT_FAILURE; deinvert::AudioReader* reader; deinvert::AudioWriter* writer; if (options.input_type == deinvert::INPUT_SNDFILE) { #ifdef HAVE_SNDFILE reader = new deinvert::SndfileReader(options); options.samplerate = reader->samplerate(); #endif } else { reader = new deinvert::StdinReader(options); } #ifdef HAVE_SNDFILE if (options.output_type == deinvert::OUTPUT_WAVFILE) writer = new deinvert::SndfileWriter(options.outfilename, options.samplerate); else #endif writer = new deinvert::RawPCMWriter(); if (options.is_split_band) { static const std::vector<float> filter_gain_compensation({ 0.5f, 1.4f, 1.8f, 1.8f, 1.8f }); float gain = filter_gain_compensation.at(options.quality); deinvert::Inverter inverter1(options.frequency_lo, options.frequency_lo, options.frequency_lo, options.samplerate, options.quality); deinvert::Inverter inverter2(options.frequency_hi, options.frequency_lo + options.frequency_hi, options.frequency_hi, options.samplerate, options.quality); while (!reader->eof()) { for (float insample : reader->ReadBlock()) { bool can_still_write = writer->push(gain * (inverter1.execute(insample) + inverter2.execute(insample))); if (!can_still_write) continue; } } } else { static const std::vector<float> filter_gain_compensation({ 1.0f, 1.4f, 1.8f, 1.8f, 1.8f }); float gain = filter_gain_compensation.at(options.quality); deinvert::Inverter inverter(options.frequency_hi, options.frequency_hi, options.frequency_hi, options.samplerate, options.quality); while (!reader->eof()) { for (float insample : reader->ReadBlock()) { bool can_still_write = writer->push(gain * inverter.execute(insample)); if (!can_still_write) continue; } } } delete reader; delete writer; } <commit_msg>revert, the filter works better now<commit_after>/* * deinvert - a voice inversion descrambler * Copyright (c) Oona Räisänen * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "src/deinvert.h" #include <getopt.h> #include <iostream> #include <string> #include "config.h" #include "src/liquid_wrappers.h" #include "src/wdsp.h" namespace deinvert { namespace { #ifdef HAVE_LIQUID const int kMaxFilterLength = 2047; int FilterLengthInSamples(float len_seconds, float samplerate) { int filter_length = 2 * std::round(samplerate * len_seconds) + 1; filter_length = filter_length < deinvert::kMaxFilterLength ? filter_length : deinvert::kMaxFilterLength; return filter_length; } #endif } void PrintUsage() { std::cout << "deinvert [OPTIONS]\n" "\n" "-f, --frequency FREQ Frequency of the inversion carrier, in Hertz.\n" "\n" "-h, --help Display this usage help.\n" "\n" "-i, --input-file FILE Use an audio file as input. All formats\n" " supported by libsndfile should work.\n" "\n" "-o, --output-file FILE Write output to a WAV file instead of stdout. An\n" " existing file will be overwritten.\n" "\n" "-p, --preset NUM Scrambler frequency preset (1-8), referring to\n" " the set of common carrier frequencies used by\n" " e.g. the Selectone ST-20B scrambler.\n" "\n" "-q, --quality NUM Filter quality, from 0 (worst and fastest) to\n" " 3 (best and slowest). The default is 2.\n" "\n" "-r, --samplerate RATE Sampling rate of raw input audio, in Hertz.\n" "\n" "-s, --split-frequency Split point for split-band inversion, in Hertz.\n" "\n" "-v, --version Display version string.\n"; } void PrintVersion() { #ifdef DEBUG std::cout << PACKAGE_STRING << "-debug by OH2EIQ" << std::endl; #else std::cout << PACKAGE_STRING << " by OH2EIQ" << std::endl; #endif } Options GetOptions(int argc, char** argv) { deinvert::Options options; static struct option long_options[] = { { "frequency", no_argument, 0, 'f'}, { "preset", 1, 0, 'p'}, { "input-file", 1, 0, 'i'}, { "help", no_argument, 0, 'h'}, { "nofilter", no_argument, 0, 'n'}, { "output-file", 1, 0, 'o'}, { "quality", 1, 0, 'q'}, { "samplerate", 1, 0, 'r'}, { "split-frequency", 1, 0, 's'}, { "version", no_argument, 0, 'v'}, {0, 0, 0, 0}}; static const std::vector<float> selectone_carriers({ 2632.f, 2718.f, 2868.f, 3023.f, 3196.f, 3339.f, 3495.f, 3729.f }); options.frequency_hi = selectone_carriers.at(0); #ifdef HAVE_LIQUID options.quality = 2; #else options.quality = 0; #endif int option_index = 0; int option_char; int selectone_num; while ((option_char = getopt_long(argc, argv, "f:hi:no:p:q:r:s:v", long_options, &option_index)) >= 0) { switch (option_char) { case 'i': #ifdef HAVE_SNDFILE options.infilename = std::string(optarg); options.input_type = deinvert::INPUT_SNDFILE; #else std::cerr << "error: deinvert was compiled without libsndfile" << std::endl; options.just_exit = true; #endif break; case 'f': options.frequency_hi = std::atoi(optarg); break; case 'n': options.quality = 0; break; case 'o': #ifdef HAVE_SNDFILE options.output_type = deinvert::OUTPUT_WAVFILE; options.outfilename = std::string(optarg); #else std::cerr << "error: deinvert was compiled without libsndfile" << std::endl; options.just_exit = true; #endif break; case 'p': selectone_num = std::atoi(optarg); if (selectone_num >= 1 && selectone_num <= 8) { options.frequency_hi = selectone_carriers.at(selectone_num - 1); } else { std::cerr << "error: please specify scrambler group from 1 to 8" << std::endl; options.just_exit = true; } break; case 'q': #ifdef HAVE_LIQUID options.quality = std::atoi(optarg); if (options.quality < 0 || options.quality > 3) { std::cerr << "error: please specify filter quality from 0 to 3" << std::endl; options.just_exit = true; } #else std::cerr << "warning: deinvert was built without liquid-dsp, " << "filtering disabled" << std::endl; #endif break; case 'r': options.samplerate = std::atoi(optarg); if (options.samplerate < 6000.f) { std::cerr << "error: sample rate must be 6000 Hz or higher" << std::endl; options.just_exit = true; } break; case 's': options.frequency_lo = std::atoi(optarg); options.is_split_band = true; break; case 'v': PrintVersion(); options.just_exit = true; break; case 'h': default: PrintUsage(); options.just_exit = true; break; } if (options.just_exit) break; } if (options.is_split_band && options.frequency_lo >= options.frequency_hi) { std::cerr << "error: split point should be below the inversion carrier" << std::endl; options.just_exit = true; } return options; } AudioReader::~AudioReader() { } bool AudioReader::eof() const { return is_eof_; } StdinReader::StdinReader(const Options& options) : samplerate_(options.samplerate) { is_eof_ = false; } StdinReader::~StdinReader() { } std::vector<float> StdinReader::ReadBlock() { int num_read = fread(buffer_, sizeof(buffer_[0]), kIOBufferSize, stdin); if (num_read < kIOBufferSize) is_eof_ = true; std::vector<float> result(num_read); for (int i = 0; i < num_read; i++) result[i] = buffer_[i] * (1.f / 32768.f); return result; } float StdinReader::samplerate() const { return samplerate_; } #ifdef HAVE_SNDFILE SndfileReader::SndfileReader(const Options& options) : info_({0, 0, 0, 0, 0, 0}), file_(sf_open(options.infilename.c_str(), SFM_READ, &info_)) { is_eof_ = false; if (file_ == nullptr) { std::cerr << options.infilename << ": " << sf_strerror(nullptr) << std::endl; is_eof_ = true; } else if (info_.samplerate < 6000.f) { std::cerr << "error: sample rate must be 6000 Hz or higher" << std::endl; is_eof_ = true; } } SndfileReader::~SndfileReader() { sf_close(file_); } std::vector<float> SndfileReader::ReadBlock() { std::vector<float> result; if (is_eof_) return result; int to_read = kIOBufferSize / info_.channels; sf_count_t num_read = sf_readf_float(file_, buffer_, to_read); if (num_read != to_read) is_eof_ = true; if (info_.channels == 1) { result = std::vector<float>(buffer_, buffer_ + num_read); } else { result = std::vector<float>(num_read); for (size_t i = 0; i < result.size(); i++) result[i] = buffer_[i * info_.channels]; } return result; } float SndfileReader::samplerate() const { return info_.samplerate; } #endif AudioWriter::~AudioWriter() { } RawPCMWriter::RawPCMWriter() : buffer_pos_(0) { } bool RawPCMWriter::push(float sample) { int16_t outsample = sample * 32767.f; buffer_[buffer_pos_] = outsample; buffer_pos_++; if (buffer_pos_ == kIOBufferSize) { fwrite(buffer_, sizeof(buffer_[0]), kIOBufferSize, stdout); buffer_pos_ = 0; } return true; } #ifdef HAVE_SNDFILE SndfileWriter::SndfileWriter(const std::string& fname, int rate) : info_({0, rate, 1, SF_FORMAT_WAV | SF_FORMAT_PCM_16, 0, 0}), file_(sf_open(fname.c_str(), SFM_WRITE, &info_)), buffer_pos_(0) { if (file_ == nullptr) { std::cerr << fname << ": " << sf_strerror(nullptr) << std::endl; } } SndfileWriter::~SndfileWriter() { write(); sf_close(file_); } bool SndfileWriter::push(float sample) { bool success = true; buffer_[buffer_pos_] = sample; if (buffer_pos_ == kIOBufferSize - 1) { success = write(); } buffer_pos_ = (buffer_pos_ + 1) % kIOBufferSize; return success; } bool SndfileWriter::write() { sf_count_t num_to_write = buffer_pos_ + 1; return (file_ != nullptr && sf_write_float(file_, buffer_, num_to_write) == num_to_write); } #endif Inverter::Inverter(float freq_prefilter, float freq_shift, float freq_postfilter, float samplerate, int quality) : #ifdef HAVE_LIQUID filter_lengths_({0.f, 0.0006f, 0.0024f, 0.0064f}), filter_attenuation_({60.f, 60.f, 60.f, 80.f}), prefilter_(FilterLengthInSamples(filter_lengths_.at(quality), samplerate), freq_prefilter / samplerate, filter_attenuation_.at(quality)), postfilter_(FilterLengthInSamples(filter_lengths_.at(quality), samplerate), freq_postfilter / samplerate, filter_attenuation_.at(quality)), oscillator_(LIQUID_VCO, freq_shift * 2.0f * M_PI / samplerate), do_filter_(quality > 0) #else oscillator_(freq_shift * 2.0f * M_PI / samplerate), do_filter_(false) #endif {} float Inverter::execute(float insample) { oscillator_.Step(); float result; #ifdef HAVE_LIQUID if (do_filter_) { prefilter_.push(insample); postfilter_.push(oscillator_.MixUp(prefilter_.execute()).real()); result = postfilter_.execute(); } else { result = oscillator_.MixUp({insample, 0.0f}).real(); } #else result = oscillator_.MixUp({insample, 0.0f}).real(); #endif return result; } } // namespace deinvert int main(int argc, char** argv) { deinvert::Options options = deinvert::GetOptions(argc, argv); if (options.just_exit) return EXIT_FAILURE; deinvert::AudioReader* reader; deinvert::AudioWriter* writer; if (options.input_type == deinvert::INPUT_SNDFILE) { #ifdef HAVE_SNDFILE reader = new deinvert::SndfileReader(options); options.samplerate = reader->samplerate(); #endif } else { reader = new deinvert::StdinReader(options); } #ifdef HAVE_SNDFILE if (options.output_type == deinvert::OUTPUT_WAVFILE) writer = new deinvert::SndfileWriter(options.outfilename, options.samplerate); else #endif writer = new deinvert::RawPCMWriter(); if (options.is_split_band) { static const std::vector<float> filter_gain_compensation({ 0.5f, 1.4f, 1.8f, 1.8f }); float gain = filter_gain_compensation.at(options.quality); deinvert::Inverter inverter1(options.frequency_lo, options.frequency_lo, options.frequency_lo, options.samplerate, options.quality); deinvert::Inverter inverter2(options.frequency_hi, options.frequency_lo + options.frequency_hi, options.frequency_hi, options.samplerate, options.quality); while (!reader->eof()) { for (float insample : reader->ReadBlock()) { bool can_still_write = writer->push(gain * (inverter1.execute(insample) + inverter2.execute(insample))); if (!can_still_write) continue; } } } else { static const std::vector<float> filter_gain_compensation({ 1.0f, 1.4f, 1.8f, 1.8f }); float gain = filter_gain_compensation.at(options.quality); deinvert::Inverter inverter(options.frequency_hi, options.frequency_hi, options.frequency_hi, options.samplerate, options.quality); while (!reader->eof()) { for (float insample : reader->ReadBlock()) { bool can_still_write = writer->push(gain * inverter.execute(insample)); if (!can_still_write) continue; } } } delete reader; delete writer; } <|endoftext|>
<commit_before>#include "df_font.h" #include "df_bitmap.h" #include "df_common.h" #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <limits.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> // **************************************************************************** // Glyph // **************************************************************************** typedef struct { unsigned startX; unsigned startY; unsigned runLen; } EncodedRun; class Glyph { public: unsigned m_width; int m_numRuns; EncodedRun *m_pixelRuns; Glyph(int w) { m_width = w; } }; // **************************************************************************** // Global variables // **************************************************************************** DfFont *g_defaultFont = NULL; // **************************************************************************** // Public Functions // **************************************************************************** static bool GetPixelFromBuffer(unsigned *buf, int w, int h, int x, int y) { return buf[(h - y - 1) * w + x] > 0; } DfFont *FontCreate(char const *fontName, int size, int weight) { if (size < 4 || size > 1000 || weight < 1 || weight > 9) return NULL; DfFont *tr = new DfFont; memset(tr, 0, sizeof(DfFont)); // Get the font from GDI HDC winDC = CreateDC("DISPLAY", NULL, NULL, NULL); HDC memDC = CreateCompatibleDC(winDC); int scaledSize = -MulDiv(size, GetDeviceCaps(memDC, LOGPIXELSY), 72); HFONT fontHandle = CreateFont(scaledSize, 0, 0, 0, weight * 100, false, false, false, ANSI_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, NONANTIALIASED_QUALITY, DEFAULT_PITCH, fontName); ReleaseAssert(fontHandle != NULL, "Couldn't find Windows font '%s'", fontName); // Ask GDI about the font size and fixed-widthness SelectObject(memDC, fontHandle); TEXTMETRIC textMetrics; GetTextMetrics(memDC, &textMetrics); tr->charHeight = textMetrics.tmHeight; tr->maxCharWidth = textMetrics.tmMaxCharWidth; tr->fixedWidth = (textMetrics.tmAveCharWidth == textMetrics.tmMaxCharWidth); // Ask GDI about the name of the font char nameOfFontWeGot[256]; GetTextFace(memDC, 256, nameOfFontWeGot); ReleaseWarn(strncasecmp(nameOfFontWeGot, fontName, 255) == 0, "Attempt to load font '%s' failed.\n" "'%s' will be used instead.", fontName, nameOfFontWeGot); // Create an off-screen bitmap BITMAPINFO bmpInfo = { 0 }; bmpInfo.bmiHeader.biBitCount = 32; bmpInfo.bmiHeader.biHeight = tr->charHeight; bmpInfo.bmiHeader.biWidth = tr->maxCharWidth; bmpInfo.bmiHeader.biPlanes = 1; bmpInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); UINT *gdiPixels = 0; HBITMAP memBmp = CreateDIBSection(memDC, (BITMAPINFO *)&bmpInfo, DIB_RGB_COLORS, (void **)&gdiPixels, NULL, 0); HBITMAP prevBmp = (HBITMAP)SelectObject(memDC, memBmp); // Allocate enough EncodedRuns to store the worst case for a glyph of this size. // Worst case is if the whole glyph is encoded as runs of one pixel. There has // to be a gap of one pixel between each run, so there can only be half as many // runs as there are pixels. unsigned tempRunsSize = tr->charHeight * (tr->maxCharWidth / 2 + 1); EncodedRun *tempRuns = new EncodedRun [tempRunsSize]; // Setup stuff needed to render text with GDI SetTextColor(memDC, RGB(255,255,255)); SetBkColor(memDC, 0); RECT rect = { 0, 0, tr->maxCharWidth, tr->charHeight }; // Run-length encode each ASCII character for (int i = 0; i < 256; i++) { char buf[] = {(char)i}; // Get the size of this glyph SIZE glyphSize; GetTextExtentPoint32(memDC, buf, 1, &glyphSize); // if (glyphSize.cx > tr->maxCharWidth) // tr->maxCharWidth = glyphSize.cx; // if (glyphSize.cy > tr->charHeight) // tr->charHeight = glyphSize.cy; // Ask GDI to draw the character ExtTextOut(memDC, 0, 0, ETO_OPAQUE, &rect, buf, 1, 0); // Read back what GDI put in the bitmap and construct a run-length encoding memset(tempRuns, 0, tempRunsSize); EncodedRun *run = tempRuns; for (int y = 0; y < tr->charHeight; y++) { int x = 0; while (x < tr->maxCharWidth) { // Skip blank pixels while (!GetPixelFromBuffer(gdiPixels, tr->maxCharWidth, tr->charHeight, x, y)) { x++; if (x >= tr->maxCharWidth) break; } // Have we got to the end of the line? if (x >= tr->maxCharWidth) continue; run->startX = x; run->startY = y; run->runLen = 0; // Count non-blank pixels while (GetPixelFromBuffer(gdiPixels, tr->maxCharWidth, tr->charHeight, x, y)) { x++; run->runLen++; if (x >= tr->maxCharWidth) break; } run++; } } // Create the glyph to store the encoded runs we've made Glyph *glyph = new Glyph(glyphSize.cx); tr->glyphs[i] = glyph; // Copy the runs into the glyph glyph->m_numRuns = run - tempRuns; glyph->m_pixelRuns = new EncodedRun [glyph->m_numRuns]; memcpy(glyph->m_pixelRuns, tempRuns, glyph->m_numRuns * sizeof(EncodedRun)); } delete [] tempRuns; // Release the GDI resources DeleteDC(winDC); DeleteDC(memDC); DeleteObject(fontHandle); DeleteObject(memBmp); DeleteObject(prevBmp); return tr; } static int DrawTextSimpleClipped(DfFont *tr, DfColour col, DfBitmap *bmp, int _x, int y, char const *text, int maxChars) { int x = _x; DfColour *startRow = bmp->pixels + y * bmp->width; int width = bmp->width; if (y + tr->charHeight < bmp->clipTop || y > bmp->clipBottom) return 0; for (int j = 0; text[j] && j < maxChars; j++) { if (x > bmp->clipRight) break; unsigned char c = text[j]; Glyph *glyph = tr->glyphs[c]; EncodedRun *rleBuf = glyph->m_pixelRuns; for (int i = 0; i < glyph->m_numRuns; i++) { int y3 = y + rleBuf->startY; if (y3 >= bmp->clipTop && y3 < bmp->clipBottom) { DfColour *thisRow = startRow + rleBuf->startY * width; for (unsigned i = 0; i < rleBuf->runLen; i++) { int x3 = x + rleBuf->startX + i; if (x3 >= bmp->clipLeft && x3 < bmp->clipRight) thisRow[x3] = col; } } rleBuf++; } x += glyph->m_width; } return x - _x; } int DrawTextSimpleLen(DfFont *tr, DfColour col, DfBitmap *bmp, int _x, int y, char const *text, int maxChars) { int x = _x; int width = bmp->width; if (x < bmp->clipLeft || y < bmp->clipTop || (y + tr->charHeight) > bmp->clipBottom) return DrawTextSimpleClipped(tr, col, bmp, _x, y, text, maxChars); DfColour *startRow = bmp->pixels + y * bmp->width; for (int j = 0; text[j] && j < maxChars; j++) { unsigned char c = text[j]; if (x + (int)tr->glyphs[c]->m_width > bmp->clipRight) break; // Copy the glyph onto the stack for better cache performance. This increased the // performance from 13.8 to 14.4 million chars per second. Madness. Glyph glyph = *tr->glyphs[c]; EncodedRun *rleBuf = glyph.m_pixelRuns; for (int i = 0; i < glyph.m_numRuns; i++) { DfColour *startPixel = startRow + rleBuf->startY * width + rleBuf->startX + x; for (unsigned i = 0; i < rleBuf->runLen; i++) startPixel[i] = col; rleBuf++; } x += glyph.m_width; } return x - _x; } int DrawTextSimple(DfFont *f, DfColour col, DfBitmap *bmp, int x, int y, char const *text) { return DrawTextSimpleLen(f, col, bmp, x, y, text, 9999); } int DrawTextLeft(DfFont *tr, DfColour c, DfBitmap *bmp, int x, int y, char const *text, ...) { char buf[512]; va_list ap; va_start(ap, text); vsprintf(buf, text, ap); return DrawTextSimple(tr, c, bmp, x, y, buf); } int DrawTextRight(DfFont *tr, DfColour c, DfBitmap *bmp, int x, int y, char const *text, ...) { char buf[512]; va_list ap; va_start(ap, text); vsprintf(buf, text, ap); int width = GetTextWidth(tr, buf); return DrawTextSimple(tr, c, bmp, x - width, y, buf); } int DrawTextCentre(DfFont *tr, DfColour c, DfBitmap *bmp, int x, int y, char const *text, ...) { char buf[512]; va_list ap; va_start(ap, text); vsprintf(buf, text, ap); int width = GetTextWidth(tr, buf); return DrawTextSimple(tr, c, bmp, x - width/2, y, buf); } int GetTextWidth(DfFont *tr, char const *text, int len) { len = IntMin((int)strlen(text), len); if (tr->fixedWidth) { return len * tr->maxCharWidth; } else { int width = 0; for (int i = 0; i < len; i++) width += tr->glyphs[(int)text[i]]->m_width; return width; } } <commit_msg>Bug fix: GetTextWidth() failed and maybe crashed if the string passed in contained a character with an ASCII value greater than 127.<commit_after>#include "df_font.h" #include "df_bitmap.h" #include "df_common.h" #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <limits.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> // **************************************************************************** // Glyph // **************************************************************************** typedef struct { unsigned startX; unsigned startY; unsigned runLen; } EncodedRun; class Glyph { public: unsigned m_width; int m_numRuns; EncodedRun *m_pixelRuns; Glyph(int w) { m_width = w; } }; // **************************************************************************** // Global variables // **************************************************************************** DfFont *g_defaultFont = NULL; // **************************************************************************** // Public Functions // **************************************************************************** static bool GetPixelFromBuffer(unsigned *buf, int w, int h, int x, int y) { return buf[(h - y - 1) * w + x] > 0; } DfFont *FontCreate(char const *fontName, int size, int weight) { if (size < 4 || size > 1000 || weight < 1 || weight > 9) return NULL; DfFont *tr = new DfFont; memset(tr, 0, sizeof(DfFont)); // Get the font from GDI HDC winDC = CreateDC("DISPLAY", NULL, NULL, NULL); HDC memDC = CreateCompatibleDC(winDC); int scaledSize = -MulDiv(size, GetDeviceCaps(memDC, LOGPIXELSY), 72); HFONT fontHandle = CreateFont(scaledSize, 0, 0, 0, weight * 100, false, false, false, ANSI_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, NONANTIALIASED_QUALITY, DEFAULT_PITCH, fontName); ReleaseAssert(fontHandle != NULL, "Couldn't find Windows font '%s'", fontName); // Ask GDI about the font size and fixed-widthness SelectObject(memDC, fontHandle); TEXTMETRIC textMetrics; GetTextMetrics(memDC, &textMetrics); tr->charHeight = textMetrics.tmHeight; tr->maxCharWidth = textMetrics.tmMaxCharWidth; tr->fixedWidth = (textMetrics.tmAveCharWidth == textMetrics.tmMaxCharWidth); // Ask GDI about the name of the font char nameOfFontWeGot[256]; GetTextFace(memDC, 256, nameOfFontWeGot); ReleaseWarn(strncasecmp(nameOfFontWeGot, fontName, 255) == 0, "Attempt to load font '%s' failed.\n" "'%s' will be used instead.", fontName, nameOfFontWeGot); // Create an off-screen bitmap BITMAPINFO bmpInfo = { 0 }; bmpInfo.bmiHeader.biBitCount = 32; bmpInfo.bmiHeader.biHeight = tr->charHeight; bmpInfo.bmiHeader.biWidth = tr->maxCharWidth; bmpInfo.bmiHeader.biPlanes = 1; bmpInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); UINT *gdiPixels = 0; HBITMAP memBmp = CreateDIBSection(memDC, (BITMAPINFO *)&bmpInfo, DIB_RGB_COLORS, (void **)&gdiPixels, NULL, 0); HBITMAP prevBmp = (HBITMAP)SelectObject(memDC, memBmp); // Allocate enough EncodedRuns to store the worst case for a glyph of this size. // Worst case is if the whole glyph is encoded as runs of one pixel. There has // to be a gap of one pixel between each run, so there can only be half as many // runs as there are pixels. unsigned tempRunsSize = tr->charHeight * (tr->maxCharWidth / 2 + 1); EncodedRun *tempRuns = new EncodedRun [tempRunsSize]; // Setup stuff needed to render text with GDI SetTextColor(memDC, RGB(255,255,255)); SetBkColor(memDC, 0); RECT rect = { 0, 0, tr->maxCharWidth, tr->charHeight }; // Run-length encode each ASCII character for (int i = 0; i < 256; i++) { char buf[] = {(char)i}; // Get the size of this glyph SIZE glyphSize; GetTextExtentPoint32(memDC, buf, 1, &glyphSize); // if (glyphSize.cx > tr->maxCharWidth) // tr->maxCharWidth = glyphSize.cx; // if (glyphSize.cy > tr->charHeight) // tr->charHeight = glyphSize.cy; // Ask GDI to draw the character ExtTextOut(memDC, 0, 0, ETO_OPAQUE, &rect, buf, 1, 0); // Read back what GDI put in the bitmap and construct a run-length encoding memset(tempRuns, 0, tempRunsSize); EncodedRun *run = tempRuns; for (int y = 0; y < tr->charHeight; y++) { int x = 0; while (x < tr->maxCharWidth) { // Skip blank pixels while (!GetPixelFromBuffer(gdiPixels, tr->maxCharWidth, tr->charHeight, x, y)) { x++; if (x >= tr->maxCharWidth) break; } // Have we got to the end of the line? if (x >= tr->maxCharWidth) continue; run->startX = x; run->startY = y; run->runLen = 0; // Count non-blank pixels while (GetPixelFromBuffer(gdiPixels, tr->maxCharWidth, tr->charHeight, x, y)) { x++; run->runLen++; if (x >= tr->maxCharWidth) break; } run++; } } // Create the glyph to store the encoded runs we've made Glyph *glyph = new Glyph(glyphSize.cx); tr->glyphs[i] = glyph; // Copy the runs into the glyph glyph->m_numRuns = run - tempRuns; glyph->m_pixelRuns = new EncodedRun [glyph->m_numRuns]; memcpy(glyph->m_pixelRuns, tempRuns, glyph->m_numRuns * sizeof(EncodedRun)); } delete [] tempRuns; // Release the GDI resources DeleteDC(winDC); DeleteDC(memDC); DeleteObject(fontHandle); DeleteObject(memBmp); DeleteObject(prevBmp); return tr; } static int DrawTextSimpleClipped(DfFont *tr, DfColour col, DfBitmap *bmp, int _x, int y, char const *text, int maxChars) { int x = _x; DfColour *startRow = bmp->pixels + y * bmp->width; int width = bmp->width; if (y + tr->charHeight < bmp->clipTop || y > bmp->clipBottom) return 0; for (int j = 0; text[j] && j < maxChars; j++) { if (x > bmp->clipRight) break; unsigned char c = text[j]; Glyph *glyph = tr->glyphs[c]; EncodedRun *rleBuf = glyph->m_pixelRuns; for (int i = 0; i < glyph->m_numRuns; i++) { int y3 = y + rleBuf->startY; if (y3 >= bmp->clipTop && y3 < bmp->clipBottom) { DfColour *thisRow = startRow + rleBuf->startY * width; for (unsigned i = 0; i < rleBuf->runLen; i++) { int x3 = x + rleBuf->startX + i; if (x3 >= bmp->clipLeft && x3 < bmp->clipRight) thisRow[x3] = col; } } rleBuf++; } x += glyph->m_width; } return x - _x; } int DrawTextSimpleLen(DfFont *tr, DfColour col, DfBitmap *bmp, int _x, int y, char const *text, int maxChars) { int x = _x; int width = bmp->width; if (x < bmp->clipLeft || y < bmp->clipTop || (y + tr->charHeight) > bmp->clipBottom) return DrawTextSimpleClipped(tr, col, bmp, _x, y, text, maxChars); DfColour *startRow = bmp->pixels + y * bmp->width; for (int j = 0; text[j] && j < maxChars; j++) { unsigned char c = text[j]; if (x + (int)tr->glyphs[c]->m_width > bmp->clipRight) break; // Copy the glyph onto the stack for better cache performance. This increased the // performance from 13.8 to 14.4 million chars per second. Madness. Glyph glyph = *tr->glyphs[c]; EncodedRun *rleBuf = glyph.m_pixelRuns; for (int i = 0; i < glyph.m_numRuns; i++) { DfColour *startPixel = startRow + rleBuf->startY * width + rleBuf->startX + x; for (unsigned i = 0; i < rleBuf->runLen; i++) startPixel[i] = col; rleBuf++; } x += glyph.m_width; } return x - _x; } int DrawTextSimple(DfFont *f, DfColour col, DfBitmap *bmp, int x, int y, char const *text) { return DrawTextSimpleLen(f, col, bmp, x, y, text, 9999); } int DrawTextLeft(DfFont *tr, DfColour c, DfBitmap *bmp, int x, int y, char const *text, ...) { char buf[512]; va_list ap; va_start(ap, text); vsprintf(buf, text, ap); return DrawTextSimple(tr, c, bmp, x, y, buf); } int DrawTextRight(DfFont *tr, DfColour c, DfBitmap *bmp, int x, int y, char const *text, ...) { char buf[512]; va_list ap; va_start(ap, text); vsprintf(buf, text, ap); int width = GetTextWidth(tr, buf); return DrawTextSimple(tr, c, bmp, x - width, y, buf); } int DrawTextCentre(DfFont *tr, DfColour c, DfBitmap *bmp, int x, int y, char const *text, ...) { char buf[512]; va_list ap; va_start(ap, text); vsprintf(buf, text, ap); int width = GetTextWidth(tr, buf); return DrawTextSimple(tr, c, bmp, x - width/2, y, buf); } int GetTextWidth(DfFont *tr, char const *text, int len) { len = IntMin((int)strlen(text), len); if (tr->fixedWidth) { return len * tr->maxCharWidth; } else { int width = 0; for (int i = 0; i < len; i++) width += tr->glyphs[text[i] & 0xff]->m_width; return width; } } <|endoftext|>
<commit_before>/** * * \file dsp3000.cpp * \brief KVH DSP-3000 Fiber optic gyro controller. * Parses data from DSP-3000 and publishes to dsp3000. * Serial interface handled by cereal_port * \author Jeff Schmidt <jschmidt@clearpathrobotics.com> * \copyright Copyright (c) 2013, Clearpath Robotics, Inc. * * 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 Clearpath Robotics, 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 CLEARPATH ROBOTICS, INC. 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. * * Please send comments, questions, or patches to code@clearpathrobotics.com * */ #include "ros/ros.h" #include "std_msgs/Float32.h" #include "cereal_port/CerealPort.h" #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <math.h> #include <vector> #include <sstream> const int TIMEOUT=1000; const float PI=3.14159265359f; using namespace std; bool configure_dsp3000(cereal::CerealPort *const device) { bool output = true; // Start by zeroing the sensor. Write three times, to ensure it is received (according to datasheet) ROS_INFO("Zeroing the DSP-3000."); try{ device->write("ZZZ", 3); } catch(cereal::TimeoutException& e) { ROS_ERROR("Unable to communicate with DSP-3000 device."); output = false; } //ros::Duration(0.1).sleep(); if (output) { // Set to "Rate" output. R=Rate, A=Incremental Angle, P=Integrated Angle ROS_INFO("Configuring for Rate output."); try{ device->write("RRR", 3); } catch(cereal::TimeoutException& e) { ROS_ERROR("Unable to communicate with DSP-3000 device."); } } //ros::Duration(0.1).sleep(); return output; } int main(int argc, char **argv) { ros::init(argc, argv, "dsp3000"); ros::NodeHandle n; // Grab the port name passed by the launch file. If the launch file was not used, or the desired // port is not present, default to /dev/ttyUSB0. string port_name; ros::param::param<std::string>("~port", port_name, "/dev/ttyUSB0"); // Define the publisher topic name ros::Publisher dsp3000_pub = n.advertise<std_msgs::Float32>("dsp3000", 10); cereal::CerealPort device; // Open a port as defined in the launch file. The DSP-3000 baud rate is 38400. try{ device.open(port_name.c_str(), 38400); } catch(cereal::Exception& e) { ROS_FATAL("Failed to open the serial port!!!"); ROS_BREAK(); } ROS_INFO("The serial port named \"%s\" is opened.", port_name.c_str()); configure_dsp3000(&device); device.flush(); static const int TEMP_BUFFER_SIZE = 128; char temp_buffer[TEMP_BUFFER_SIZE]; while (ros::ok()) { // Get the reply, the last value is the timeout in ms int temp_buffer_length = 0; try { temp_buffer_length = device.readLine(temp_buffer, TEMP_BUFFER_SIZE, TIMEOUT); } catch(cereal::TimeoutException& e) { ROS_ERROR("Unable to communicate with DSP-3000 device."); } static const char *ENDING_SEQUENCE = "\r\n"; static const int ENDING_SEQUENCE_LENGTH = strlen(ENDING_SEQUENCE); string str(temp_buffer, temp_buffer_length-ENDING_SEQUENCE_LENGTH); stringstream ss(str); vector<string> tokens; string ss_buf; while (ss >> ss_buf) tokens.push_back(ss_buf); if (!(tokens.size()&1)) { // Extra loop to publish extra readings for (int offset = 0; offset < tokens.size() / 2; offset+=2) { const float rotate = atof(tokens[offset].c_str()); const bool data_is_valid = (1 == atoi(tokens[offset+1].c_str()) ? true : false); ROS_DEBUG("Raw DSP-3000 Output: %f", rotate); if (data_is_valid) ROS_DEBUG("Data is valid"); //Declare the sensor message std_msgs::Float32 dsp_out; dsp_out.data = (rotate * PI) / 180.0f; //Publish the joint state message dsp3000_pub.publish(dsp_out); } } else { ROS_WARN("Bad data. Received data \"%s\" of length %i", ss.str().c_str(), static_cast<int>(tokens.size())); } ros::spinOnce(); } return 0; } <commit_msg>formatted file<commit_after>/** * * \file dsp3000.cpp * \brief KVH DSP-3000 Fiber optic gyro controller. * Parses data from DSP-3000 and publishes to dsp3000. * Serial interface handled by cereal_port * \author Jeff Schmidt <jschmidt@clearpathrobotics.com> * \copyright Copyright (c) 2013, Clearpath Robotics, Inc. * * 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 Clearpath Robotics, 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 CLEARPATH ROBOTICS, INC. 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. * * Please send comments, questions, or patches to code@clearpathrobotics.com * */ #include "cereal_port/CerealPort.h" #include "ros/ros.h" #include "std_msgs/Float32.h" #include <math.h> #include <sstream> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <vector> const int TIMEOUT = 1000; const float PI = 3.14159265359f; using namespace std; bool configure_dsp3000(cereal::CerealPort *const device) { bool output = true; // Start by zeroing the sensor. Write three times, to ensure it is received // (according to datasheet) ROS_INFO("Zeroing the DSP-3000."); try { device->write("ZZZ", 3); } catch (cereal::TimeoutException &e) { ROS_ERROR("Unable to communicate with DSP-3000 device."); output = false; } // ros::Duration(0.1).sleep(); if (output) { // Set to "Rate" output. R=Rate, A=Incremental Angle, P=Integrated Angle ROS_INFO("Configuring for Rate output."); try { device->write("RRR", 3); } catch (cereal::TimeoutException &e) { ROS_ERROR("Unable to communicate with DSP-3000 device."); } } // ros::Duration(0.1).sleep(); return output; } int main(int argc, char **argv) { ros::init(argc, argv, "dsp3000"); ros::NodeHandle n; // Grab the port name passed by the launch file. If the launch file was not // used, or the desired // port is not present, default to /dev/ttyUSB0. string port_name; ros::param::param<std::string>("~port", port_name, "/dev/ttyUSB0"); // Define the publisher topic name ros::Publisher dsp3000_pub = n.advertise<std_msgs::Float32>("dsp3000", 10); cereal::CerealPort device; // Open a port as defined in the launch file. The DSP-3000 baud rate is // 38400. try { device.open(port_name.c_str(), 38400); } catch (cereal::Exception &e) { ROS_FATAL("Failed to open the serial port!!!"); ROS_BREAK(); } ROS_INFO("The serial port named \"%s\" is opened.", port_name.c_str()); configure_dsp3000(&device); device.flush(); static const int TEMP_BUFFER_SIZE = 128; char temp_buffer[TEMP_BUFFER_SIZE]; while (ros::ok()) { // Get the reply, the last value is the timeout in ms int temp_buffer_length = 0; try { temp_buffer_length = device.readLine(temp_buffer, TEMP_BUFFER_SIZE, TIMEOUT); } catch (cereal::TimeoutException &e) { ROS_ERROR("Unable to communicate with DSP-3000 device."); } static const char *ENDING_SEQUENCE = "\r\n"; static const int ENDING_SEQUENCE_LENGTH = strlen(ENDING_SEQUENCE); string str(temp_buffer, temp_buffer_length - ENDING_SEQUENCE_LENGTH); stringstream ss(str); vector<string> tokens; string ss_buf; while (ss >> ss_buf) tokens.push_back(ss_buf); if (!(tokens.size() & 1)) { // Extra loop to publish extra readings for (int offset = 0; offset < tokens.size() / 2; offset += 2) { const float rotate = atof(tokens[offset].c_str()); const bool data_is_valid = (1 == atoi(tokens[offset + 1].c_str()) ? true : false); ROS_DEBUG("Raw DSP-3000 Output: %f", rotate); if (data_is_valid) ROS_DEBUG("Data is valid"); // Declare the sensor message std_msgs::Float32 dsp_out; dsp_out.data = (rotate * PI) / 180.0f; // Publish the joint state message dsp3000_pub.publish(dsp_out); } } else { ROS_WARN("Bad data. Received data \"%s\" of length %i", ss.str().c_str(), static_cast<int>(tokens.size())); } ros::spinOnce(); } return 0; } <|endoftext|>
<commit_before>/* Calf DSP Library utility application. * DSSI GUI application. * Copyright (C) 2007 Krzysztof Foltman * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General * Public License along with this program; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA */ #include <calf/giface.h> #include <calf/gui.h> #include <calf/osctl_glib.h> #include <calf/preset.h> #include <getopt.h> using namespace std; using namespace dsp; using namespace calf_plugins; using namespace osctl; #define debug_printf(...) struct cairo_params { enum { HAS_COLOR = 1, HAS_WIDTH = 2 }; uint32_t flags; float r, g, b, a; float line_width; cairo_params() : flags(0) , r(0.f) , g(0.f) , b(0.f) , a(1.f) , line_width(1) { } }; struct graph_item: public cairo_params { float data[128]; }; struct dot_item: public cairo_params { float x, y; int32_t size; }; struct gridline_item: public cairo_params { float pos; int32_t vertical; std::string text; }; struct param_line_graphs { vector<graph_item *> graphs; vector<dot_item *> dots; vector<gridline_item *> gridlines; void clear(); }; void param_line_graphs::clear() { for (size_t i = 0; i < graphs.size(); i++) delete graphs[i]; graphs.clear(); for (size_t i = 0; i < dots.size(); i++) delete dots[i]; dots.clear(); for (size_t i = 0; i < gridlines.size(); i++) delete gridlines[i]; gridlines.clear(); } struct plugin_proxy: public plugin_ctl_iface, public line_graph_iface { osc_client *client; bool send_osc; plugin_gui *gui; map<string, string> cfg_vars; int param_count; float *params; map<int, param_line_graphs> graphs; bool update_graphs; const plugin_metadata_iface *metadata; vector<string> new_status; uint32_t new_status_serial; bool is_lv2; plugin_proxy(const plugin_metadata_iface *md, bool _is_lv2) { new_status_serial = 0; metadata = md; client = NULL; send_osc = false; update_graphs = true; gui = NULL; param_count = md->get_param_count(); params = new float[param_count]; for (int i = 0; i < param_count; i++) params[i] = metadata->get_param_props(i)->def_value; is_lv2 = _is_lv2; } virtual float get_param_value(int param_no) { if (param_no < 0 || param_no >= param_count) return 0; return params[param_no]; } virtual void set_param_value(int param_no, float value) { if (param_no < 0 || param_no >= param_count) return; update_graphs = true; params[param_no] = value; if (send_osc) { osc_inline_typed_strstream str; str << (uint32_t)(param_no + metadata->get_param_port_offset()) << value; client->send("/control", str); } } virtual bool activate_preset(int bank, int program) { if (send_osc) { osc_inline_typed_strstream str; str << (uint32_t)(bank) << (uint32_t)(program); client->send("/program", str); return false; } return false; } virtual float get_level(unsigned int port) { return 0.f; } virtual void execute(int command_no) { if (send_osc) { stringstream ss; ss << command_no; osc_inline_typed_strstream str; str << "ExecCommand" << ss.str(); client->send("/configure", str); str.clear(); str << "ExecCommand" << ""; client->send("/configure", str); } } char *configure(const char *key, const char *value) { // do not store temporary vars in presets osc_inline_typed_strstream str; if (value) { if (strncmp(key, "OSC:", 4)) cfg_vars[key] = value; str << key << value; } else str << key; client->send("/configure", str); return NULL; } void send_configures(send_configure_iface *sci) { for (map<string, string>::iterator i = cfg_vars.begin(); i != cfg_vars.end(); i++) sci->send_configure(i->first.c_str(), i->second.c_str()); } virtual int send_status_updates(send_updates_iface *sui, int last_serial) { if ((int)new_status_serial != last_serial) { for (size_t i = 0; i < (new_status.size() & ~1); i += 2) { sui->send_status(new_status[i].c_str(), new_status[i + 1].c_str()); } return new_status_serial; } if (!is_lv2) { osc_inline_typed_strstream str; str << "OSC:SEND_STATUS" << calf_utils::i2s(last_serial); client->send("/configure", str); return last_serial; } else { osc_inline_typed_strstream str; str << (uint32_t)last_serial; client->send("/send_status", str); return last_serial; } } virtual const line_graph_iface *get_line_graph_iface() const { return this; } virtual bool get_graph(int index, int subindex, float *data, int points, cairo_iface *context) const; virtual bool get_dot(int index, int subindex, float &x, float &y, int &size, cairo_iface *context) const; virtual bool get_gridline(int index, int subindex, float &pos, bool &vertical, std::string &legend, cairo_iface *context) const; void update_cairo_context(cairo_iface *context, cairo_params &item) const; virtual const plugin_metadata_iface *get_metadata_iface() const { return metadata; } }; bool plugin_proxy::get_graph(int index, int subindex, float *data, int points, cairo_iface *context) const { if (!graphs.count(index)) return false; const param_line_graphs &g = graphs.find(index)->second; if (subindex < (int)g.graphs.size()) { float *sdata = g.graphs[subindex]->data; for (int i = 0; i < points; i++) { float pos = i * 127.0 / points; int ipos = i * 127 / points; data[i] = sdata[ipos] + (sdata[ipos + 1] - sdata[ipos]) * (pos-ipos); } update_cairo_context(context, *g.graphs[subindex]); return true; } return false; } bool plugin_proxy::get_dot(int index, int subindex, float &x, float &y, int &size, cairo_iface *context) const { if (!graphs.count(index)) return false; const param_line_graphs &g = graphs.find(index)->second; if (subindex < (int)g.dots.size()) { dot_item &item = *g.dots[subindex]; x = item.x; y = item.y; size = item.size; update_cairo_context(context, item); return true; } return false; } bool plugin_proxy::get_gridline(int index, int subindex, float &pos, bool &vertical, std::string &legend, cairo_iface *context) const { if (!graphs.count(index)) return false; const param_line_graphs &g = graphs.find(index)->second; if (subindex < (int)g.gridlines.size()) { gridline_item &item = *g.gridlines[subindex]; pos = item.pos; vertical = item.vertical != 0; legend = item.text; update_cairo_context(context, item); return true; } return false; } void plugin_proxy::update_cairo_context(cairo_iface *context, cairo_params &item) const { if (item.flags & cairo_params::HAS_COLOR) context->set_source_rgba(item.r, item.g, item.b, item.a); if (item.flags & cairo_params::HAS_WIDTH) context->set_line_width(item.line_width); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// GMainLoop *mainloop; static bool osc_debug = false; struct dssi_osc_server: public osc_glib_server, public osc_message_sink<osc_strstream>, public gui_environment { plugin_proxy *plugin; plugin_gui_window *window; string effect_name, title; osc_client cli; bool in_program, enable_dump; vector<plugin_preset> presets; /// Timeout callback source ID int source_id; bool osc_link_active; /// If we're communicating with the LV2 external UI bridge, use a slightly different protocol bool is_lv2; dssi_osc_server() : plugin(NULL) , window(new plugin_gui_window(this, NULL)) { sink = this; source_id = 0; osc_link_active = false; is_lv2 = false; } void set_plugin(const char *arg) { const plugin_metadata_iface *pmi = plugin_registry::instance().get_by_id(arg); if (!pmi) { pmi = plugin_registry::instance().get_by_uri(arg); if (pmi) is_lv2 = true; } if (!pmi) { fprintf(stderr, "Unknown plugin: %s\n", arg); exit(1); } effect_name = pmi->get_id(); plugin = new plugin_proxy(pmi, is_lv2); } static void on_destroy(GtkWindow *window, dssi_osc_server *self) { debug_printf("on_destroy, have to send \"exiting\"\n"); bool result = self->cli.send("/exiting"); debug_printf("result = %d\n", result ? 1 : 0); g_main_loop_quit(mainloop); // eliminate a warning with empty debug_printf result = false; } void create_window() { plugin->client = &cli; plugin->send_osc = true; conditions.insert("dssi"); conditions.insert("configure"); conditions.insert("directlink"); window->create(plugin, title.c_str(), effect_name.c_str()); plugin->gui = window->gui; gtk_signal_connect(GTK_OBJECT(window->toplevel), "destroy", G_CALLBACK(on_destroy), this); vector<plugin_preset> tmp_presets; get_builtin_presets().get_for_plugin(presets, effect_name.c_str()); get_user_presets().get_for_plugin(tmp_presets, effect_name.c_str()); presets.insert(presets.end(), tmp_presets.begin(), tmp_presets.end()); source_id = g_timeout_add_full(G_PRIORITY_LOW, 1000/30, on_idle, this, NULL); } static gboolean on_idle(void *self) { dssi_osc_server *self_ptr = (dssi_osc_server *)(self); if (self_ptr->osc_link_active) self_ptr->send_osc_update(); return TRUE; } void set_osc_update(bool enabled); void send_osc_update(); virtual void receive_osc_message(std::string address, std::string args, osc_strstream &buffer); void unmarshal_line_graph(osc_strstream &buffer); }; void dssi_osc_server::set_osc_update(bool enabled) { if (is_lv2) { osc_inline_typed_strstream data; data << ((uint32_t)(enabled ? 1 : 0)); cli.send("/enable_updates", data); } else { osc_link_active = enabled; osc_inline_typed_strstream data; data << "OSC:FEEDBACK_URI"; data << (enabled ? get_url() : ""); cli.send("/configure", data); } } void dssi_osc_server::send_osc_update() { // LV2 is updating via run() callback in the external UI library, so this is not needed if (is_lv2) return; static int serial_no = 0; osc_inline_typed_strstream data; data << "OSC:UPDATE"; data << calf_utils::i2s(serial_no++); cli.send("/configure", data); } void dssi_osc_server::unmarshal_line_graph(osc_strstream &buffer) { uint32_t cmd; do { buffer >> cmd; if (cmd == LGI_GRAPH) { uint32_t param; buffer >> param; param_line_graphs &graphs = plugin->graphs[param]; graphs.clear(); cairo_params params; do { buffer >> cmd; if (cmd == LGI_SET_RGBA) { params.flags |= cairo_params::HAS_COLOR; buffer >> params.r >> params.g >> params.b >> params.a; } else if (cmd == LGI_SET_WIDTH) { params.flags |= cairo_params::HAS_WIDTH; buffer >> params.line_width; } else if (cmd == LGI_SUBGRAPH) { buffer >> param; // ignore number of points graph_item *gi = new graph_item; (cairo_params &)*gi = params; for (int i = 0; i < 128; i++) buffer >> gi->data[i]; graphs.graphs.push_back(gi); params.flags = 0; } else if (cmd == LGI_DOT) { dot_item *di = new dot_item; (cairo_params &)*di = params; buffer >> di->x >> di->y >> di->size; graphs.dots.push_back(di); params.flags = 0; } else if (cmd == LGI_LEGEND) { gridline_item *li = new gridline_item; (cairo_params &)*li = params; buffer >> li->pos >> li->vertical >> li->text; graphs.gridlines.push_back(li); params.flags = 0; } else break; } while(1); } else break; } while(1); } void dssi_osc_server::receive_osc_message(std::string address, std::string args, osc_strstream &buffer) { if (osc_debug) dump.receive_osc_message(address, args, buffer); if (address == prefix + "/update" && args == "s") { string str; buffer >> str; debug_printf("UPDATE: %s\n", str.c_str()); set_osc_update(true); send_osc_update(); return; } else if (address == prefix + "/quit") { set_osc_update(false); debug_printf("QUIT\n"); g_main_loop_quit(mainloop); return; } else if (address == prefix + "/configure"&& args == "ss") { string key, value; buffer >> key >> value; // do not store temporary vars in presets if (strncmp(key.c_str(), "OSC:", 4)) plugin->cfg_vars[key] = value; // XXXKF perhaps this should be queued ! window->gui->refresh(); return; } else if (address == prefix + "/program"&& args == "ii") { uint32_t bank, program; buffer >> bank >> program; unsigned int nr = bank * 128 + program; debug_printf("PROGRAM %d\n", nr); if (nr == 0) { bool sosc = plugin->send_osc; plugin->send_osc = false; int count = plugin->metadata->get_param_count(); for (int i =0 ; i < count; i++) plugin->set_param_value(i, plugin->metadata->get_param_props(i)->def_value); plugin->send_osc = sosc; window->gui->refresh(); // special handling for default preset return; } nr--; if (nr >= presets.size()) return; bool sosc = plugin->send_osc; plugin->send_osc = false; presets[nr].activate(plugin); plugin->send_osc = sosc; window->gui->refresh(); // cli.send("/update", data); return; } else if (address == prefix + "/control" && args == "if") { uint32_t port; float val; buffer >> port >> val; int idx = port - plugin->metadata->get_param_port_offset(); debug_printf("CONTROL %d %f\n", idx, val); bool sosc = plugin->send_osc; plugin->send_osc = false; window->gui->set_param_value(idx, val); plugin->send_osc = sosc; if (plugin->metadata->get_param_props(idx)->flags & PF_PROP_GRAPH) plugin->update_graphs = true; return; } else if (address == prefix + "/show") { set_osc_update(true); gtk_widget_show(GTK_WIDGET(window->toplevel)); return; } else if (address == prefix + "/hide") { set_osc_update(false); gtk_widget_hide(GTK_WIDGET(window->toplevel)); return; } else if (address == prefix + "/lineGraph") { unmarshal_line_graph(buffer); if (plugin->update_graphs) { // updates graphs that are only redrawn on startup and parameter changes // (the OSC message may come a while after the parameter has been changed, // so the redraw triggered by parameter change usually shows stale values) window->gui->refresh(); plugin->update_graphs = false; } return; } else if (address == prefix + "/status_data" && (args.length() & 1) && args[args.length() - 1] == 'i') { int len = (int)args.length(); plugin->new_status.clear(); for (int pos = 0; pos < len - 2; pos += 2) { if (args[pos] == 's' && args[pos+1] == 's') { string key, value; buffer >> key >> value; plugin->new_status.push_back(key); plugin->new_status.push_back(value); } } buffer >> plugin->new_status_serial; return; } else printf("Unknown OSC address: %s\n", address.c_str()); } ////////////////////////////////////////////////////////////////////////////////// void help(char *argv[]) { printf("GTK+ user interface for Calf DSSI plugins\nSyntax: %s [--help] [--version] <osc-url> <so-file> <plugin-label> <instance-name>\n", argv[0]); } static struct option long_options[] = { {"help", 0, 0, 'h'}, {"version", 0, 0, 'v'}, {"debug", 0, 0, 'd'}, {0,0,0,0}, }; int main(int argc, char *argv[]) { char *debug_var = getenv("OSC_DEBUG"); if (debug_var && atoi(debug_var)) osc_debug = true; gtk_rc_add_default_file(PKGLIBDIR "calf.rc"); gtk_init(&argc, &argv); while(1) { int option_index; int c = getopt_long(argc, argv, "dhv", long_options, &option_index); if (c == -1) break; switch(c) { case 'd': osc_debug = true; break; case 'h': help(argv); return 0; case 'v': printf("%s\n", PACKAGE_STRING); return 0; } } if (argc - optind != 4) { help(argv); exit(0); } try { get_builtin_presets().load_defaults(true); get_user_presets().load_defaults(false); } catch(calf_plugins::preset_exception &e) { fprintf(stderr, "Error while loading presets: %s\n", e.what()); exit(1); } dssi_osc_server srv; srv.set_plugin(argv[optind + 2]); srv.prefix = "/dssi/"+string(argv[optind + 1]) + "/" + srv.effect_name; srv.title = argv[optind + 3]; srv.bind(); srv.create_window(); mainloop = g_main_loop_new(NULL, FALSE); srv.cli.bind(); srv.cli.set_url(argv[optind]); debug_printf("URI = %s\n", srv.get_url().c_str()); osc_inline_typed_strstream data; data << srv.get_url(); if (!srv.cli.send("/update", data)) { g_error("Could not send the initial update message via OSC to %s", argv[optind]); return 1; } g_main_loop_run(mainloop); if (srv.source_id) g_source_remove(srv.source_id); srv.set_osc_update(false); debug_printf("exited\n"); return 0; } <commit_msg>Remove obsolete file.<commit_after><|endoftext|>
<commit_before> /* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <GLES/gl.h> #include "GLWindowContext_android.h" #include <android/native_window_jni.h> namespace sk_app { // Most of the following 3 functions (GLWindowContext::Create, constructor, desctructor) // are copied from Unix/Win platform with unix/win changed to android // platform-dependent create GLWindowContext* GLWindowContext::Create(void* platformData, const DisplayParams& params) { GLWindowContext_android* ctx = new GLWindowContext_android(platformData, params); if (!ctx->isValid()) { delete ctx; return nullptr; } return ctx; } GLWindowContext_android::GLWindowContext_android(void* platformData, const DisplayParams& params) : GLWindowContext(platformData, params) , fDisplay(EGL_NO_DISPLAY) , fEGLContext(EGL_NO_CONTEXT) , fSurface(EGL_NO_SURFACE) { // any config code here (particularly for msaa)? this->initializeContext(platformData, params); } GLWindowContext_android::~GLWindowContext_android() { this->destroyContext(); } void GLWindowContext_android::onInitializeContext(void* platformData, const DisplayParams& params) { if (platformData != nullptr) { ContextPlatformData_android* androidPlatformData = reinterpret_cast<ContextPlatformData_android*>(platformData); fNativeWindow = androidPlatformData->fNativeWindow; } else { SkASSERT(fNativeWindow); } fWidth = ANativeWindow_getWidth(fNativeWindow); fHeight = ANativeWindow_getHeight(fNativeWindow); fDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY); EGLint majorVersion; EGLint minorVersion; eglInitialize(fDisplay, &majorVersion, &minorVersion); SkAssertResult(eglBindAPI(EGL_OPENGL_ES_API)); EGLint numConfigs = 0; const EGLint configAttribs[] = { EGL_SURFACE_TYPE, EGL_PBUFFER_BIT, EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_ALPHA_SIZE, 8, EGL_NONE }; EGLConfig surfaceConfig; SkAssertResult(eglChooseConfig(fDisplay, configAttribs, &surfaceConfig, 1, &numConfigs)); SkASSERT(numConfigs > 0); static const EGLint kEGLContextAttribsForOpenGLES[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE }; fEGLContext = eglCreateContext( fDisplay, surfaceConfig, nullptr, kEGLContextAttribsForOpenGLES); SkASSERT(EGL_NO_CONTEXT != fEGLContext); fSurface = eglCreateWindowSurface( fDisplay, surfaceConfig, fNativeWindow, nullptr); SkASSERT(EGL_NO_SURFACE != fSurface); SkAssertResult(eglMakeCurrent(fDisplay, fSurface, fSurface, fEGLContext)); // GLWindowContext::initializeContext will call GrGLCreateNativeInterface so we // won't call it here. glClearStencil(0); glClearColor(0, 0, 0, 0); glStencilMask(0xffffffff); glClear(GL_STENCIL_BUFFER_BIT | GL_COLOR_BUFFER_BIT); int redBits, greenBits, blueBits; eglGetConfigAttrib(fDisplay, surfaceConfig, EGL_RED_SIZE, &redBits); eglGetConfigAttrib(fDisplay, surfaceConfig, EGL_GREEN_SIZE, &greenBits); eglGetConfigAttrib(fDisplay, surfaceConfig, EGL_BLUE_SIZE, &blueBits); fColorBits = redBits + greenBits + blueBits; eglGetConfigAttrib(fDisplay, surfaceConfig, EGL_STENCIL_SIZE, &fStencilBits); eglGetConfigAttrib(fDisplay, surfaceConfig, EGL_SAMPLES, &fSampleCount); } void GLWindowContext_android::onDestroyContext() { if (!fDisplay || !fEGLContext || !fSurface) { return; } eglMakeCurrent(fDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); SkAssertResult(eglDestroySurface(fDisplay, fSurface)); SkAssertResult(eglDestroyContext(fDisplay, fEGLContext)); fEGLContext = EGL_NO_CONTEXT; fSurface = EGL_NO_SURFACE; } void GLWindowContext_android::onSwapBuffers() { if (fDisplay && fEGLContext && fSurface) { eglSwapBuffers(fDisplay, fSurface); } } } <commit_msg>Request an sRGB FBO0 on Android. Fixes sRGB GL mode.<commit_after> /* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <GLES/gl.h> #include "GLWindowContext_android.h" #include <android/native_window_jni.h> namespace sk_app { // Most of the following 3 functions (GLWindowContext::Create, constructor, desctructor) // are copied from Unix/Win platform with unix/win changed to android // platform-dependent create GLWindowContext* GLWindowContext::Create(void* platformData, const DisplayParams& params) { GLWindowContext_android* ctx = new GLWindowContext_android(platformData, params); if (!ctx->isValid()) { delete ctx; return nullptr; } return ctx; } GLWindowContext_android::GLWindowContext_android(void* platformData, const DisplayParams& params) : GLWindowContext(platformData, params) , fDisplay(EGL_NO_DISPLAY) , fEGLContext(EGL_NO_CONTEXT) , fSurface(EGL_NO_SURFACE) { // any config code here (particularly for msaa)? this->initializeContext(platformData, params); } GLWindowContext_android::~GLWindowContext_android() { this->destroyContext(); } void GLWindowContext_android::onInitializeContext(void* platformData, const DisplayParams& params) { if (platformData != nullptr) { ContextPlatformData_android* androidPlatformData = reinterpret_cast<ContextPlatformData_android*>(platformData); fNativeWindow = androidPlatformData->fNativeWindow; } else { SkASSERT(fNativeWindow); } fWidth = ANativeWindow_getWidth(fNativeWindow); fHeight = ANativeWindow_getHeight(fNativeWindow); fDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY); EGLint majorVersion; EGLint minorVersion; eglInitialize(fDisplay, &majorVersion, &minorVersion); SkAssertResult(eglBindAPI(EGL_OPENGL_ES_API)); EGLint numConfigs = 0; const EGLint configAttribs[] = { EGL_SURFACE_TYPE, EGL_PBUFFER_BIT, EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_ALPHA_SIZE, 8, EGL_NONE }; EGLConfig surfaceConfig; SkAssertResult(eglChooseConfig(fDisplay, configAttribs, &surfaceConfig, 1, &numConfigs)); SkASSERT(numConfigs > 0); static const EGLint kEGLContextAttribsForOpenGLES[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE }; fEGLContext = eglCreateContext( fDisplay, surfaceConfig, nullptr, kEGLContextAttribsForOpenGLES); SkASSERT(EGL_NO_CONTEXT != fEGLContext); // These values are the same as the corresponding VG colorspace attributes, // which were accepted starting in EGL 1.2. For some reason in 1.4, sRGB // became hidden behind an extension, but it looks like devices aren't // advertising that extension (including Nexus 5X). So just check version? const EGLint srgbWindowAttribs[] = { /*EGL_GL_COLORSPACE_KHR*/ 0x309D, /*EGL_GL_COLORSPACE_SRGB_KHR*/ 0x3089, EGL_NONE, }; const EGLint* windowAttribs = nullptr; if (kSRGB_SkColorProfileType == params.fProfileType && majorVersion == 1 && minorVersion >= 2) { windowAttribs = srgbWindowAttribs; } fSurface = eglCreateWindowSurface( fDisplay, surfaceConfig, fNativeWindow, windowAttribs); SkASSERT(EGL_NO_SURFACE != fSurface); SkAssertResult(eglMakeCurrent(fDisplay, fSurface, fSurface, fEGLContext)); // GLWindowContext::initializeContext will call GrGLCreateNativeInterface so we // won't call it here. glClearStencil(0); glClearColor(0, 0, 0, 0); glStencilMask(0xffffffff); glClear(GL_STENCIL_BUFFER_BIT | GL_COLOR_BUFFER_BIT); int redBits, greenBits, blueBits; eglGetConfigAttrib(fDisplay, surfaceConfig, EGL_RED_SIZE, &redBits); eglGetConfigAttrib(fDisplay, surfaceConfig, EGL_GREEN_SIZE, &greenBits); eglGetConfigAttrib(fDisplay, surfaceConfig, EGL_BLUE_SIZE, &blueBits); fColorBits = redBits + greenBits + blueBits; eglGetConfigAttrib(fDisplay, surfaceConfig, EGL_STENCIL_SIZE, &fStencilBits); eglGetConfigAttrib(fDisplay, surfaceConfig, EGL_SAMPLES, &fSampleCount); } void GLWindowContext_android::onDestroyContext() { if (!fDisplay || !fEGLContext || !fSurface) { return; } eglMakeCurrent(fDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); SkAssertResult(eglDestroySurface(fDisplay, fSurface)); SkAssertResult(eglDestroyContext(fDisplay, fEGLContext)); fEGLContext = EGL_NO_CONTEXT; fSurface = EGL_NO_SURFACE; } void GLWindowContext_android::onSwapBuffers() { if (fDisplay && fEGLContext && fSurface) { eglSwapBuffers(fDisplay, fSurface); } } } <|endoftext|>
<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include <iostream> #include <sstream> #include <SFNUL/Config.hpp> #if defined( ERROR ) #undef ERROR #endif namespace sfn { extern std::ostringstream discard_message; enum class MessageLevel : unsigned char { ERROR = 0, WARNING = 1, INFORMATION = 2, DEBUG = 3, }; extern MessageLevel message_level; void SetMessageLevel( MessageLevel level ); std::ostream& ErrorMessage(); std::ostream& WarningMessage(); std::ostream& InformationMessage(); std::ostream& DebugMessage(); } <commit_msg>Removed a couple of unneeded extern declarations.<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #include <iostream> #include <sstream> #include <SFNUL/Config.hpp> #if defined( ERROR ) #undef ERROR #endif namespace sfn { enum class MessageLevel : unsigned char { ERROR = 0, WARNING = 1, INFORMATION = 2, DEBUG = 3, }; void SetMessageLevel( MessageLevel level ); std::ostream& ErrorMessage(); std::ostream& WarningMessage(); std::ostream& InformationMessage(); std::ostream& DebugMessage(); } <|endoftext|>
<commit_before>#ifndef STAN_MATH_PRIM_SCAL_FUN_DIVIDE_HPP #define STAN_MATH_PRIM_SCAL_FUN_DIVIDE_HPP #include <stan/math/prim/scal/err/domain_error.hpp> #include <stan/math/prim/scal/meta/likely.hpp> #include <stan/math/prim/scal/meta/return_type.hpp> #include <cstddef> #include <cstdlib> namespace stan { namespace math { /** * Return the division of the first scalar by * the second scalar. * @param[in] x Specified vector. * @param[in] y Specified scalar. * @return Vector divided by the scalar. */ template<typename T1, typename T2> inline typename stan::return_type<T1, T2>::type divide(const T1& x, const T2& y) { return x / y; } inline int divide(const int x, const int y) { if (unlikely(y == 0)) domain_error("divide", "denominator is", y, ""); return std::div(x, y).quot; } } } #endif <commit_msg>Changing divide implementation<commit_after>#ifndef STAN_MATH_PRIM_SCAL_FUN_DIVIDE_HPP #define STAN_MATH_PRIM_SCAL_FUN_DIVIDE_HPP #include <stan/math/prim/scal/err/domain_error.hpp> #include <stan/math/prim/scal/meta/likely.hpp> #include <stan/math/prim/scal/meta/return_type.hpp> #include <cstddef> #include <cstdlib> namespace stan { namespace math { /** * Return the division of the first scalar by * the second scalar. * @param[in] x Specified vector. * @param[in] y Specified scalar. * @return Vector divided by the scalar. */ template<typename T1, typename T2> inline typename stan::return_type<T1, T2>::type divide(const T1& x, const T2& y) { return x / y; } inline int divide(const int x, const int y) { if (unlikely(y == 0)) domain_error("divide", "denominator is", y, ""); return x / y; } } } #endif <|endoftext|>
<commit_before>#ifndef ATL_GC_GC_HPP #define ATL_GC_GC_HPP // @file /home/ryan/programming/atl/gc.hpp // @author Ryan Domigan <ryan_domigan@sutdents@uml.edu> // Created on Jan 08, 2014 // // A garbage collected environment. #include <limits> #include <algorithm> #include <functional> #include <list> #include <memory> #include <iterator> #include <boost/mpl/map.hpp> #include <gc/pool.hpp> #include "./debug.hpp" #include "./byte_code.hpp" namespace atl { using namespace std; /*****************/ /* ____ ____ */ /* / ___|/ ___| */ /* | | _| | */ /* | |_| | |___ */ /* \____|\____| */ /*****************/ // This is a basic vector with the copy constructor disabled so I // can pass it around by reference and not accidently copy by // value. struct AstSubstrate : public std::vector<Any> { AstSubstrate() : std::vector<Any>() {} AstSubstrate(AstSubstrate const&) = delete; Any& root() { return front(); } void dbg(); }; void AstSubstrate::dbg() { for(auto& vv : *this) { std::cout << type_name(vv) << std::endl; } } // An iterator like thing which follows the position of an object // in a vector so it will remain valid after a resize. struct MovableAstPointer { AstSubstrate *vect; size_t position; MovableAstPointer(AstSubstrate* vect_, size_t pos) : vect(vect_), position(pos) {} AstData* ast_data() { return reinterpret_cast<AstData*>(&(*vect)[position]); } // Last + 1 element of the wrapped Ast void end_ast() { reinterpret_cast<AstData*>(vect->data() + position)->value = vect->size() - position - 1; } Ast operator*() { return Ast(ast_data()); } }; MovableAstPointer push_nested_ast(AstSubstrate& substrate) { auto pos = substrate.size(); substrate.emplace_back(tag<AstData>::value, nullptr); return MovableAstPointer(&substrate, pos); } struct AstAllocator; typedef std::function<Ast (AstAllocator)> ast_composer; // I would like some Asts generating functions to be able to use // either the GC or an Arena at runtime, struct AllocatorBase { virtual ~AllocatorBase() {} virtual AstSubstrate& sequence() = 0; virtual Symbol* symbol(std::string const&) = 0; virtual LambdaMetadata* lambda_metadata() = 0; virtual Symbol* symbol(std::string const&, Scheme const& type) = 0; virtual void free(Any any) = 0; Ast operator()(ast_composer const& func); pcode::value_type* closure(pcode::value_type body_location, size_t formals, size_t captures) { auto rval = new pcode::value_type[captures + 2]; rval[0] = formals; rval[1] = body_location; return rval; } }; struct AstAllocator { AllocatorBase &store; AstSubstrate &buffer; explicit AstAllocator(AllocatorBase &aa) : store(aa), buffer(aa.sequence()) {} AstAllocator& push_back(Any value) { buffer.push_back(value); return *this; } MovableAstPointer nest_ast() { return push_nested_ast(buffer); } size_t size() { return buffer.size(); } }; Ast AllocatorBase::operator()(ast_composer const& func) { auto backer = AstAllocator(*this); func(backer); return Ast(reinterpret_cast<AstData*>(&backer.buffer.root())); } struct NestAst { AstAllocator& store; MovableAstPointer ast; NestAst(AstAllocator& store_) : store(store_), ast(store.nest_ast()) {} ~NestAst() { ast.end_ast(); } }; // A mark-and-sweep GC. STUB class GC : public AllocatorBase { private: typedef std::list< Any > MarkType; MarkType _mark; private: vector< function<void (GC&)> > _mark_callbacks; void unregister(MarkType::iterator itr) { _mark.erase(itr); } memory_pool::Pool< LambdaMetadata > _lambda_metadata_heap; memory_pool::Pool< String > _string_heap; memory_pool::Pool< CxxFunctor > _primitive_recursive_heap; memory_pool::Pool< Symbol > _symbol_heap; template< class T, memory_pool::Pool<T> GC::*member > struct MemberPtr { typedef memory_pool::Pool<T> GC::* PoolType; /* man this would be easier with inline definitions. */ const static PoolType value; }; typedef mpl::map< mpl::pair< LambdaMetadata , MemberPtr<LambdaMetadata, &GC::_lambda_metadata_heap > > , mpl::pair< String , MemberPtr<String, &GC::_string_heap > > , mpl::pair< CxxFunctor, MemberPtr<CxxFunctor, &GC::_primitive_recursive_heap > > , mpl::pair< Symbol, MemberPtr<Symbol, &GC::_symbol_heap > > > PoolMap; template<class T> T* alloc_from(memory_pool::Pool<T> &pool) { T* result = pool.alloc(); if(result == nullptr) { mark_and_sweep(); result = pool.alloc(); if(result == nullptr) throw string("out of memory"); } return result; } std::vector<Code> code_blocks; public: void mark_and_sweep() { for(auto i : _mark_callbacks) i(*this); _string_heap.sweep(); } void mark(Any a) {} // Adds callbacks which will be invoked during the mark phase of the GC. // @param fn: the callback void mark_callback(function<void (GC&)> fn) { _mark_callbacks.push_back(fn); } /*****************************/ /** __ __ _ **/ /** | \/ | __ _| | _____ **/ /** | |\/| |/ _` | |/ / _ \ **/ /** | | | | (_| | < __/ **/ /** |_| |_|\__,_|_|\_\___| **/ /*****************************/ template<class T> T* alloc() { static_assert( mpl::has_key<PoolMap, T>::value, "GC::Type does not have corrosponding pool." ); return alloc_from( (this->*mpl::at<PoolMap,T>::type::value) ); } Code& alloc_pcode() { code_blocks.emplace_back(); return code_blocks.back(); } template<class Type, class ... Types> Type* make(Types ... args) { return new ( alloc<Type>() ) Type (args...); } template<class Type, class ... Types> Any amake(Types ... args) { return Any( tag<Type>::value , make<Type>(args...)); } virtual AstSubstrate& sequence() override { auto rval = new AstSubstrate(); rval->reserve(100); return *rval; } virtual Symbol* symbol(std::string const& name) override { return make<Symbol>(name); } virtual LambdaMetadata* lambda_metadata() override { return make<LambdaMetadata>(); } virtual Symbol* symbol(std::string const& name, Scheme const& type) override { return make<Symbol>(name, type); } virtual void free(Any any) override { /* stub */ } }; template< class T, memory_pool::Pool<T> GC::*member > const typename GC::MemberPtr<T,member>::PoolType GC::MemberPtr<T,member>::value = member; // Uses GC to mark each argument of this function. // // @tparam Types: types of the args // @param args: args to be marked void mark_args(GC &gc) {} template<class T, class ... Types> void mark_args(GC &gc, T a, Types ... as) { gc.mark( a ); mark_args(gc, as...); } // A GC which collects all allocated objects when it goes out of // scope. <STUB> struct Arena : public AllocatorBase { virtual AstSubstrate& sequence() override { auto rval = new AstSubstrate(); rval->reserve(100); return *rval; } template<class T, class ... Args> T* make(Args ... args) { return new T(args...); } template<class T, class ... Args> Any amake(Args ... args) { return Any( tag<T>::value , make<T>(args...)); } virtual Symbol* symbol(std::string const& name) override { return make<Symbol>(name); } virtual LambdaMetadata* lambda_metadata() override { return make<LambdaMetadata>(); } virtual Symbol* symbol(std::string const& name, Scheme const& type) override { return make<Symbol>(name, type); } virtual void free(Any any) override { /* stub */ } }; } #endif <commit_msg>gc: get rid of AllocatorBase and Arena<commit_after>#ifndef ATL_GC_GC_HPP #define ATL_GC_GC_HPP // @file /home/ryan/programming/atl/gc.hpp // @author Ryan Domigan <ryan_domigan@sutdents@uml.edu> // Created on Jan 08, 2014 // // A garbage collected environment. #include <limits> #include <algorithm> #include <functional> #include <list> #include <memory> #include <iterator> #include <boost/mpl/map.hpp> #include <gc/pool.hpp> #include "./debug.hpp" #include "./byte_code.hpp" namespace atl { using namespace std; /*****************/ /* ____ ____ */ /* / ___|/ ___| */ /* | | _| | */ /* | |_| | |___ */ /* \____|\____| */ /*****************/ // This is a basic vector with the copy constructor disabled so I // can pass it around by reference and not accidently copy by // value. struct AstSubstrate : public std::vector<Any> { AstSubstrate() : std::vector<Any>() {} AstSubstrate(AstSubstrate const&) = delete; Any& root() { return front(); } void dbg(); }; void AstSubstrate::dbg() { for(auto& vv : *this) { std::cout << type_name(vv) << std::endl; } } // An iterator like thing which follows the position of an object // in a vector so it will remain valid after a resize. struct MovableAstPointer { AstSubstrate *vect; size_t position; MovableAstPointer(AstSubstrate* vect_, size_t pos) : vect(vect_), position(pos) {} AstData* ast_data() { return reinterpret_cast<AstData*>(&(*vect)[position]); } // Last + 1 element of the wrapped Ast void end_ast() { reinterpret_cast<AstData*>(vect->data() + position)->value = vect->size() - position - 1; } Ast operator*() { return Ast(ast_data()); } }; MovableAstPointer push_nested_ast(AstSubstrate& substrate) { auto pos = substrate.size(); substrate.emplace_back(tag<AstData>::value, nullptr); return MovableAstPointer(&substrate, pos); } struct AstAllocator; typedef std::function<Ast (AstAllocator)> ast_composer; struct AstAllocator { AllocatorBase &store; AstSubstrate &buffer; explicit AstAllocator(AllocatorBase &aa) : store(aa), buffer(aa.sequence()) {} AstAllocator& push_back(Any value) { buffer.push_back(value); return *this; } MovableAstPointer nest_ast() { return push_nested_ast(buffer); } size_t size() { return buffer.size(); } }; struct NestAst { AstAllocator& store; MovableAstPointer ast; NestAst(AstAllocator& store_) : store(store_), ast(store.nest_ast()) {} ~NestAst() { ast.end_ast(); } }; // A mark-and-sweep GC. STUB struct GC { private: typedef std::list< Any > MarkType; MarkType _mark; private: vector< function<void (GC&)> > _mark_callbacks; void unregister(MarkType::iterator itr) { _mark.erase(itr); } memory_pool::Pool< LambdaMetadata > _lambda_metadata_heap; memory_pool::Pool< String > _string_heap; memory_pool::Pool< CxxFunctor > _primitive_recursive_heap; memory_pool::Pool< Symbol > _symbol_heap; template< class T, memory_pool::Pool<T> GC::*member > struct MemberPtr { typedef memory_pool::Pool<T> GC::* PoolType; /* man this would be easier with inline definitions. */ const static PoolType value; }; typedef mpl::map< mpl::pair< LambdaMetadata , MemberPtr<LambdaMetadata, &GC::_lambda_metadata_heap > > , mpl::pair< String , MemberPtr<String, &GC::_string_heap > > , mpl::pair< CxxFunctor, MemberPtr<CxxFunctor, &GC::_primitive_recursive_heap > > , mpl::pair< Symbol, MemberPtr<Symbol, &GC::_symbol_heap > > > PoolMap; template<class T> T* alloc_from(memory_pool::Pool<T> &pool) { T* result = pool.alloc(); if(result == nullptr) { mark_and_sweep(); result = pool.alloc(); if(result == nullptr) throw string("out of memory"); } return result; } std::vector<Code> code_blocks; public: void mark_and_sweep() { for(auto i : _mark_callbacks) i(*this); _string_heap.sweep(); } void mark(Any a) {} // Adds callbacks which will be invoked during the mark phase of the GC. // @param fn: the callback void mark_callback(function<void (GC&)> fn) { _mark_callbacks.push_back(fn); } /*****************************/ /** __ __ _ **/ /** | \/ | __ _| | _____ **/ /** | |\/| |/ _` | |/ / _ \ **/ /** | | | | (_| | < __/ **/ /** |_| |_|\__,_|_|\_\___| **/ /*****************************/ template<class T> T* alloc() { static_assert( mpl::has_key<PoolMap, T>::value, "GC::Type does not have corrosponding pool." ); return alloc_from( (this->*mpl::at<PoolMap,T>::type::value) ); } Code& alloc_pcode() { code_blocks.emplace_back(); return code_blocks.back(); } template<class Type, class ... Types> Type* make(Types ... args) { return new ( alloc<Type>() ) Type (args...); } template<class Type, class ... Types> Any amake(Types ... args) { return Any( tag<Type>::value , make<Type>(args...)); } virtual AstSubstrate& sequence() override { auto rval = new AstSubstrate(); rval->reserve(100); return *rval; } virtual Symbol* symbol(std::string const& name) override { return make<Symbol>(name); } virtual LambdaMetadata* lambda_metadata() override { return make<LambdaMetadata>(); } virtual Symbol* symbol(std::string const& name, Scheme const& type) override { return make<Symbol>(name, type); } virtual void free(Any any) override { /* stub */ } }; template< class T, memory_pool::Pool<T> GC::*member > const typename GC::MemberPtr<T,member>::PoolType GC::MemberPtr<T,member>::value = member; // Uses GC to mark each argument of this function. // // @tparam Types: types of the args // @param args: args to be marked void mark_args(GC &gc) {} template<class T, class ... Types> void mark_args(GC &gc, T a, Types ... as) { gc.mark( a ); mark_args(gc, as...); } } #endif <|endoftext|>
<commit_before>#ifndef STAN_MATH_REV_FUN_INC_BETA_INV_HPP #define STAN_MATH_REV_FUN_INC_BETA_INV_HPP #include <stan/math/rev/meta.hpp> #include <stan/math/rev/core.hpp> #include <stan/math/prim/fun/constants.hpp> #include <stan/math/prim/fun/inc_beta_inv.hpp> #include <stan/math/prim/fun/inc_beta.hpp> #include <stan/math/prim/fun/exp.hpp> #include <stan/math/prim/fun/log.hpp> #include <stan/math/prim/fun/log_diff_exp.hpp> #include <stan/math/prim/fun/lbeta.hpp> #include <stan/math/prim/fun/lgamma.hpp> #include <stan/math/prim/fun/digamma.hpp> #include <stan/math/prim/fun/F32.hpp> #include <stan/math/prim/fun/is_any_nan.hpp> namespace stan { namespace math { /** * The inverse of the normalized incomplete beta function of a, b, with * probability p. * * Used to compute the cumulative density function for the beta * distribution. * \f[ \frac{\partial }{\partial a} = (1-w)^{1-b}w^{1-a} \left( w^a\Gamma(a)^2 {}_3\tilde{F}_2(a,a,1-b;a+1,a+1;w) - B(a,b)I_w(a,b)\left(\log(w)-\psi(a) + \psi(a+b)\right) \right)/;w=I_z^{-1}(a,b) \f] \f[ \frac{\partial }{\partial b} = (1-w)^{-b}w^{1-a}(w-1) \left( (1-w)^{b}\Gamma(b)^2 {}_3\tilde{F}_2(b,b,1-a;b+1,b+1;1-w) - B_{1-w}(b,a)\left(\log(1-w)-\psi(b) + \psi(a+b)\right) \right)/;w=I_z^{-1}(a,b) \f] \f[ \frac{\partial }{\partial z} = (1-w)^{1-b}w^{1-a}B(a,b)/;w=I_z^{-1}(a,b) \f] * * @param a Shape parameter a >= 0; a and b can't both be 0 * @param b Shape parameter b >= 0 * @param p Random variate. 0 <= p <= 1 * @throws if constraints are violated or if any argument is NaN * @return The inverse of the normalized incomplete beta function. */ template <typename T1, typename T2, typename T3, require_all_stan_scalar_t<T1, T2, T3>* = nullptr, require_any_var_t<T1, T2, T3>* = nullptr> inline var inc_beta_inv(const T1& a, const T2& b, const T3& p) { double a_val = value_of(a); double b_val = value_of(b); double p_val = value_of(p); double w = inc_beta_inv(a_val, b_val, p_val); return make_callback_var(w, [a, b, p, a_val, b_val, p_val, w](auto& vi) { double log_w = log(w); double log1m_w = log1m(w); double one_m_a = 1 - a_val; double one_m_b = 1 - b_val; double one_m_w = 1 - w; double ap1 = a_val + 1; double bp1 = b_val + 1; double lbeta_ab = lbeta(a_val, b_val); double digamma_apb = digamma(a_val + b_val); if (!is_constant_all<T1>::value) { double da1 = exp(one_m_b * log1m_w + one_m_a * log_w); double da2 = a_val * log_w + 2 * lgamma(a_val) + log(F32(a_val, a_val, one_m_b, ap1, ap1, w)) - 2 * lgamma(ap1); double da3 = inc_beta(a_val, b_val, w) * exp(lbeta_ab) * (log_w - digamma(a_val) + digamma_apb); forward_as<var>(a).adj() += vi.adj() * da1 * (exp(da2) - da3); } if (!is_constant_all<T2>::value) { double db1 = (w - 1) * exp(-b_val * log1m_w + one_m_a * log_w); double db2 = 2 * lgamma(b_val) + log(F32(b_val, b_val, one_m_a, bp1, bp1, one_m_w)) - 2 * lgamma(bp1) + b_val * log1m_w; double db3 = inc_beta(b_val, a_val, one_m_w) * exp(lbeta_ab) * (log1m_w - digamma(b_val) + digamma_apb); forward_as<var>(b).adj() += vi.adj() * db1 * (exp(db2) - db3); } if (!is_constant_all<T3>::value) { forward_as<var>(p).adj() += vi.adj() * exp(one_m_b * log1m_w + one_m_a * log_w + lbeta_ab); } }); } } // namespace math } // namespace stan #endif <commit_msg>[Jenkins] auto-formatting by clang-format version 6.0.0-1ubuntu2~16.04.1 (tags/RELEASE_600/final)<commit_after>#ifndef STAN_MATH_REV_FUN_INC_BETA_INV_HPP #define STAN_MATH_REV_FUN_INC_BETA_INV_HPP #include <stan/math/rev/meta.hpp> #include <stan/math/rev/core.hpp> #include <stan/math/prim/fun/constants.hpp> #include <stan/math/prim/fun/inc_beta_inv.hpp> #include <stan/math/prim/fun/inc_beta.hpp> #include <stan/math/prim/fun/exp.hpp> #include <stan/math/prim/fun/log.hpp> #include <stan/math/prim/fun/log_diff_exp.hpp> #include <stan/math/prim/fun/lbeta.hpp> #include <stan/math/prim/fun/lgamma.hpp> #include <stan/math/prim/fun/digamma.hpp> #include <stan/math/prim/fun/F32.hpp> #include <stan/math/prim/fun/is_any_nan.hpp> namespace stan { namespace math { /** * The inverse of the normalized incomplete beta function of a, b, with * probability p. * * Used to compute the cumulative density function for the beta * distribution. * \f[ \frac{\partial }{\partial a} = (1-w)^{1-b}w^{1-a} \left( w^a\Gamma(a)^2 {}_3\tilde{F}_2(a,a,1-b;a+1,a+1;w) - B(a,b)I_w(a,b)\left(\log(w)-\psi(a) + \psi(a+b)\right) \right)/;w=I_z^{-1}(a,b) \f] \f[ \frac{\partial }{\partial b} = (1-w)^{-b}w^{1-a}(w-1) \left( (1-w)^{b}\Gamma(b)^2 {}_3\tilde{F}_2(b,b,1-a;b+1,b+1;1-w) - B_{1-w}(b,a)\left(\log(1-w)-\psi(b) + \psi(a+b)\right) \right)/;w=I_z^{-1}(a,b) \f] \f[ \frac{\partial }{\partial z} = (1-w)^{1-b}w^{1-a}B(a,b)/;w=I_z^{-1}(a,b) \f] * * @param a Shape parameter a >= 0; a and b can't both be 0 * @param b Shape parameter b >= 0 * @param p Random variate. 0 <= p <= 1 * @throws if constraints are violated or if any argument is NaN * @return The inverse of the normalized incomplete beta function. */ template <typename T1, typename T2, typename T3, require_all_stan_scalar_t<T1, T2, T3>* = nullptr, require_any_var_t<T1, T2, T3>* = nullptr> inline var inc_beta_inv(const T1& a, const T2& b, const T3& p) { double a_val = value_of(a); double b_val = value_of(b); double p_val = value_of(p); double w = inc_beta_inv(a_val, b_val, p_val); return make_callback_var(w, [a, b, p, a_val, b_val, p_val, w](auto& vi) { double log_w = log(w); double log1m_w = log1m(w); double one_m_a = 1 - a_val; double one_m_b = 1 - b_val; double one_m_w = 1 - w; double ap1 = a_val + 1; double bp1 = b_val + 1; double lbeta_ab = lbeta(a_val, b_val); double digamma_apb = digamma(a_val + b_val); if (!is_constant_all<T1>::value) { double da1 = exp(one_m_b * log1m_w + one_m_a * log_w); double da2 = a_val * log_w + 2 * lgamma(a_val) + log(F32(a_val, a_val, one_m_b, ap1, ap1, w)) - 2 * lgamma(ap1); double da3 = inc_beta(a_val, b_val, w) * exp(lbeta_ab) * (log_w - digamma(a_val) + digamma_apb); forward_as<var>(a).adj() += vi.adj() * da1 * (exp(da2) - da3); } if (!is_constant_all<T2>::value) { double db1 = (w - 1) * exp(-b_val * log1m_w + one_m_a * log_w); double db2 = 2 * lgamma(b_val) + log(F32(b_val, b_val, one_m_a, bp1, bp1, one_m_w)) - 2 * lgamma(bp1) + b_val * log1m_w; double db3 = inc_beta(b_val, a_val, one_m_w) * exp(lbeta_ab) * (log1m_w - digamma(b_val) + digamma_apb); forward_as<var>(b).adj() += vi.adj() * db1 * (exp(db2) - db3); } if (!is_constant_all<T3>::value) { forward_as<var>(p).adj() += vi.adj() * exp(one_m_b * log1m_w + one_m_a * log_w + lbeta_ab); } }); } } // namespace math } // namespace stan #endif <|endoftext|>
<commit_before>#ifndef STAN_MATH_REV_SCAL_FUN_GAMMA_P_HPP #define STAN_MATH_REV_SCAL_FUN_GAMMA_P_HPP #include <stan/math/rev/core.hpp> #include <stan/math/prim/scal/fun/is_inf.hpp> #include <stan/math/prim/scal/err/domain_error.hpp> #include <stan/math/prim/scal/fun/digamma.hpp> #include <stan/math/prim/scal/fun/gamma_p.hpp> #include <stan/math/prim/scal/fun/lgamma.hpp> #include <stan/math/prim/scal/fun/grad_reg_lower_inc_gamma.hpp> #include <valarray> #include <limits> namespace stan { namespace math { namespace { class gamma_p_vv_vari : public op_vv_vari { public: gamma_p_vv_vari(vari* avi, vari* bvi) : op_vv_vari(gamma_p(avi->val_, bvi->val_), avi, bvi) {} void chain() { using boost::math::lgamma; using std::exp; using std::fabs; using std::log; if (is_inf(avi_->val_)) { avi_->adj_ += std::numeric_limits<double>::quiet_NaN(); bvi_->adj_ += std::numeric_limits<double>::quiet_NaN(); return; } if (is_inf(bvi_->val_)) { avi_->adj_ += std::numeric_limits<double>::quiet_NaN(); bvi_->adj_ += std::numeric_limits<double>::quiet_NaN(); return; } // return zero derivative as gamma_p is flat // to machine precision for b / a > 10 if (std::fabs(bvi_->val_ / avi_->val_) > 10) return; avi_->adj_ += adj_ * grad_reg_lower_inc_gamma(avi_->val_, bvi_->val_, 1.0e-10); bvi_->adj_ += adj_ * std::exp(-bvi_->val_ + (avi_->val_ - 1.0) * std::log(bvi_->val_) - lgamma(avi_->val_)); } }; class gamma_p_vd_vari : public op_vd_vari { public: gamma_p_vd_vari(vari* avi, double b) : op_vd_vari(gamma_p(avi->val_, b), avi, b) {} void chain() { if (is_inf(avi_->val_)) { avi_->adj_ += std::numeric_limits<double>::quiet_NaN(); return; } if (is_inf(bd_)) { avi_->adj_ += std::numeric_limits<double>::quiet_NaN(); return; } // return zero derivative as gamma_p is flat // to machine precision for b / a > 10 if (std::fabs(bd_ / avi_->val_) > 10) return; avi_->adj_ += adj_ * grad_reg_lower_inc_gamma(avi_->val_, bd_, 1.0e-10); } }; class gamma_p_dv_vari : public op_dv_vari { public: gamma_p_dv_vari(double a, vari* bvi) : op_dv_vari(gamma_p(a, bvi->val_), a, bvi) {} void chain() { if (is_inf(ad_)) { bvi_->adj_ += std::numeric_limits<double>::quiet_NaN(); return; } if (is_inf(bvi_->val_)) { bvi_->adj_ += std::numeric_limits<double>::quiet_NaN(); return; } // return zero derivative as gamma_p is flat to // machine precision for b / a > 10 if (std::fabs(bvi_->val_ / ad_) > 10) return; bvi_->adj_ += adj_ * std::exp(-bvi_->val_ + (ad_ - 1.0) * std::log(bvi_->val_) - lgamma(ad_)); } }; } inline var gamma_p(const var& a, const var& b) { return var(new gamma_p_vv_vari(a.vi_, b.vi_)); } inline var gamma_p(const var& a, double b) { return var(new gamma_p_vd_vari(a.vi_, b)); } inline var gamma_p(double a, const var& b) { return var(new gamma_p_dv_vari(a, b.vi_)); } } // namespace math } // namespace stan #endif <commit_msg>[Jenkins] auto-formatting by clang-format version 5.0.1 (tags/RELEASE_501/final)<commit_after>#ifndef STAN_MATH_REV_SCAL_FUN_GAMMA_P_HPP #define STAN_MATH_REV_SCAL_FUN_GAMMA_P_HPP #include <stan/math/rev/core.hpp> #include <stan/math/prim/scal/fun/is_inf.hpp> #include <stan/math/prim/scal/err/domain_error.hpp> #include <stan/math/prim/scal/fun/digamma.hpp> #include <stan/math/prim/scal/fun/gamma_p.hpp> #include <stan/math/prim/scal/fun/lgamma.hpp> #include <stan/math/prim/scal/fun/grad_reg_lower_inc_gamma.hpp> #include <valarray> #include <limits> namespace stan { namespace math { namespace { class gamma_p_vv_vari : public op_vv_vari { public: gamma_p_vv_vari(vari* avi, vari* bvi) : op_vv_vari(gamma_p(avi->val_, bvi->val_), avi, bvi) {} void chain() { using boost::math::lgamma; using std::exp; using std::fabs; using std::log; if (is_inf(avi_->val_)) { avi_->adj_ += std::numeric_limits<double>::quiet_NaN(); bvi_->adj_ += std::numeric_limits<double>::quiet_NaN(); return; } if (is_inf(bvi_->val_)) { avi_->adj_ += std::numeric_limits<double>::quiet_NaN(); bvi_->adj_ += std::numeric_limits<double>::quiet_NaN(); return; } // return zero derivative as gamma_p is flat // to machine precision for b / a > 10 if (std::fabs(bvi_->val_ / avi_->val_) > 10) return; avi_->adj_ += adj_ * grad_reg_lower_inc_gamma(avi_->val_, bvi_->val_, 1.0e-10); bvi_->adj_ += adj_ * std::exp(-bvi_->val_ + (avi_->val_ - 1.0) * std::log(bvi_->val_) - lgamma(avi_->val_)); } }; class gamma_p_vd_vari : public op_vd_vari { public: gamma_p_vd_vari(vari* avi, double b) : op_vd_vari(gamma_p(avi->val_, b), avi, b) {} void chain() { if (is_inf(avi_->val_)) { avi_->adj_ += std::numeric_limits<double>::quiet_NaN(); return; } if (is_inf(bd_)) { avi_->adj_ += std::numeric_limits<double>::quiet_NaN(); return; } // return zero derivative as gamma_p is flat // to machine precision for b / a > 10 if (std::fabs(bd_ / avi_->val_) > 10) return; avi_->adj_ += adj_ * grad_reg_lower_inc_gamma(avi_->val_, bd_, 1.0e-10); } }; class gamma_p_dv_vari : public op_dv_vari { public: gamma_p_dv_vari(double a, vari* bvi) : op_dv_vari(gamma_p(a, bvi->val_), a, bvi) {} void chain() { if (is_inf(ad_)) { bvi_->adj_ += std::numeric_limits<double>::quiet_NaN(); return; } if (is_inf(bvi_->val_)) { bvi_->adj_ += std::numeric_limits<double>::quiet_NaN(); return; } // return zero derivative as gamma_p is flat to // machine precision for b / a > 10 if (std::fabs(bvi_->val_ / ad_) > 10) return; bvi_->adj_ += adj_ * std::exp(-bvi_->val_ + (ad_ - 1.0) * std::log(bvi_->val_) - lgamma(ad_)); } }; } // namespace inline var gamma_p(const var& a, const var& b) { return var(new gamma_p_vv_vari(a.vi_, b.vi_)); } inline var gamma_p(const var& a, double b) { return var(new gamma_p_vd_vari(a.vi_, b)); } inline var gamma_p(double a, const var& b) { return var(new gamma_p_dv_vari(a, b.vi_)); } } // namespace math } // namespace stan #endif <|endoftext|>
<commit_before>#ifndef AST_LIST_NODE_HPP #define AST_LIST_NODE_HPP #include <memory> #include <vector> namespace ast { template <typename wrapped> class list_node; class expression; class index_expression; class statement; template<typename wrapped> class list_node : public node { public: typedef std::shared_ptr<wrapped> wrapped_p; public: list_node() = default; virtual ~list_node() = default; std::vector<wrapped_p> items; void add_front(wrapped_p item) { items.insert(items.begin(), item); } size_t size() { return items.size(); } auto begin() { return items.begin(); } auto end() { return items.end(); } public: virtual void accept(visitor_p guest); virtual void children_accept(visitor_p guest); virtual void traverse_top_down(visitor_p guest); virtual void traverse_bottom_up(visitor_p guest); }; } /* namespace ast */ #endif /* AST_LIST_NODE_HPP */<commit_msg>Remove some unneeded forward decls from list_node<commit_after>#ifndef AST_LIST_NODE_HPP #define AST_LIST_NODE_HPP #include <memory> #include <vector> namespace ast { template<typename wrapped> class list_node : public node { public: typedef std::shared_ptr<wrapped> wrapped_p; public: list_node() = default; virtual ~list_node() = default; std::vector<wrapped_p> items; void add_front(wrapped_p item) { items.insert(items.begin(), item); } size_t size() { return items.size(); } auto begin() { return items.begin(); } auto end() { return items.end(); } public: virtual void accept(visitor_p guest); virtual void children_accept(visitor_p guest); virtual void traverse_top_down(visitor_p guest); virtual void traverse_bottom_up(visitor_p guest); }; } /* namespace ast */ #endif /* AST_LIST_NODE_HPP */<|endoftext|>
<commit_before>#pragma once #include <string> #include <vector> #include <boost/container/small_vector.hpp> #include <boost/range/adaptor/transformed.hpp> #include <boost/range/any_range.hpp> #include <boost/range/join.hpp> #include <boost/variant/variant.hpp> #include <boost/variant/apply_visitor.hpp> #include <boost/variant/static_visitor.hpp> #define FMT_HEADER_ONLY #include <cppformat/format.h> #include "blackhole/cpp17/string_view.hpp" #include "blackhole/sandbox.hpp" namespace blackhole { namespace cppformat = fmt; using cpp17::string_view; class scoped_t {}; using inner1_t = boost::variant< std::int64_t, double, string_view >; // mpl::transform + into_owned. using inner2_t = boost::variant< std::int64_t, double, std::string >; class owned_attribute_value_t { public: inner2_t inner; owned_attribute_value_t(int v): inner(static_cast<std::int64_t>(v)) {} owned_attribute_value_t(double v): inner(v) {} owned_attribute_value_t(std::string v): inner(std::move(v)) {} }; struct from_owned_t : public boost::static_visitor<inner1_t> { template<typename T> inner1_t operator()(const T& v) const { return v; } }; class attribute_value_t { public: inner1_t inner; attribute_value_t(int v): inner(static_cast<std::int64_t>(v)) {} attribute_value_t(double v): inner(v) {} attribute_value_t(string_view v): inner(v) {} attribute_value_t(const owned_attribute_value_t& v): inner(boost::apply_visitor(from_owned_t(), v.inner)) {} }; // using attributes_t = std::vector<std::pair<string_view, attribute_value_t>>; using attributes_t = boost::container::small_vector<std::pair<string_view, attribute_value_t>, 16>; class record_t { // struct { // string_view message; // } d; public: auto message() const -> string_view; auto severity() const -> int { return 0; } // std::chrono::time_point timestamp() const; const attributes_t& attributes() const; }; typedef boost::any_range< std::pair<string_view, attribute_value_t>, boost::forward_traversal_tag > range_type; class writer_t; class formatter_t { public: virtual ~formatter_t(); virtual auto format(const record_t& record, writer_t& writer) -> void = 0; }; class sink_t { virtual sink_t(); virtual auto filter(const record_t& record) -> bool = 0; virtual auto execute(const record_t& record, string_view formatted) -> void = 0; }; class handler_t { public: auto set(std::unique_ptr<formatter_t> formatter) -> void; auto add(std::unique_ptr<sink_t> sink) -> void; auto execute(const record_t& record) -> void; }; class log_t { public: typedef std::function<bool(const record_t&)> filter_type; private: struct inner_t; std::shared_ptr<inner_t> inner; public: log_t(); ~log_t(); auto filter(filter_type fn) -> void; /// \note it's faster to provide a string literal instead of `std::string`. void info(string_view message); void info(string_view message, const attributes_t& attributes); void info_with_range(string_view message, const range_type& range) { for (const auto& attribute : range) { } } // template<typename Range> // void // info_with_range(string_view message, const Range& range) { // for (const auto& attribute : range) { // } // } template<typename T, typename... Args> void info(string_view message, const T& arg, const Args&... args) { cppformat::MemoryWriter wr; wr.write(message.data(), arg, args...); info({wr.data(), wr.size()}); } template<typename T, typename... Args> void info(string_view message, const attributes_t& attributes, const T& arg, const Args&... args) { cppformat::MemoryWriter wr; wr.write(message.data(), arg, args...); info({wr.data(), wr.size()}, attributes); } #ifdef __cpp_constexpr template<std::size_t N, typename T, typename... Args> void info(const detail::formatter<N>& formatter, const T& arg, const Args&... args) { fmt::MemoryWriter wr; formatter.format(wr, arg, args...); info({wr.data(), wr.size()}); } #endif scoped_t scoped(attributes_t); }; using owned_attributes_t = boost::container::small_vector<std::pair<std::string, owned_attribute_value_t>, 16>; class wrapper_t { public: log_t& log; owned_attributes_t attributes; template<typename T, typename... Args> void info(string_view message, const attributes_t& attributes, const T& arg, const Args&... args) { const auto range = this->attributes | boost::adaptors::transformed(+[](const std::pair<std::string, owned_attribute_value_t>& v) -> std::pair<string_view, attribute_value_t> { return std::make_pair(v.first, v.second); } ); // filter. cppformat::MemoryWriter wr; wr.write(message.data(), arg, args...); log.info_with_range({wr.data(), wr.size()}, boost::range::join(range, attributes)); } }; } // namespace blackhole <commit_msg>fix(sink): fix typo in virtual destructor<commit_after>#pragma once #include <string> #include <vector> #include <boost/container/small_vector.hpp> #include <boost/range/adaptor/transformed.hpp> #include <boost/range/any_range.hpp> #include <boost/range/join.hpp> #include <boost/variant/variant.hpp> #include <boost/variant/apply_visitor.hpp> #include <boost/variant/static_visitor.hpp> #define FMT_HEADER_ONLY #include <cppformat/format.h> #include "blackhole/cpp17/string_view.hpp" #include "blackhole/sandbox.hpp" namespace blackhole { namespace cppformat = fmt; using cpp17::string_view; class scoped_t {}; using inner1_t = boost::variant< std::int64_t, double, string_view >; // mpl::transform + into_owned. using inner2_t = boost::variant< std::int64_t, double, std::string >; class owned_attribute_value_t { public: inner2_t inner; owned_attribute_value_t(int v): inner(static_cast<std::int64_t>(v)) {} owned_attribute_value_t(double v): inner(v) {} owned_attribute_value_t(std::string v): inner(std::move(v)) {} }; struct from_owned_t : public boost::static_visitor<inner1_t> { template<typename T> inner1_t operator()(const T& v) const { return v; } }; class attribute_value_t { public: inner1_t inner; attribute_value_t(int v): inner(static_cast<std::int64_t>(v)) {} attribute_value_t(double v): inner(v) {} attribute_value_t(string_view v): inner(v) {} attribute_value_t(const owned_attribute_value_t& v): inner(boost::apply_visitor(from_owned_t(), v.inner)) {} }; // using attributes_t = std::vector<std::pair<string_view, attribute_value_t>>; using attributes_t = boost::container::small_vector<std::pair<string_view, attribute_value_t>, 16>; class record_t { // struct { // string_view message; // } d; public: auto message() const -> string_view; auto severity() const -> int { return 0; } // std::chrono::time_point timestamp() const; const attributes_t& attributes() const; }; typedef boost::any_range< std::pair<string_view, attribute_value_t>, boost::forward_traversal_tag > range_type; class writer_t; class formatter_t { public: virtual ~formatter_t(); virtual auto format(const record_t& record, writer_t& writer) -> void = 0; }; class sink_t { virtual ~sink_t(); virtual auto filter(const record_t& record) -> bool = 0; virtual auto execute(const record_t& record, string_view formatted) -> void = 0; }; class handler_t { public: auto set(std::unique_ptr<formatter_t> formatter) -> void; auto add(std::unique_ptr<sink_t> sink) -> void; auto execute(const record_t& record) -> void; }; class log_t { public: typedef std::function<bool(const record_t&)> filter_type; private: struct inner_t; std::shared_ptr<inner_t> inner; public: log_t(); ~log_t(); auto filter(filter_type fn) -> void; /// \note it's faster to provide a string literal instead of `std::string`. void info(string_view message); void info(string_view message, const attributes_t& attributes); void info_with_range(string_view message, const range_type& range) { for (const auto& attribute : range) { } } // template<typename Range> // void // info_with_range(string_view message, const Range& range) { // for (const auto& attribute : range) { // } // } template<typename T, typename... Args> void info(string_view message, const T& arg, const Args&... args) { cppformat::MemoryWriter wr; wr.write(message.data(), arg, args...); info({wr.data(), wr.size()}); } template<typename T, typename... Args> void info(string_view message, const attributes_t& attributes, const T& arg, const Args&... args) { cppformat::MemoryWriter wr; wr.write(message.data(), arg, args...); info({wr.data(), wr.size()}, attributes); } #ifdef __cpp_constexpr template<std::size_t N, typename T, typename... Args> void info(const detail::formatter<N>& formatter, const T& arg, const Args&... args) { fmt::MemoryWriter wr; formatter.format(wr, arg, args...); info({wr.data(), wr.size()}); } #endif scoped_t scoped(attributes_t); }; using owned_attributes_t = boost::container::small_vector<std::pair<std::string, owned_attribute_value_t>, 16>; class wrapper_t { public: log_t& log; owned_attributes_t attributes; template<typename T, typename... Args> void info(string_view message, const attributes_t& attributes, const T& arg, const Args&... args) { const auto range = this->attributes | boost::adaptors::transformed(+[](const std::pair<std::string, owned_attribute_value_t>& v) -> std::pair<string_view, attribute_value_t> { return std::make_pair(v.first, v.second); } ); // filter. cppformat::MemoryWriter wr; wr.write(message.data(), arg, args...); log.info_with_range({wr.data(), wr.size()}, boost::range::join(range, attributes)); } }; } // namespace blackhole <|endoftext|>
<commit_before>#pragma once #include "common.hpp" #include "components/ipc.hpp" #include "components/parser.hpp" #include "components/types.hpp" #include "utils/functional.hpp" POLYBAR_NS // fwd enum class mousebtn; enum class syntaxtag; enum class alignment; enum class attribute; namespace signals { namespace detail { class signal { public: explicit signal() = default; virtual ~signal() {} virtual size_t size() const = 0; }; template <typename Derived> class base_signal : public signal { public: using base_type = base_signal<Derived>; explicit base_signal() = default; virtual ~base_signal() {} virtual size_t size() const override { return sizeof(Derived); }; }; template <typename Derived, typename ValueType> class value_signal : public base_signal<Derived> { public: using base_type = value_signal<Derived, ValueType>; explicit value_signal(void* data) : m_ptr(data) {} explicit value_signal(ValueType&& data) : m_ptr(&data) {} virtual ~value_signal() {} inline ValueType cast() const { return *static_cast<ValueType*>(m_ptr); } private: void* m_ptr; }; } namespace eventqueue { struct start : public detail::base_signal<start> { using base_type::base_type; }; struct exit_terminate : public detail::base_signal<exit_terminate> { using base_type::base_type; }; struct exit_reload : public detail::base_signal<exit_reload> { using base_type::base_type; }; struct notify_change : public detail::base_signal<notify_change> { using base_type::base_type; }; struct notify_forcechange : public detail::base_signal<notify_forcechange> { using base_type::base_type; }; struct check_state : public detail::base_signal<check_state> { using base_type::base_type; }; } namespace ipc { struct command : public detail::value_signal<command, string> { using base_type::base_type; }; struct hook : public detail::value_signal<hook, string> { using base_type::base_type; }; struct action : public detail::value_signal<action, string> { using base_type::base_type; }; } namespace ui { struct ready : public detail::base_signal<ready> { using base_type::base_type; }; struct changed : public detail::base_signal<changed> { using base_type::base_type; }; struct tick : public detail::base_signal<tick> { using base_type::base_type; }; struct button_press : public detail::value_signal<button_press, string> { using base_type::base_type; }; struct cursor_change : public detail::value_signal<cursor_change, string> { using base_type::base_type; }; struct visibility_change : public detail::value_signal<visibility_change, bool> { using base_type::base_type; }; struct dim_window : public detail::value_signal<dim_window, double> { using base_type::base_type; }; struct shade_window : public detail::base_signal<shade_window> { using base_type::base_type; }; struct unshade_window : public detail::base_signal<unshade_window> { using base_type::base_type; }; struct request_snapshot : public detail::value_signal<request_snapshot, string> { using base_type::base_type; }; struct update_background : public detail::base_signal<update_background> { using base_type::base_type; }; struct update_geometry : public detail::base_signal<update_geometry> { using base_type::base_type; }; } namespace ui_tray { struct mapped_clients : public detail::value_signal<mapped_clients, unsigned int> { using base_type::base_type; }; } namespace parser { struct change_background : public detail::value_signal<change_background, unsigned int> { using base_type::base_type; }; struct change_foreground : public detail::value_signal<change_foreground, unsigned int> { using base_type::base_type; }; struct change_underline : public detail::value_signal<change_underline, unsigned int> { using base_type::base_type; }; struct change_overline : public detail::value_signal<change_overline, unsigned int> { using base_type::base_type; }; struct change_font : public detail::value_signal<change_font, int> { using base_type::base_type; }; struct change_alignment : public detail::value_signal<change_alignment, alignment> { using base_type::base_type; }; struct reverse_colors : public detail::base_signal<reverse_colors> { using base_type::base_type; }; struct offset_pixel : public detail::value_signal<offset_pixel, int> { using base_type::base_type; }; struct attribute_set : public detail::value_signal<attribute_set, attribute> { using base_type::base_type; }; struct attribute_unset : public detail::value_signal<attribute_unset, attribute> { using base_type::base_type; }; struct attribute_toggle : public detail::value_signal<attribute_toggle, attribute> { using base_type::base_type; }; struct action_begin : public detail::value_signal<action_begin, action> { using base_type::base_type; }; struct action_end : public detail::value_signal<action_end, mousebtn> { using base_type::base_type; }; struct text : public detail::value_signal<text, string> { using base_type::base_type; }; } } POLYBAR_NS_END <commit_msg>docs(signal): document newly added signals<commit_after>#pragma once #include "common.hpp" #include "components/ipc.hpp" #include "components/parser.hpp" #include "components/types.hpp" #include "utils/functional.hpp" POLYBAR_NS // fwd enum class mousebtn; enum class syntaxtag; enum class alignment; enum class attribute; namespace signals { namespace detail { class signal { public: explicit signal() = default; virtual ~signal() {} virtual size_t size() const = 0; }; template <typename Derived> class base_signal : public signal { public: using base_type = base_signal<Derived>; explicit base_signal() = default; virtual ~base_signal() {} virtual size_t size() const override { return sizeof(Derived); }; }; template <typename Derived, typename ValueType> class value_signal : public base_signal<Derived> { public: using base_type = value_signal<Derived, ValueType>; explicit value_signal(void* data) : m_ptr(data) {} explicit value_signal(ValueType&& data) : m_ptr(&data) {} virtual ~value_signal() {} inline ValueType cast() const { return *static_cast<ValueType*>(m_ptr); } private: void* m_ptr; }; } namespace eventqueue { struct start : public detail::base_signal<start> { using base_type::base_type; }; struct exit_terminate : public detail::base_signal<exit_terminate> { using base_type::base_type; }; struct exit_reload : public detail::base_signal<exit_reload> { using base_type::base_type; }; struct notify_change : public detail::base_signal<notify_change> { using base_type::base_type; }; struct notify_forcechange : public detail::base_signal<notify_forcechange> { using base_type::base_type; }; struct check_state : public detail::base_signal<check_state> { using base_type::base_type; }; } namespace ipc { struct command : public detail::value_signal<command, string> { using base_type::base_type; }; struct hook : public detail::value_signal<hook, string> { using base_type::base_type; }; struct action : public detail::value_signal<action, string> { using base_type::base_type; }; } namespace ui { struct ready : public detail::base_signal<ready> { using base_type::base_type; }; struct changed : public detail::base_signal<changed> { using base_type::base_type; }; struct tick : public detail::base_signal<tick> { using base_type::base_type; }; struct button_press : public detail::value_signal<button_press, string> { using base_type::base_type; }; struct cursor_change : public detail::value_signal<cursor_change, string> { using base_type::base_type; }; struct visibility_change : public detail::value_signal<visibility_change, bool> { using base_type::base_type; }; struct dim_window : public detail::value_signal<dim_window, double> { using base_type::base_type; }; struct shade_window : public detail::base_signal<shade_window> { using base_type::base_type; }; struct unshade_window : public detail::base_signal<unshade_window> { using base_type::base_type; }; struct request_snapshot : public detail::value_signal<request_snapshot, string> { using base_type::base_type; }; /// emitted whenever the desktop background slice changes struct update_background : public detail::base_signal<update_background> { using base_type::base_type; }; /// emitted when the bar geometry changes (such as position of the bar on the screen) struct update_geometry : public detail::base_signal<update_geometry> { using base_type::base_type; }; } namespace ui_tray { struct mapped_clients : public detail::value_signal<mapped_clients, unsigned int> { using base_type::base_type; }; } namespace parser { struct change_background : public detail::value_signal<change_background, unsigned int> { using base_type::base_type; }; struct change_foreground : public detail::value_signal<change_foreground, unsigned int> { using base_type::base_type; }; struct change_underline : public detail::value_signal<change_underline, unsigned int> { using base_type::base_type; }; struct change_overline : public detail::value_signal<change_overline, unsigned int> { using base_type::base_type; }; struct change_font : public detail::value_signal<change_font, int> { using base_type::base_type; }; struct change_alignment : public detail::value_signal<change_alignment, alignment> { using base_type::base_type; }; struct reverse_colors : public detail::base_signal<reverse_colors> { using base_type::base_type; }; struct offset_pixel : public detail::value_signal<offset_pixel, int> { using base_type::base_type; }; struct attribute_set : public detail::value_signal<attribute_set, attribute> { using base_type::base_type; }; struct attribute_unset : public detail::value_signal<attribute_unset, attribute> { using base_type::base_type; }; struct attribute_toggle : public detail::value_signal<attribute_toggle, attribute> { using base_type::base_type; }; struct action_begin : public detail::value_signal<action_begin, action> { using base_type::base_type; }; struct action_end : public detail::value_signal<action_end, mousebtn> { using base_type::base_type; }; struct text : public detail::value_signal<text, string> { using base_type::base_type; }; } } POLYBAR_NS_END <|endoftext|>
<commit_before>#ifndef NAMELESSGUI_WIDGET_HPP #define NAMELESSGUI_WIDGET_HPP #include <SFML/Window/Window.hpp> #include <SFML/Window/Event.hpp> #include <SFML/Graphics/Drawable.hpp> #include "gui/ng/signal.hpp" #include "gui/ng/singleparametersignal.hpp" namespace namelessgui { class Widget : public sf::Drawable { public: Widget(sf::Window* window, float width, float height); Widget(sf::Window* window, sf::Vector2f size); ~Widget(); void handleEvent(const sf::Event& event); void setVisible(bool visibility = true); void disconnectAllSignals(); void setSize(sf::Vector2f size); sf::Vector2f getSize() const; virtual sf::FloatRect getGlobalBounds() = 0; // Signals Signal signalclicked; Signal signalrightclicked; Signal signalmouseentered; Signal signalmouseleft; Signal signalmousemoved; Signal signalleftmousebuttonpressed; SingleParameterSignal<const sf::Event&> signalkeypressed; protected: bool hasMouseFocus(); const sf::Window* window; private: /** * @brief Registeres when left mouse button is pressed. * * Is set to true if the left mouse button was pressed while mouse cursor was on the widget. If the mouse * is released again while on the widget a click event took place. Reset leftMouseButtonpressRegistered if * mouse leaves focus. */ bool leftMouseButtonPressRegistered; /** * @brief Registeres when right mouse button is pressed. * * Is set to true if the right mouse button was pressed while mouse cursor was on the widget. If the mouse * is released again while on the widget a click event took place. Reset leftMouseButtonpressRegistered if * mouse leaves focus. */ bool rightMouseButtonPressRegistered; /** * @brief Saves the last known mouse focus state. * * Is used to determine if a signalmouseleft or signalmouseentered signal has to be emitted. It holds the last * known mouse focus state which means that in case of mouseFocus followed by hasMouseFocus() == true the mouse * cursor entered the widget or other way round left the widget. */ bool mouseFocus; bool visible; /** * Holds size of the widget. */ sf::Vector2f size; }; } #endif <commit_msg>Made namelessgui::Widget::visible protected.<commit_after>#ifndef NAMELESSGUI_WIDGET_HPP #define NAMELESSGUI_WIDGET_HPP #include <SFML/Window/Window.hpp> #include <SFML/Window/Event.hpp> #include <SFML/Graphics/Drawable.hpp> #include "gui/ng/signal.hpp" #include "gui/ng/singleparametersignal.hpp" namespace namelessgui { class Widget : public sf::Drawable { public: Widget(sf::Window* window, float width, float height); Widget(sf::Window* window, sf::Vector2f size); ~Widget(); void handleEvent(const sf::Event& event); void setVisible(bool visibility = true); void disconnectAllSignals(); void setSize(sf::Vector2f size); sf::Vector2f getSize() const; virtual sf::FloatRect getGlobalBounds() = 0; // Signals Signal signalclicked; Signal signalrightclicked; Signal signalmouseentered; Signal signalmouseleft; Signal signalmousemoved; Signal signalleftmousebuttonpressed; SingleParameterSignal<const sf::Event&> signalkeypressed; protected: bool hasMouseFocus(); const sf::Window* window; bool visible; private: /** * @brief Registeres when left mouse button is pressed. * * Is set to true if the left mouse button was pressed while mouse cursor was on the widget. If the mouse * is released again while on the widget a click event took place. Reset leftMouseButtonpressRegistered if * mouse leaves focus. */ bool leftMouseButtonPressRegistered; /** * @brief Registeres when right mouse button is pressed. * * Is set to true if the right mouse button was pressed while mouse cursor was on the widget. If the mouse * is released again while on the widget a click event took place. Reset leftMouseButtonpressRegistered if * mouse leaves focus. */ bool rightMouseButtonPressRegistered; /** * @brief Saves the last known mouse focus state. * * Is used to determine if a signalmouseleft or signalmouseentered signal has to be emitted. It holds the last * known mouse focus state which means that in case of mouseFocus followed by hasMouseFocus() == true the mouse * cursor entered the widget or other way round left the widget. */ bool mouseFocus; /** * Holds size of the widget. */ sf::Vector2f size; }; } #endif <|endoftext|>
<commit_before>/* _______ __ __ __ ______ __ __ _______ __ __ * / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___ /\ / |\/ /\ * / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / / * / / /__ / / // / // / // / / / ___ / // ___ / // /| ' / / * / /_// /\ / /_// / // / // /_/_ / / // / // /\_/ / // / | / / * /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ / * \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/ * * Copyright (c) 2004, 2005, 2006, 2007 Olof Naessn and Per Larsson * * Js_./ * Per Larsson a.k.a finalman _RqZ{a<^_aa * Olof Naessn a.k.a jansem/yakslem _asww7!uY`> )\a// * _Qhm`] _f "'c 1!5m * Visit: http://guichan.darkbits.org )Qk<P ` _: :+' .' "{[ * .)j(] .d_/ '-( P . S * License: (BSD) <Td/Z <fP"5(\"??"\a. .L * Redistribution and use in source and _dV>ws?a-?' ._/L #' * binary forms, with or without )4d[#7r, . ' )d`)[ * modification, are permitted provided _Q-5'5W..j/?' -?!\)cam' * that the following conditions are met: j<<WP+k/);. _W=j f * 1. Redistributions of source code must .$%w\/]Q . ."' . mj$ * retain the above copyright notice, ]E.pYY(Q]>. a J@\ * this list of conditions and the j(]1u<sE"L,. . ./^ ]{a * following disclaimer. 4'_uomm\. )L);-4 (3= * 2. Redistributions in binary form must )_]X{Z('a_"a7'<a"a, ]"[ * reproduce the above copyright notice, #}<]m7`Za??4,P-"'7. ).m * this list of conditions and the ]d2e)Q(<Q( ?94 b- LQ/ * following disclaimer in the <B!</]C)d_, '(<' .f. =C+m * documentation and/or other materials .Z!=J ]e []('-4f _ ) -.)m]' * provided with the distribution. .w[5]' _[ /.)_-"+? _/ <W" * 3. Neither the name of Guichan nor the :$we` _! + _/ . j? * names of its contributors may be used =3)= _f (_yQmWW$#( " * to endorse or promote products derived - W, sQQQQmZQ#Wwa].. * from this software without specific (js, \[QQW$QWW#?!V"". * prior written permission. ]y:.<\.. . * -]n w/ ' [. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT )/ )/ ! * HOLDERS AND CONTRIBUTORS "AS IS" AND ANY < (; sac , ' * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, ]^ .- % * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF c < r * MERCHANTABILITY AND FITNESS FOR A PARTICULAR aga< <La * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 5% )P'-3L * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR _bQf` y`..)a * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, ,J?4P'.P"_(\?d'., * EXEMPLARY, OR CONSEQUENTIAL DAMAGES _Pa,)!f/<[]/ ?" * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT _2-..:. .r+_,.. . * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ?a.<%"' " -'.a_ _, * 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. */ #ifndef GCN_IMAGE_HPP #define GCN_IMAGE_HPP #include <string> #include "guichan/platform.hpp" namespace gcn { class Color; class ImageLoader; /** * Holds an image. To be able to use this class you must first set an * ImageLoader in Image by calling * @code Image::setImageLoader(myImageLoader) @endcode * The function is static. If this is not done, the constructor taking a * filename will throw an exception. The ImageLoader you use must be * compatible with the Graphics object you use. * * EXAMPLE: If you use SDLGraphics you should use SDLImageLoader. * Otherwise your program will crash in a most bizarre way. */ class GCN_CORE_DECLSPEC Image { public: /** * Constructor. */ Image(); /** * Destructor. */ virtual ~Image(); /** * Loads an image by calling the Image class' ImageLoader. * * NOTE: The functions getPixel and putPixel are only guaranteed to work * before an image has been converted to display format. * * @param filename the file to load. * @param convertToDisplayFormat true if the image should be converted * to display, false otherwise. */ static Image* load(const std::string& filename, bool convertToDisplayFormat = true); /** * Gets the ImageLoader used for loading Images. * * @return the ImageLoader used for loading Images. * @see SDLImageLoader, AllegroImageLoader */ static ImageLoader* getImageLoader(); /** * Sets the ImageLoader to be used for loading images. * * IMPORTANT: The ImageLoader is static and MUST be set before loading * images! * * @param imageLoader the ImageLoader to be used for loading images. * @see SDLImageLoader, AllegroImageLoader */ static void setImageLoader(ImageLoader* imageLoader); /** * Frees an image. */ virtual void free() = 0; /** * Gets the width of the Image. * * @return the image width */ virtual int getWidth() const = 0; /** * Gets the height of the Image. * * @return the image height */ virtual int getHeight() const = 0; /** * Gets the color of a pixel at coordinate (x, y) in the image. * * IMPORTANT: Only guaranteed to work before the image has been * converted to display format. * * @param x the x coordinate. * @param y the y coordinate. * @return the color of the pixel. */ virtual Color getPixel(int x, int y) = 0; /** * Puts a pixel with a certain color at coordinate (x, y). * * @param x the x coordinate. * @param y the y coordinate. * @param color the color of the pixel to put. */ virtual void putPixel(int x, int y, const Color& color) = 0; /** * Converts the image, if possible, to display format. * * IMPORTANT: Only guaranteed to work before the image has been * converted to display format. */ virtual void convertToDisplayFormat() = 0; protected: static ImageLoader* mImageLoader; }; } #endif // end GCN_IMAGE_HPP <commit_msg>Documentation has been improved.<commit_after>/* _______ __ __ __ ______ __ __ _______ __ __ * / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___ /\ / |\/ /\ * / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / / * / / /__ / / // / // / // / / / ___ / // ___ / // /| ' / / * / /_// /\ / /_// / // / // /_/_ / / // / // /\_/ / // / | / / * /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ / * \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/ * * Copyright (c) 2004, 2005, 2006, 2007 Olof Naessn and Per Larsson * * Js_./ * Per Larsson a.k.a finalman _RqZ{a<^_aa * Olof Naessn a.k.a jansem/yakslem _asww7!uY`> )\a// * _Qhm`] _f "'c 1!5m * Visit: http://guichan.darkbits.org )Qk<P ` _: :+' .' "{[ * .)j(] .d_/ '-( P . S * License: (BSD) <Td/Z <fP"5(\"??"\a. .L * Redistribution and use in source and _dV>ws?a-?' ._/L #' * binary forms, with or without )4d[#7r, . ' )d`)[ * modification, are permitted provided _Q-5'5W..j/?' -?!\)cam' * that the following conditions are met: j<<WP+k/);. _W=j f * 1. Redistributions of source code must .$%w\/]Q . ."' . mj$ * retain the above copyright notice, ]E.pYY(Q]>. a J@\ * this list of conditions and the j(]1u<sE"L,. . ./^ ]{a * following disclaimer. 4'_uomm\. )L);-4 (3= * 2. Redistributions in binary form must )_]X{Z('a_"a7'<a"a, ]"[ * reproduce the above copyright notice, #}<]m7`Za??4,P-"'7. ).m * this list of conditions and the ]d2e)Q(<Q( ?94 b- LQ/ * following disclaimer in the <B!</]C)d_, '(<' .f. =C+m * documentation and/or other materials .Z!=J ]e []('-4f _ ) -.)m]' * provided with the distribution. .w[5]' _[ /.)_-"+? _/ <W" * 3. Neither the name of Guichan nor the :$we` _! + _/ . j? * names of its contributors may be used =3)= _f (_yQmWW$#( " * to endorse or promote products derived - W, sQQQQmZQ#Wwa].. * from this software without specific (js, \[QQW$QWW#?!V"". * prior written permission. ]y:.<\.. . * -]n w/ ' [. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT )/ )/ ! * HOLDERS AND CONTRIBUTORS "AS IS" AND ANY < (; sac , ' * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, ]^ .- % * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF c < r * MERCHANTABILITY AND FITNESS FOR A PARTICULAR aga< <La * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 5% )P'-3L * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR _bQf` y`..)a * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, ,J?4P'.P"_(\?d'., * EXEMPLARY, OR CONSEQUENTIAL DAMAGES _Pa,)!f/<[]/ ?" * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT _2-..:. .r+_,.. . * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ?a.<%"' " -'.a_ _, * 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. */ #ifndef GCN_IMAGE_HPP #define GCN_IMAGE_HPP #include <string> #include "guichan/platform.hpp" namespace gcn { class Color; class ImageLoader; /** * Holds an image. To be able to use this class you must first set an * ImageLoader in Image by calling * @code Image::setImageLoader(myImageLoader) @endcode * The function is static. If this is not done, the constructor taking a * filename will throw an exception. The ImageLoader you use must be * compatible with the Graphics object you use. * * EXAMPLE: If you use SDLGraphics you should use SDLImageLoader. * Otherwise your program will crash in a most bizarre way. */ class GCN_CORE_DECLSPEC Image { public: /** * Constructor. */ Image(); /** * Destructor. */ virtual ~Image(); /** * Loads an image by calling the Image class' ImageLoader. With most image loaders * you can assume a newly instantiated image is return which must be deleted in * order to avoid a memory leak. * * NOTE: The functions getPixel and putPixel are only guaranteed to work * before an image has been converted to display format. * * @param filename the file to load. * @param convertToDisplayFormat true if the image should be converted * to display, false otherwise. */ static Image* load(const std::string& filename, bool convertToDisplayFormat = true); /** * Gets the ImageLoader used for loading Images. * * @return the ImageLoader used for loading Images. * @see SDLImageLoader, AllegroImageLoader */ static ImageLoader* getImageLoader(); /** * Sets the ImageLoader to be used for loading images. * * IMPORTANT: The ImageLoader is static and MUST be set before loading * images! * * @param imageLoader the ImageLoader to be used for loading images. * @see SDLImageLoader, AllegroImageLoader */ static void setImageLoader(ImageLoader* imageLoader); /** * Frees an image. */ virtual void free() = 0; /** * Gets the width of the Image. * * @return the image width */ virtual int getWidth() const = 0; /** * Gets the height of the Image. * * @return the image height */ virtual int getHeight() const = 0; /** * Gets the color of a pixel at coordinate (x, y) in the image. * * IMPORTANT: Only guaranteed to work before the image has been * converted to display format. * * @param x the x coordinate. * @param y the y coordinate. * @return the color of the pixel. */ virtual Color getPixel(int x, int y) = 0; /** * Puts a pixel with a certain color at coordinate (x, y). * * @param x the x coordinate. * @param y the y coordinate. * @param color the color of the pixel to put. */ virtual void putPixel(int x, int y, const Color& color) = 0; /** * Converts the image, if possible, to display format. * * IMPORTANT: Only guaranteed to work before the image has been * converted to display format. */ virtual void convertToDisplayFormat() = 0; protected: static ImageLoader* mImageLoader; }; } #endif // end GCN_IMAGE_HPP <|endoftext|>
<commit_before>#include "stdafx.h" #include "AutowiringBenchmarkTest.h" #include "TestFixtures/SimpleObject.h" #include <boost/chrono/system_clocks.hpp> TEST_F(AutowiringBenchmarkTest, VerifySimplePerformance) { const size_t n = 10000; // Insert the object: AutoRequired<SimpleObject>(); // Time n hash map hits, in order to get a baseline: std::unordered_map<int, int> ref; ref[0] = 212; ref[1] = 21; boost::chrono::nanoseconds baseline; { auto start = boost::chrono::high_resolution_clock::now(); for(size_t i = n; i--;) ref[i % 2]; baseline = boost::chrono::high_resolution_clock::now() - start; } // Time n autowirings: boost::chrono::nanoseconds benchmark; { auto start = boost::chrono::high_resolution_clock::now(); for(size_t i = n; i--;) Autowired<SimpleObject>(); benchmark = (boost::chrono::high_resolution_clock::now() - start) / n; } EXPECT_GT(baseline * 3. / 2., benchmark) << "Average time to autowire one member was more than 3/2 of a hash map lookup"; } template<int N> struct dummy: public ContextMember {}; void InjectDummy(void) { Autowired<dummy<1>>(); Autowired<dummy<2>>(); Autowired<dummy<3>>(); Autowired<dummy<4>>(); Autowired<dummy<5>>(); Autowired<dummy<6>>(); Autowired<dummy<7>>(); Autowired<dummy<8>>(); Autowired<dummy<9>>(); Autowired<dummy<10>>(); Autowired<dummy<11>>(); Autowired<dummy<12>>(); Autowired<dummy<13>>(); Autowired<dummy<14>>(); Autowired<dummy<15>>(); Autowired<dummy<16>>(); Autowired<dummy<17>>(); Autowired<dummy<18>>(); Autowired<dummy<19>>(); Autowired<dummy<20>>(); Autowired<dummy<21>>(); Autowired<dummy<22>>(); Autowired<dummy<23>>(); Autowired<dummy<24>>(); Autowired<dummy<25>>(); }; #if defined(__GNUC__) && !defined(__clang__) TEST_F(AutowiringBenchmarkTest, DISABLED_VerifyAutowiringCache) #else TEST_F(AutowiringBenchmarkTest, VerifyAutowiringCache) #endif { boost::chrono::nanoseconds baseline(0); boost::chrono::nanoseconds benchmark(0); for(int i = 0; i<100; ++i) { AutoCreateContext ctxt; CurrentContextPusher pshr(ctxt); auto startBase = boost::chrono::high_resolution_clock::now(); InjectDummy(); baseline += boost::chrono::high_resolution_clock::now() - startBase; auto startBench = boost::chrono::high_resolution_clock::now(); InjectDummy(); benchmark += boost::chrono::high_resolution_clock::now() - startBench; } EXPECT_GT(baseline, benchmark) << "Autowiring cache not improving performance on subsequent autowirings"; } TEST_F(AutowiringBenchmarkTest, VerifyAutowiredFast) { { AutoCreateContext ctxt; CurrentContextPusher pshr(ctxt); AutoRequired<dummy<1>> foo; AutowiredFast<dummy<1>> bar; ASSERT_TRUE(foo) << "AutoRequred member not created"; EXPECT_TRUE(bar) << "AutowiredFast not satisfied"; } { AutoCreateContext ctxt; CurrentContextPusher pshr(ctxt); AutowiredFast<dummy<1>> fast; Autowired<dummy<1>> wired; AutoRequired<dummy<1>> required; ASSERT_TRUE(required) << "AutoRequired member not created"; EXPECT_TRUE(wired.IsAutowired()) << "Deferred Autowiring wasn't satisfied"; EXPECT_FALSE(fast) << "AutowiredFast member was deferred"; } } TEST_F(AutowiringBenchmarkTest, VerifyAutowiredFastPerformance) { boost::chrono::nanoseconds baseline; boost::chrono::nanoseconds benchmark; { // All of these tests will operate in the same context: AutoCreateContext ctxt; CurrentContextPusher pshr(ctxt); // Prime all memos: InjectDummy(); // Test simple autowiring first: auto startBase = boost::chrono::high_resolution_clock::now(); for(int i = 0; i < 500; ++i) InjectDummy(); baseline = boost::chrono::high_resolution_clock::now() - startBase; auto startBench = boost::chrono::high_resolution_clock::now(); for(int i = 0; i < 500; ++i) { AutowiredFast<dummy<1>>(); AutowiredFast<dummy<2>>(); AutowiredFast<dummy<3>>(); AutowiredFast<dummy<4>>(); AutowiredFast<dummy<5>>(); AutowiredFast<dummy<6>>(); AutowiredFast<dummy<7>>(); AutowiredFast<dummy<8>>(); AutowiredFast<dummy<9>>(); AutowiredFast<dummy<10>>(); AutowiredFast<dummy<11>>(); AutowiredFast<dummy<12>>(); AutowiredFast<dummy<13>>(); AutowiredFast<dummy<14>>(); AutowiredFast<dummy<15>>(); AutowiredFast<dummy<16>>(); AutowiredFast<dummy<17>>(); AutowiredFast<dummy<18>>(); AutowiredFast<dummy<19>>(); AutowiredFast<dummy<20>>(); } benchmark = boost::chrono::high_resolution_clock::now() - startBench; } EXPECT_GT(baseline, benchmark*1.75) << "Fast autowiring is slower than ordinary autowiring"; } <commit_msg>Disable unreliable VerifyAutowiringCache completely per Jason's recommendation, #9459<commit_after>#include "stdafx.h" #include "AutowiringBenchmarkTest.h" #include "TestFixtures/SimpleObject.h" #include <boost/chrono/system_clocks.hpp> TEST_F(AutowiringBenchmarkTest, VerifySimplePerformance) { const size_t n = 10000; // Insert the object: AutoRequired<SimpleObject>(); // Time n hash map hits, in order to get a baseline: std::unordered_map<int, int> ref; ref[0] = 212; ref[1] = 21; boost::chrono::nanoseconds baseline; { auto start = boost::chrono::high_resolution_clock::now(); for(size_t i = n; i--;) ref[i % 2]; baseline = boost::chrono::high_resolution_clock::now() - start; } // Time n autowirings: boost::chrono::nanoseconds benchmark; { auto start = boost::chrono::high_resolution_clock::now(); for(size_t i = n; i--;) Autowired<SimpleObject>(); benchmark = (boost::chrono::high_resolution_clock::now() - start) / n; } EXPECT_GT(baseline * 3. / 2., benchmark) << "Average time to autowire one member was more than 3/2 of a hash map lookup"; } template<int N> struct dummy: public ContextMember {}; void InjectDummy(void) { Autowired<dummy<1>>(); Autowired<dummy<2>>(); Autowired<dummy<3>>(); Autowired<dummy<4>>(); Autowired<dummy<5>>(); Autowired<dummy<6>>(); Autowired<dummy<7>>(); Autowired<dummy<8>>(); Autowired<dummy<9>>(); Autowired<dummy<10>>(); Autowired<dummy<11>>(); Autowired<dummy<12>>(); Autowired<dummy<13>>(); Autowired<dummy<14>>(); Autowired<dummy<15>>(); Autowired<dummy<16>>(); Autowired<dummy<17>>(); Autowired<dummy<18>>(); Autowired<dummy<19>>(); Autowired<dummy<20>>(); Autowired<dummy<21>>(); Autowired<dummy<22>>(); Autowired<dummy<23>>(); Autowired<dummy<24>>(); Autowired<dummy<25>>(); }; TEST_F(AutowiringBenchmarkTest, DISABLED_VerifyAutowiringCache) { boost::chrono::nanoseconds baseline(0); boost::chrono::nanoseconds benchmark(0); for(int i = 0; i<100; ++i) { AutoCreateContext ctxt; CurrentContextPusher pshr(ctxt); auto startBase = boost::chrono::high_resolution_clock::now(); InjectDummy(); baseline += boost::chrono::high_resolution_clock::now() - startBase; auto startBench = boost::chrono::high_resolution_clock::now(); InjectDummy(); benchmark += boost::chrono::high_resolution_clock::now() - startBench; } EXPECT_GT(baseline, benchmark) << "Autowiring cache not improving performance on subsequent autowirings"; } TEST_F(AutowiringBenchmarkTest, VerifyAutowiredFast) { { AutoCreateContext ctxt; CurrentContextPusher pshr(ctxt); AutoRequired<dummy<1>> foo; AutowiredFast<dummy<1>> bar; ASSERT_TRUE(foo) << "AutoRequred member not created"; EXPECT_TRUE(bar) << "AutowiredFast not satisfied"; } { AutoCreateContext ctxt; CurrentContextPusher pshr(ctxt); AutowiredFast<dummy<1>> fast; Autowired<dummy<1>> wired; AutoRequired<dummy<1>> required; ASSERT_TRUE(required) << "AutoRequired member not created"; EXPECT_TRUE(wired.IsAutowired()) << "Deferred Autowiring wasn't satisfied"; EXPECT_FALSE(fast) << "AutowiredFast member was deferred"; } } TEST_F(AutowiringBenchmarkTest, VerifyAutowiredFastPerformance) { boost::chrono::nanoseconds baseline; boost::chrono::nanoseconds benchmark; { // All of these tests will operate in the same context: AutoCreateContext ctxt; CurrentContextPusher pshr(ctxt); // Prime all memos: InjectDummy(); // Test simple autowiring first: auto startBase = boost::chrono::high_resolution_clock::now(); for(int i = 0; i < 500; ++i) InjectDummy(); baseline = boost::chrono::high_resolution_clock::now() - startBase; auto startBench = boost::chrono::high_resolution_clock::now(); for(int i = 0; i < 500; ++i) { AutowiredFast<dummy<1>>(); AutowiredFast<dummy<2>>(); AutowiredFast<dummy<3>>(); AutowiredFast<dummy<4>>(); AutowiredFast<dummy<5>>(); AutowiredFast<dummy<6>>(); AutowiredFast<dummy<7>>(); AutowiredFast<dummy<8>>(); AutowiredFast<dummy<9>>(); AutowiredFast<dummy<10>>(); AutowiredFast<dummy<11>>(); AutowiredFast<dummy<12>>(); AutowiredFast<dummy<13>>(); AutowiredFast<dummy<14>>(); AutowiredFast<dummy<15>>(); AutowiredFast<dummy<16>>(); AutowiredFast<dummy<17>>(); AutowiredFast<dummy<18>>(); AutowiredFast<dummy<19>>(); AutowiredFast<dummy<20>>(); } benchmark = boost::chrono::high_resolution_clock::now() - startBench; } EXPECT_GT(baseline, benchmark*1.75) << "Fast autowiring is slower than ordinary autowiring"; } <|endoftext|>
<commit_before>#include "precompiled.hpp" #include "ui/Uniforms.hpp" #include "util/Logging.hpp" #include <QtCore/QEvent> #include <QtGui/QMouseEvent> #include <QtGui/QResizeEvent> #include <QtGui/QWheelEvent> #include "util/Trackball.hpp" #include "util/TypeInfo.hpp" #include "util/Util.hpp" // TODO Should implement Qtilities::Core::Interfaces::IModificationNotifier namespace balls { constexpr float ZOOM_INTERVAL = 1.0f; using balls::util::types::info; using balls::util::resolveGLType; using balls::util::types::UniformInfo; using balls::util::types::UniformCollection; Uniforms::Uniforms(QObject* parent) noexcept : QObject(parent), _view(glm::translate(vec3(0, 0, -8))), _nearPlane(.01f), _farPlane(100), _canvasSize(1, 1), _lastCanvasSize(1, 1), _meta(metaObject()) { setFov(glm::radians(45.0f)); _elapsedTime.start(); } void Uniforms::receiveUniforms(const UniformCollection& uniforms) noexcept { // We must consider three cases: // 1: Uniforms that were removed (old - new) // 2: Uniforms that were added (new - old) // 3: Uniforms we still have (new & old) using balls::util::types::info; using balls::util::resolveGLType; using balls::util::types::UniformInfo; using balls::util::types::UniformCollection; using std::set_difference; using std::set_intersection; UniformCollection temp; auto cb = _uniformList.cbegin(); auto ce = _uniformList.cend(); // It's okay to cache these iterators, as we're not modifying _uniformList // First handle discarded uniforms (old - new) set_difference( cb, ce, uniforms.cbegin(), uniforms.cend(), std::inserter(temp, temp.begin()) ); _handleDiscardedUniforms(temp); temp.clear(); // Now handle new uniforms; we have to add these (new - old) set_difference( uniforms.cbegin(), uniforms.cend(), cb, ce, std::inserter(temp, temp.begin()) ); _handleNewUniforms(temp); temp.clear(); // Finally, handle uniforms that still exist, but may have changed type (new & old) set_intersection( uniforms.cbegin(), uniforms.cend(), cb, ce, std::inserter(temp, temp.begin()) ); _handleKeptUniforms(temp); this->_uniformList = uniforms; } void Uniforms::_handleDiscardedUniforms(const UniformCollection& temp) noexcept { qCDebug(logs::uniform::Name) << temp.size() << "discarded uniforms"; for (const UniformInfo& i : temp) { // For each uniform we're throwing away... QByteArray name = i.name.toLocal8Bit(); const char* name_cstr = name.data(); if (_meta->indexOfProperty(name_cstr) == -1) { // If this is a custom uniform... Q_ASSERT(property(name_cstr).isValid()); this->setProperty(name_cstr, QVariant()); // Then clear it Q_ASSERT(!property(name_cstr).isValid()); qCDebug(logs::uniform::Name) << "Removed" << i.name; } } } void Uniforms::_handleNewUniforms(const UniformCollection& temp) noexcept { qCDebug(logs::uniform::Name) << temp.size() << "new uniforms"; for (const UniformInfo& i : temp) { // For each uniform we're adding... QByteArray name = i.name.toLocal8Bit(); const char* name_cstr = name.data(); auto qtype = info[i.type].qMetaType; if (_meta->indexOfProperty(name_cstr) == -1) { // If this is a custom uniform... qCDebug(logs::uniform::Name) << "Discovered custom" << QMetaType::typeName(qtype) << i.name; Q_ASSERT(!property(name_cstr).isValid()); this->setProperty(name_cstr, QVariant(qtype, nullptr)); Q_ASSERT(property(name_cstr).isValid()); // Add a default-constructed uniform } else { qCDebug(logs::uniform::Name) << "Now using built-in" << QMetaType::typeName(qtype) << i.name; } } } void Uniforms::_handleKeptUniforms(const UniformCollection& temp) noexcept { qCDebug(logs::uniform::Name) << temp.size() << "uniforms carried over"; for (const UniformInfo& i : temp) { // For each uniform we still have... QByteArray name = i.name.toLocal8Bit(); const char* name_cstr = name.data(); const util::types::TypeInfo& inf = info[i.type]; QVariant prop = this->property(name_cstr); if (_meta->indexOfProperty(name_cstr) == -1) { // If this is a custom uniform... if (prop.userType() == inf.qMetaType) { // If this uniform still has the same type as before... qCDebug(logs::uniform::Name) << "Left" << prop.typeName() << i.name << "unchanged"; } else { // This uniform is defined with a different type this time... if (prop.canConvert(inf.qMetaType)) { // If a conversion exists to this new type... prop.convert(inf.qMetaType); } else { prop = QVariant(inf.qMetaType, nullptr); // Otherwise, just default-construct a value } this->setProperty(name_cstr, prop); qCDebug(logs::uniform::Name) << "Have" << prop.typeName() << i.name << "but it's now a" << QMetaType::typeName(info[i.type].qMetaType) << i.name; } } } } void Uniforms::resetModelView() noexcept { _model = mat4(); _view = mat4(); } void Uniforms::setFov(const float fov) noexcept { _fov = fov; _updateProjection(); } void Uniforms::_updateProjection() noexcept { _projection = glm::perspectiveFov( _fov, static_cast<float>(_canvasSize.x), static_cast<float>(_canvasSize.y + 1), _nearPlane, _farPlane ); } bool Uniforms::event(QEvent* e) { return false; } bool Uniforms::eventFilter(QObject* obj, QEvent* event) { switch (event->type()) { case QEvent::MouseMove: mouseMoveEvent(static_cast<QMouseEvent*>(event)); return false; case QEvent::MouseButtonPress: mousePressEvent(static_cast<QMouseEvent*>(event)); return false; case QEvent::Wheel: wheelEvent(static_cast<QWheelEvent*>(event)); return false; case QEvent::Resize: resizeEvent(static_cast<QResizeEvent*>(event)); return false; default: return false; } } void Uniforms::mouseMoveEvent(QMouseEvent* e) noexcept { this->_mousePos.x = e->x(); this->_mousePos.y = e->y(); vec2 localPos = { e->localPos().x(), e->localPos().y() }; if (e->buttons() & Qt::LeftButton) { // If the left mouse button is being held down... vec2 delta = localPos - vec2(_lastMousePos); _model = glm::rotate(_model, glm::radians(delta.x), vec3(0, 1, 0)); _model = glm::rotate(_model, glm::radians(delta.y), vec3(1, 0, 0)); } this->_lastMousePos = localPos; } void Uniforms::mousePressEvent(QMouseEvent* e) noexcept { if (e->buttons() & Qt::LeftButton) { // If the left mouse button was just clicked... _trackball.click( e->x(), _canvasSize.y - e->y() ); } } void Uniforms::wheelEvent(QWheelEvent* e) noexcept { int delta = e->angleDelta().y(); //this->setFov(_fov + ((delta > 0) ? ZOOM_INTERVAL : -ZOOM_INTERVAL)); _view = glm::translate(_view, {0.0f, 0.0f, (delta > 0 ? ZOOM_INTERVAL : -ZOOM_INTERVAL)}); } void Uniforms::resizeEvent(QResizeEvent* e) noexcept { const QSize& size = e->size(); int w = size.width(); int h = size.height(); _canvasSize.x = w; _canvasSize.y = h; const QSize& lastSize = e->oldSize(); _lastCanvasSize.x = lastSize.width(); _lastCanvasSize.y = lastSize.height(); _updateProjection(); _trackball.setBounds(w, h); } } <commit_msg>Clean up logging and formatting in Uniforms.cpp<commit_after>#include "precompiled.hpp" #include "ui/Uniforms.hpp" #include "util/Logging.hpp" #include <QtCore/QEvent> #include <QtGui/QMouseEvent> #include <QtGui/QResizeEvent> #include <QtGui/QWheelEvent> #include "util/Trackball.hpp" #include "util/TypeInfo.hpp" #include "util/Util.hpp" // TODO Should implement Qtilities::Core::Interfaces::IModificationNotifier namespace balls { constexpr float ZOOM_INTERVAL = 1.0f; using balls::util::types::info; using balls::util::resolveGLType; using balls::util::types::UniformInfo; using balls::util::types::UniformCollection; Uniforms::Uniforms(QObject* parent) noexcept : QObject(parent), _view(glm::translate(vec3(0, 0, -8))), _nearPlane(.01f), _farPlane(100), _canvasSize(1, 1), _lastCanvasSize(1, 1), _meta(metaObject()) { setFov(glm::radians(45.0f)); _elapsedTime.start(); } void Uniforms::receiveUniforms(const UniformCollection& uniforms) noexcept { // We must consider three cases: // 1: Uniforms that were removed (old - new) // 2: Uniforms that were added (new - old) // 3: Uniforms we still have (new & old) using balls::util::types::info; using balls::util::resolveGLType; using balls::util::types::UniformInfo; using balls::util::types::UniformCollection; using std::set_difference; using std::set_intersection; UniformCollection temp; auto cb = _uniformList.cbegin(); auto ce = _uniformList.cend(); // It's okay to cache these iterators, as we're not modifying _uniformList // First handle discarded uniforms (old - new) set_difference( cb, ce, uniforms.cbegin(), uniforms.cend(), std::inserter(temp, temp.begin()) ); _handleDiscardedUniforms(temp); temp.clear(); // Now handle new uniforms; we have to add these (new - old) set_difference( uniforms.cbegin(), uniforms.cend(), cb, ce, std::inserter(temp, temp.begin()) ); _handleNewUniforms(temp); temp.clear(); // Finally, handle uniforms that still exist, but may have changed type (new & old) set_intersection( uniforms.cbegin(), uniforms.cend(), cb, ce, std::inserter(temp, temp.begin()) ); _handleKeptUniforms(temp); this->_uniformList = uniforms; } void Uniforms::_handleDiscardedUniforms(const UniformCollection& temp) noexcept { #ifdef DEBUG QStringList removed; #endif for (const UniformInfo& i : temp) { // For each uniform we're throwing away... QByteArray name = i.name.toLocal8Bit(); const char* name_cstr = name.data(); if (_meta->indexOfProperty(name_cstr) == -1) { // If this is a custom uniform... Q_ASSERT(property(name_cstr).isValid()); this->setProperty(name_cstr, QVariant()); // Then clear it Q_ASSERT(!property(name_cstr).isValid()); #ifdef DEBUG removed << i.name; #endif } } #ifdef DEBUG qCDebug(logs::uniform::Removed).noquote() << (removed.empty() ? "None" : removed.join(", ")); #endif } void Uniforms::_handleNewUniforms(const UniformCollection& temp) noexcept { #ifdef DEBUG QStringList added; #endif for (const UniformInfo& i : temp) { // For each uniform we're adding... QByteArray name = i.name.toLocal8Bit(); const char* name_cstr = name.data(); auto qtype = info[i.type].qMetaType; if (_meta->indexOfProperty(name_cstr) == -1) { // If this is a custom uniform... #ifdef DEBUG added << QString("%1(%2)").arg(i.name, QMetaType::typeName(qtype)); #endif //Q_ASSERT(!property(name_cstr).isValid()); this->setProperty(name_cstr, QVariant(qtype, nullptr)); Q_ASSERT(property(name_cstr).isValid()); // Add a default-constructed uniform } else { #if DEBUG added << QString("%1(built-in %2)").arg(i.name, QMetaType::typeName(qtype)); #endif } } #ifdef DEBUG qCDebug(logs::uniform::New).noquote() << (added.empty() ? "None" : added.join(", ")); #endif } void Uniforms::_handleKeptUniforms(const UniformCollection& temp) noexcept { qCDebug(logs::uniform::Name) << temp.size() << "uniforms carried over"; for (const UniformInfo& i : temp) { // For each uniform we still have... QByteArray name = i.name.toLocal8Bit(); const char* name_cstr = name.data(); const util::types::TypeInfo& inf = info[i.type]; QVariant prop = this->property(name_cstr); if (_meta->indexOfProperty(name_cstr) == -1) { // If this is a custom uniform... if (prop.userType() == inf.qMetaType) { // If this uniform still has the same type as before... qCDebug(logs::uniform::Name) << "Left" << prop.typeName() << i.name << "unchanged"; } else { // This uniform is defined with a different type this time... if (prop.canConvert(inf.qMetaType)) { // If a conversion exists to this new type... prop.convert(inf.qMetaType); } else { prop = QVariant(inf.qMetaType, nullptr); // Otherwise, just default-construct a value } this->setProperty(name_cstr, prop); qCDebug(logs::uniform::Name) << "Have" << prop.typeName() << i.name << "but it's now a" << QMetaType::typeName(info[i.type].qMetaType) << i.name; } } } } void Uniforms::resetModelView() noexcept { _model = mat4(); _view = mat4(); } void Uniforms::setFov(const float fov) noexcept { _fov = fov; _updateProjection(); } void Uniforms::_updateProjection() noexcept { _projection = glm::perspectiveFov( _fov, static_cast<float>(_canvasSize.x), static_cast<float>(_canvasSize.y + 1), _nearPlane, _farPlane ); } bool Uniforms::event(QEvent* e) { return false; } bool Uniforms::eventFilter(QObject* obj, QEvent* event) { switch (event->type()) { case QEvent::MouseMove: mouseMoveEvent(static_cast<QMouseEvent*>(event)); return false; case QEvent::MouseButtonPress: mousePressEvent(static_cast<QMouseEvent*>(event)); return false; case QEvent::Wheel: wheelEvent(static_cast<QWheelEvent*>(event)); return false; case QEvent::Resize: resizeEvent(static_cast<QResizeEvent*>(event)); return false; default: return false; } } void Uniforms::mouseMoveEvent(QMouseEvent* e) noexcept { this->_mousePos.x = e->x(); this->_mousePos.y = e->y(); vec2 localPos = { e->localPos().x(), e->localPos().y() }; if (e->buttons() & Qt::LeftButton) { // If the left mouse button is being held down... vec2 delta = localPos - vec2(_lastMousePos); _model = glm::rotate(_model, glm::radians(delta.x), vec3(0, 1, 0)); _model = glm::rotate(_model, glm::radians(delta.y), vec3(1, 0, 0)); } this->_lastMousePos = localPos; } void Uniforms::mousePressEvent(QMouseEvent* e) noexcept { if (e->buttons() & Qt::LeftButton) { // If the left mouse button was just clicked... _trackball.click( e->x(), _canvasSize.y - e->y() ); } } void Uniforms::wheelEvent(QWheelEvent* e) noexcept { int delta = e->angleDelta().y(); //this->setFov(_fov + ((delta > 0) ? ZOOM_INTERVAL : -ZOOM_INTERVAL)); _view = glm::translate(_view, {0.0f, 0.0f, (delta > 0 ? ZOOM_INTERVAL : -ZOOM_INTERVAL)}); } void Uniforms::resizeEvent(QResizeEvent* e) noexcept { const QSize& size = e->size(); int w = size.width(); int h = size.height(); _canvasSize.x = w; _canvasSize.y = h; const QSize& lastSize = e->oldSize(); _lastCanvasSize.x = lastSize.width(); _lastCanvasSize.y = lastSize.height(); _updateProjection(); _trackball.setBounds(w, h); } } <|endoftext|>
<commit_before>#include "feStats.h" const feStats feStats::ZERO = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; bool feStats::operator==(const feStats &rhs) const { return (hp == rhs.hp && str == rhs.str && mag == rhs.mag && skl == rhs.skl && spd == rhs.spd && lck == rhs.lck && def == rhs.def && res == rhs.res && con == rhs.con && mov == rhs.mov); } feStats feStats::operator%(const feStats &rhs) const { feStats ret = { hp % rhs.hp, str % rhs.str, mag % rhs.mag, skl % rhs.skl, spd % rhs.spd, lck % rhs.lck, def % rhs.def, res % rhs.res, con % rhs.con, mov % rhs.mov }; return ret; } feStats feStats::operator+(const feStats &rhs) const { feStats sum = { hp += rhs.hp, str += rhs.str, mag += rhs.mag, skl += rhs.skl, lck += rhs.lck, def += rhs.def, res += rhs.res, con += rhs.con, mov += rhs.mov}; return sum; } feStats feStats::operator-(const feStats &rhs) const { feStats diff = { hp -= rhs.hp, str -= rhs.str, mag -= rhs.mag, skl -= rhs.skl, lck -= rhs.lck, def -= rhs.def, res -= rhs.res, con -= rhs.con, mov -= rhs.mov}; return diff; } feStats feStats::operator*(const feStats &rhs) const { feStats prod = { hp *= rhs.hp, str *= rhs.str, mag *= rhs.mag, skl *= rhs.skl, lck *= rhs.lck, def *= rhs.def, res *= rhs.res, con *= rhs.con, mov *= rhs.mov}; return prod; } feStats feStats::operator/(const feStats &rhs) const { feStats quot = { hp /= rhs.hp, str /= rhs.str, mag /= rhs.mag, skl /= rhs.skl, lck /= rhs.lck, def /= rhs.def, res /= rhs.res, con /= rhs.con, mov /= rhs.mov}; return quot; } feStats &feStats::operator=(const feStats &rhs) { this->hp = rhs.hp; this->str = rhs.str; this->mag = rhs.mag; this->skl = rhs.skl; this->lck = rhs.lck; this->def = rhs.def; this->res = rhs.res; this->con = rhs.con; this->mov = rhs.mov; return *this; } feStats &feStats::operator+=(const feStats &rhs) { this->hp += rhs.hp; this->str += rhs.str; this->mag += rhs.mag; this->skl += rhs.skl; this->lck += rhs.lck; this->def += rhs.def; this->res += rhs.res; this->con += rhs.con; this->mov += rhs.mov; return *this; } feStats &feStats::operator-=(const feStats &rhs) { this->hp -= rhs.hp; this->str -= rhs.str; this->mag -= rhs.mag; this->skl -= rhs.skl; this->lck -= rhs.lck; this->def -= rhs.def; this->res -= rhs.res; this->con -= rhs.con; this->mov -= rhs.mov; return *this; } feStats &feStats::operator*=(const feStats &rhs) { this->hp *= rhs.hp; this->str *= rhs.str; this->mag *= rhs.mag; this->skl *= rhs.skl; this->lck *= rhs.lck; this->def *= rhs.def; this->res *= rhs.res; this->con *= rhs.con; this->mov *= rhs.mov; return *this; } feStats &feStats::operator/=(const feStats &rhs) { this->hp /= rhs.hp; this->str /= rhs.str; this->mag /= rhs.mag; this->skl /= rhs.skl; this->lck /= rhs.lck; this->def /= rhs.def; this->res /= rhs.res; this->con /= rhs.con; this->mov /= rhs.mov; return *this; } <commit_msg>change return values to ret name<commit_after>#include "feStats.h" const feStats feStats::ZERO = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; bool feStats::operator==(const feStats &rhs) const { return (hp == rhs.hp && str == rhs.str && mag == rhs.mag && skl == rhs.skl && spd == rhs.spd && lck == rhs.lck && def == rhs.def && res == rhs.res && con == rhs.con && mov == rhs.mov); } feStats feStats::operator%(const feStats &rhs) const { feStats ret = { hp % rhs.hp, str % rhs.str, mag % rhs.mag, skl % rhs.skl, spd % rhs.spd, lck % rhs.lck, def % rhs.def, res % rhs.res, con % rhs.con, mov % rhs.mov }; return ret; } feStats feStats::operator+(const feStats &rhs) const { feStats ret = { hp += rhs.hp, str += rhs.str, mag += rhs.mag, skl += rhs.skl, lck += rhs.lck, def += rhs.def, res += rhs.res, con += rhs.con, mov += rhs.mov}; return ret; } feStats feStats::operator-(const feStats &rhs) const { feStats ret = { hp -= rhs.hp, str -= rhs.str, mag -= rhs.mag, skl -= rhs.skl, lck -= rhs.lck, def -= rhs.def, res -= rhs.res, con -= rhs.con, mov -= rhs.mov}; return ret; } feStats feStats::operator*(const feStats &rhs) const { feStats ret = { hp *= rhs.hp, str *= rhs.str, mag *= rhs.mag, skl *= rhs.skl, lck *= rhs.lck, def *= rhs.def, res *= rhs.res, con *= rhs.con, mov *= rhs.mov}; return ret; } feStats feStats::operator/(const feStats &rhs) const { feStats ret = { hp /= rhs.hp, str /= rhs.str, mag /= rhs.mag, skl /= rhs.skl, lck /= rhs.lck, def /= rhs.def, res /= rhs.res, con /= rhs.con, mov /= rhs.mov}; return ret; } feStats &feStats::operator=(const feStats &rhs) { this->hp = rhs.hp; this->str = rhs.str; this->mag = rhs.mag; this->skl = rhs.skl; this->lck = rhs.lck; this->def = rhs.def; this->res = rhs.res; this->con = rhs.con; this->mov = rhs.mov; return *this; } feStats &feStats::operator+=(const feStats &rhs) { this->hp += rhs.hp; this->str += rhs.str; this->mag += rhs.mag; this->skl += rhs.skl; this->lck += rhs.lck; this->def += rhs.def; this->res += rhs.res; this->con += rhs.con; this->mov += rhs.mov; return *this; } feStats &feStats::operator-=(const feStats &rhs) { this->hp -= rhs.hp; this->str -= rhs.str; this->mag -= rhs.mag; this->skl -= rhs.skl; this->lck -= rhs.lck; this->def -= rhs.def; this->res -= rhs.res; this->con -= rhs.con; this->mov -= rhs.mov; return *this; } feStats &feStats::operator*=(const feStats &rhs) { this->hp *= rhs.hp; this->str *= rhs.str; this->mag *= rhs.mag; this->skl *= rhs.skl; this->lck *= rhs.lck; this->def *= rhs.def; this->res *= rhs.res; this->con *= rhs.con; this->mov *= rhs.mov; return *this; } feStats &feStats::operator/=(const feStats &rhs) { this->hp /= rhs.hp; this->str /= rhs.str; this->mag /= rhs.mag; this->skl /= rhs.skl; this->lck /= rhs.lck; this->def /= rhs.def; this->res /= rhs.res; this->con /= rhs.con; this->mov /= rhs.mov; return *this; } <|endoftext|>
<commit_before>// Copyright (c) 2013, German Neuroinformatics Node (G-Node) // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted under the terms of the BSD License. See // LICENSE file in the root of the Project. /** * @namespace nix::util * @brief Namespace for utility functions. This namespace is not part of the public API. */ #ifndef NIX_UTIL_H #define NIX_UTIL_H #include <string> #include <sstream> #include <iostream> #include <vector> #include <cmath> #include <type_traits> #include <boost/optional.hpp> #include <boost/none_t.hpp> #include <nix/Platform.hpp> #include <nix/Exception.hpp> namespace nix { namespace util { /** * @brief Remove blank spaces from the entire string * * @param str The string to trim (will be modified in-place) */ NIXAPI void deblankString(std::string &str); /** * @brief Remove blank spaces from the entire string * * @param str The string to trim * * @return The trimmed string */ NIXAPI std::string deblankString(const std::string &str); /** * @brief Generates an ID-String. * * @param prefix The prefix to append to the generated id. * @param length The length of the ID. * * @return The generated id string. */ NIXAPI std::string createId(std::string prefix = "", int length = 16); /** * @brief Convert a time value into a string representation. * * @param time The time to convert. * * @return The sting representation of time. */ NIXAPI std::string timeToStr(time_t time); /** * @brief Convert a string representation of a date into a time value. * * @param time The string representation of a date. * * @return The time value that is represented by the time parameter. */ NIXAPI time_t strToTime(const std::string &time); /** * @brief Convert a time value into a string representation. * * @return The default time. */ NIXAPI time_t getTime(); /** * @brief Sanitizer function that deblanks units and replaces mu and µ * with the "u" replacement. * * @param unit The old unit. * * @return The sanitized unit. */ NIXAPI std::string unitSanitizer(const std::string &unit); /** * @brief Converts minutes and hours to seconds. * * @param unit The original unit (i.e. h for hour, or min for minutes) * @param value The original value * * @return The value in converted to seconds */ template <typename T> NIXAPI T convertToSeconds(const std::string &unit, T value) { T seconds; if (unit == "min") { seconds = value * 60; } else if (unit == "h") { std::string new_unit = "min"; seconds = convertToSeconds(new_unit, value * 60); } else if (unit == "s") { seconds = value; } else { std::cerr << "[nix::util::convertToSeconds] Warning: given unit is not supported!" << std::endl; seconds = value; } return seconds; } /** * @brief Converts temperatures given in degrees Celsius of Fahren to Kelvin. * * @param unit The original unit {"F", "°F", "C", "°C"} * @param value The original value * * @return The temperature in Kelvin */ template<typename T> NIXAPI T convertToKelvin(const std::string &unit, T value) { T temperature; if (unit == "°C" || unit == "C") { temperature = value + 273.15; } else if (unit == "°F" || unit == "F") { double temp = (value - 32) * 5.0/9 + 273.15; temperature = std::is_integral<T>::value ? std::round(temp) : temp; } else if (unit == "°K" || unit == "K") { temperature = value; } else { std::cerr << "[nix::util::convertToKelvin] Warning: given unit is not supported" << std::endl; temperature = value; } return temperature; } /** * @brief Checks if the passed string represents a valid SI unit. * * @param unit A string that is supposed to represent an SI unit. * * @return True if a valid SI unit, false otherwise. */ NIXAPI bool isSIUnit(const std::string &unit); /** * @brief Checks if the passed string is a valid combination of SI units. * * For example mV^2*Hz^-1. Method accepts only the * notation. * * @param unit A string that should be tested * * @return True if a valid compound si unti, false otherwise. */ NIXAPI bool isCompoundSIUnit(const std::string &unit); /** * @brief Get the scaling between two SI units that are identified by the two strings. * * @param originUnit The original unit * @param destinationUnit The one into which a scaling should be done * * @return A double with the appropriate scaling * * @throw std::runtime_error Exception when units cannot be converted into each other by mere scaling */ NIXAPI double getSIScaling(const std::string &originUnit, const std::string &destinationUnit); /** * Splits an SI unit into prefix, unit and the power components. * * @param fullUnit * @param prefix * @param unit * @param power */ NIXAPI void splitUnit(const std::string &fullUnit, std::string &prefix, std::string &unit, std::string &power); /** * Splits a SI unit compound into its atomic parts. * * @param compoundUnit An SI unit that consists of many atomic units * @param atomicUnits A vector that takes the atomic units */ NIXAPI void splitCompoundUnit(const std::string &compoundUnit, std::vector<std::string> &atomicUnits); /** * @brief Convert a number into a string representation. * * @param number The number to convert * * @return The string representation of number */ template<typename T> std::string numToStr(T number) { std::stringstream s; s << number; return s.str(); } /** * Convert a string representing a number into a number. * * @param str The string to convert. * * @return The number that was represented by the string. */ template<typename T> T strToNum(const std::string &str) { std::stringstream s(str); T number; return s >> number ? number : 0; } /* * Check whether a given type is of type "boost::optional" */ template<typename> struct is_optional : std::false_type {}; template<typename T> struct is_optional<boost::optional<T>> : std::true_type {}; /* * Optional de-referencing: * De-reference boost optional type if such given, returned var * unchanged otherwise. */ template<typename T> T deRef(T var) { return var; } template<typename R> R deRef(boost::optional<R> var) { if(var) return *var; else return R(); } } // namespace util } // namespace nix #endif // NIX_UTIL_H <commit_msg>add 'sec' as valid unit to util::convertToSeconds<commit_after>// Copyright (c) 2013, German Neuroinformatics Node (G-Node) // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted under the terms of the BSD License. See // LICENSE file in the root of the Project. /** * @namespace nix::util * @brief Namespace for utility functions. This namespace is not part of the public API. */ #ifndef NIX_UTIL_H #define NIX_UTIL_H #include <string> #include <sstream> #include <iostream> #include <vector> #include <cmath> #include <type_traits> #include <boost/optional.hpp> #include <boost/none_t.hpp> #include <nix/Platform.hpp> #include <nix/Exception.hpp> namespace nix { namespace util { /** * @brief Remove blank spaces from the entire string * * @param str The string to trim (will be modified in-place) */ NIXAPI void deblankString(std::string &str); /** * @brief Remove blank spaces from the entire string * * @param str The string to trim * * @return The trimmed string */ NIXAPI std::string deblankString(const std::string &str); /** * @brief Generates an ID-String. * * @param prefix The prefix to append to the generated id. * @param length The length of the ID. * * @return The generated id string. */ NIXAPI std::string createId(std::string prefix = "", int length = 16); /** * @brief Convert a time value into a string representation. * * @param time The time to convert. * * @return The sting representation of time. */ NIXAPI std::string timeToStr(time_t time); /** * @brief Convert a string representation of a date into a time value. * * @param time The string representation of a date. * * @return The time value that is represented by the time parameter. */ NIXAPI time_t strToTime(const std::string &time); /** * @brief Convert a time value into a string representation. * * @return The default time. */ NIXAPI time_t getTime(); /** * @brief Sanitizer function that deblanks units and replaces mu and µ * with the "u" replacement. * * @param unit The old unit. * * @return The sanitized unit. */ NIXAPI std::string unitSanitizer(const std::string &unit); /** * @brief Converts minutes and hours to seconds. * * @param unit The original unit (i.e. h for hour, or min for minutes) * @param value The original value * * @return The value in converted to seconds */ template <typename T> NIXAPI T convertToSeconds(const std::string &unit, T value) { T seconds; if (unit == "min") { seconds = value * 60; } else if (unit == "h") { std::string new_unit = "min"; seconds = convertToSeconds(new_unit, value * 60); } else if (unit == "s" || unit == "sec") { seconds = value; } else { std::cerr << "[nix::util::convertToSeconds] Warning: given unit is not supported!" << std::endl; seconds = value; } return seconds; } /** * @brief Converts temperatures given in degrees Celsius of Fahren to Kelvin. * * @param unit The original unit {"F", "°F", "C", "°C"} * @param value The original value * * @return The temperature in Kelvin */ template<typename T> NIXAPI T convertToKelvin(const std::string &unit, T value) { T temperature; if (unit == "°C" || unit == "C") { temperature = value + 273.15; } else if (unit == "°F" || unit == "F") { double temp = (value - 32) * 5.0/9 + 273.15; temperature = std::is_integral<T>::value ? std::round(temp) : temp; } else if (unit == "°K" || unit == "K") { temperature = value; } else { std::cerr << "[nix::util::convertToKelvin] Warning: given unit is not supported" << std::endl; temperature = value; } return temperature; } /** * @brief Checks if the passed string represents a valid SI unit. * * @param unit A string that is supposed to represent an SI unit. * * @return True if a valid SI unit, false otherwise. */ NIXAPI bool isSIUnit(const std::string &unit); /** * @brief Checks if the passed string is a valid combination of SI units. * * For example mV^2*Hz^-1. Method accepts only the * notation. * * @param unit A string that should be tested * * @return True if a valid compound si unti, false otherwise. */ NIXAPI bool isCompoundSIUnit(const std::string &unit); /** * @brief Get the scaling between two SI units that are identified by the two strings. * * @param originUnit The original unit * @param destinationUnit The one into which a scaling should be done * * @return A double with the appropriate scaling * * @throw std::runtime_error Exception when units cannot be converted into each other by mere scaling */ NIXAPI double getSIScaling(const std::string &originUnit, const std::string &destinationUnit); /** * Splits an SI unit into prefix, unit and the power components. * * @param fullUnit * @param prefix * @param unit * @param power */ NIXAPI void splitUnit(const std::string &fullUnit, std::string &prefix, std::string &unit, std::string &power); /** * Splits a SI unit compound into its atomic parts. * * @param compoundUnit An SI unit that consists of many atomic units * @param atomicUnits A vector that takes the atomic units */ NIXAPI void splitCompoundUnit(const std::string &compoundUnit, std::vector<std::string> &atomicUnits); /** * @brief Convert a number into a string representation. * * @param number The number to convert * * @return The string representation of number */ template<typename T> std::string numToStr(T number) { std::stringstream s; s << number; return s.str(); } /** * Convert a string representing a number into a number. * * @param str The string to convert. * * @return The number that was represented by the string. */ template<typename T> T strToNum(const std::string &str) { std::stringstream s(str); T number; return s >> number ? number : 0; } /* * Check whether a given type is of type "boost::optional" */ template<typename> struct is_optional : std::false_type {}; template<typename T> struct is_optional<boost::optional<T>> : std::true_type {}; /* * Optional de-referencing: * De-reference boost optional type if such given, returned var * unchanged otherwise. */ template<typename T> T deRef(T var) { return var; } template<typename R> R deRef(boost::optional<R> var) { if(var) return *var; else return R(); } } // namespace util } // namespace nix #endif // NIX_UTIL_H <|endoftext|>
<commit_before>/* * PFASST controller. */ #ifndef _PFASST_PFASST_HPP_ #define _PFASST_PFASST_HPP_ #include "mlsdc.hpp" using namespace std; namespace pfasst { template<typename time = pfasst::time_precision> class PFASST : public MLSDC<time> { ICommunicator* comm; typedef typename pfasst::Controller<time>::LevelIter LevelIter; bool predict; //<! whether to use a 'predict' sweep bool initial; //<! whether we're sweeping from a new initial condition void perform_sweeps(size_t level) { auto sweeper = this->get_level(level); for (size_t s = 0; s < this->nsweeps[level]; s++) { if (predict) { sweeper->predict(initial & predict); predict = false; } else { sweeper->sweep(); } } } public: void set_comm(ICommunicator* comm) { this->comm = comm; } /** * Predictor: restrict initial down, preform coarse sweeps, return to finest. */ void predictor() { this->get_finest()->spread(); // restrict fine initial condition for (auto l = this->finest() - 1; l >= this->coarsest(); --l) { auto crse = l.current(); auto fine = l.fine(); auto trns = l.transfer(); trns->restrict_initial(crse, fine); crse->spread(); crse->save(); } // perform sweeps on the coarse level based on rank predict = true; auto crse = this->coarsest().current(); for (int nstep = 0; nstep < comm->rank() + 1; nstep++) { // XXX: set iteration and step? perform_sweeps(0); if (nstep < comm->rank()) { crse->advance(); } } // return to finest level, sweeping as we go for (auto l = this->coarsest() + 1; l <= this->finest(); ++l) { auto crse = l.coarse(); auto fine = l.current(); auto trns = l.transfer(); trns->interpolate(fine, crse, true); if (l < this->finest()) { perform_sweeps(l.level); } } } void broadcast() { this->get_finest()->broadcast(comm); initial = true; } int tag (int level) { return level * 10000 + this->get_iteration() + 10; } int tag(LevelIter l) { return tag(l.level); } void post() { for (auto l = this->coarsest() + 1; l <= this->finest(); ++l) { l.current()->post(comm, tag(l)); } } /** * Evolve ODE using PFASST. * * This assumes that the user has set initial conditions on the * finest level. * * Currently uses "block mode" PFASST with the standard predictor. */ void run() { int nblocks = int(this->get_end_time() / this->get_time_step()) / comm->size(); if (nblocks == 0) { throw ValueError("invalid duration: there are more time processors than time steps"); } initial = true; for (int nblock = 0; nblock < nblocks; nblock++) { this->set_step(nblock * comm->size() + comm->rank()); predictor(); for (this->set_iteration(0); this->get_iteration() < this->get_max_iterations(); this->advance_iteration()) { post(); cycle_v(this->finest()); } if (nblock < nblocks - 1) { broadcast(); } } } /** * Cycle down: sweep on current (fine), restrict to coarse. */ LevelIter cycle_down(LevelIter l) { auto fine = l.current(); auto crse = l.coarse(); auto trns = l.transfer(); perform_sweeps(l.level); if (l == this->finest()) { // note: convergence tests belong here } fine->send(comm, tag(l), false); auto dt = this->get_time_step(); trns->restrict(crse, fine, true); trns->fas(dt, crse, fine); crse->save(); return l - 1; } /** * Cycle up: interpolate coarse correction to fine, sweep on * current (fine). * * Note that if the fine level corresponds to the finest MLSDC * level, we don't perform a sweep. In this case the only * operation that is performed here is interpolation. */ LevelIter cycle_up(LevelIter l) { auto fine = l.current(); auto crse = l.coarse(); auto trns = l.transfer(); trns->interpolate(fine, crse, true); fine->recv(comm, tag(l), false); trns->interpolate_initial(fine, crse); if (l < this->finest()) { perform_sweeps(l.level); } return l + 1; } /** * Cycle bottom: sweep on the current (coarsest) level. */ LevelIter cycle_bottom(LevelIter l) { auto crse = l.current(); crse->recv(comm, tag(l), true); this->perform_sweeps(l.level); crse->send(comm, tag(l), true); return l + 1; } /** * Perform an MLSDC V-cycle. */ LevelIter cycle_v(LevelIter l) { // this v-cycle is a bit different than in mlsdc if (l.level == 0) { l = cycle_bottom(l); } else { l = cycle_down(l); l = cycle_v(l); l = cycle_up(l); } return l; } }; } // ::pfasst #endif <commit_msg>PFASST: Reduce to MLSDC when only one time-processor is used.<commit_after>/* * PFASST controller. */ #ifndef _PFASST_PFASST_HPP_ #define _PFASST_PFASST_HPP_ #include "mlsdc.hpp" using namespace std; namespace pfasst { template<typename time = pfasst::time_precision> class PFASST : public MLSDC<time> { ICommunicator* comm; typedef typename pfasst::Controller<time>::LevelIter LevelIter; bool predict; //<! whether to use a 'predict' sweep bool initial; //<! whether we're sweeping from a new initial condition void perform_sweeps(size_t level) { auto sweeper = this->get_level(level); for (size_t s = 0; s < this->nsweeps[level]; s++) { if (predict) { sweeper->predict(initial & predict); predict = false; } else { sweeper->sweep(); } } } public: void set_comm(ICommunicator* comm) { this->comm = comm; } /** * Predictor: restrict initial down, preform coarse sweeps, return to finest. */ void predictor() { this->get_finest()->spread(); // restrict fine initial condition for (auto l = this->finest() - 1; l >= this->coarsest(); --l) { auto crse = l.current(); auto fine = l.fine(); auto trns = l.transfer(); trns->restrict_initial(crse, fine); crse->spread(); crse->save(); } // perform sweeps on the coarse level based on rank predict = true; auto crse = this->coarsest().current(); for (int nstep = 0; nstep < comm->rank() + 1; nstep++) { // XXX: set iteration and step? perform_sweeps(0); if (nstep < comm->rank()) { crse->advance(); } } // return to finest level, sweeping as we go for (auto l = this->coarsest() + 1; l <= this->finest(); ++l) { auto crse = l.coarse(); auto fine = l.current(); auto trns = l.transfer(); trns->interpolate(fine, crse, true); if (l < this->finest()) { perform_sweeps(l.level); } } } void broadcast() { if (this->comm->size() == 1) { for (auto leviter = this->coarsest(); leviter <= this->finest(); ++leviter) { leviter.current()->advance(); } } else { this->get_finest()->broadcast(comm); initial = true; } } int tag (int level) { return level * 10000 + this->get_iteration() + 10; } int tag(LevelIter l) { return tag(l.level); } void post() { for (auto l = this->coarsest() + 1; l <= this->finest(); ++l) { l.current()->post(comm, tag(l)); } } /** * Evolve ODE using PFASST. * * This assumes that the user has set initial conditions on the * finest level. * * Currently uses "block mode" PFASST with the standard predictor. */ void run() { int nblocks = int(this->get_end_time() / this->get_time_step()) / comm->size(); if (nblocks == 0) { throw ValueError("invalid duration: there are more time processors than time steps"); } initial = true; for (int nblock = 0; nblock < nblocks; nblock++) { this->set_step(nblock * comm->size() + comm->rank()); if (this->comm->size() == 1) { predict = true; initial = this->get_step() == 0; } else { predictor(); } for (this->set_iteration(0); this->get_iteration() < this->get_max_iterations(); this->advance_iteration()) { post(); cycle_v(this->finest()); } if (nblock < nblocks - 1) { broadcast(); } } } /** * Cycle down: sweep on current (fine), restrict to coarse. */ LevelIter cycle_down(LevelIter l) { auto fine = l.current(); auto crse = l.coarse(); auto trns = l.transfer(); perform_sweeps(l.level); if (l == this->finest()) { // note: convergence tests belong here } fine->send(comm, tag(l), false); bool restrict_initial = this->comm->size() > 1 ? true : initial; trns->restrict(crse, fine, restrict_initial); trns->fas(this->get_time_step(), crse, fine); crse->save(); return l - 1; } /** * Cycle up: interpolate coarse correction to fine, sweep on * current (fine). * * Note that if the fine level corresponds to the finest MLSDC * level, we don't perform a sweep. In this case the only * operation that is performed here is interpolation. */ LevelIter cycle_up(LevelIter l) { auto fine = l.current(); auto crse = l.coarse(); auto trns = l.transfer(); bool interpolate_initial = this->comm->size() > 1; trns->interpolate(fine, crse, interpolate_initial); if (interpolate_initial) { fine->recv(comm, tag(l), false); trns->interpolate_initial(fine, crse); } if (l < this->finest()) { perform_sweeps(l.level); } return l + 1; } /** * Cycle bottom: sweep on the current (coarsest) level. */ LevelIter cycle_bottom(LevelIter l) { auto crse = l.current(); crse->recv(comm, tag(l), true); this->perform_sweeps(l.level); crse->send(comm, tag(l), true); return l + 1; } /** * Perform an MLSDC V-cycle. */ LevelIter cycle_v(LevelIter l) { if (l.level == 0) { l = cycle_bottom(l); } else { l = cycle_down(l); l = cycle_v(l); l = cycle_up(l); } return l; } }; } // ::pfasst #endif <|endoftext|>
<commit_before>/* * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "testing/gtest/include/gtest/gtest.h" #include "webrtc/video_engine/test/common/flags.h" #include "webrtc/video_engine/test/common/run_tests.h" int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); webrtc::test::flags::Init(&argc, &argv); return webrtc::test::RunAllTests(); } <commit_msg>Call SetExecutablePath from test_main.cc<commit_after>/* * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "testing/gtest/include/gtest/gtest.h" #include "webrtc/test/testsupport/fileutils.h" #include "webrtc/video_engine/test/common/flags.h" #include "webrtc/video_engine/test/common/run_tests.h" int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); webrtc::test::flags::Init(&argc, &argv); webrtc::test::SetExecutablePath(argv[0]); return webrtc::test::RunAllTests(); } <|endoftext|>
<commit_before>#include <cstdio> #include <cstring> #include <iostream> #include <map> #include <improbable/standard_library.h> #include <improbable/view.h> #include <improbable/worker.h> #include <shoveler.h> extern "C" { #include <glib.h> #include <shoveler/spatialos/log.h> #include <shoveler/spatialos/worker/view/base/view.h> #include <shoveler/spatialos/worker/view/base/position.h> #include <shoveler/executor.h> } using shoveler::Bootstrap; using shoveler::Client; using shoveler::Heartbeat; using shoveler::Color; using shoveler::CreateClientEntityRequest; using shoveler::CreateClientEntityResponse; using shoveler::Drawable; using shoveler::DrawableType; using shoveler::Light; using shoveler::LightType; using shoveler::Material; using shoveler::MaterialType; using shoveler::Model; using shoveler::PolygonMode; using improbable::EntityAcl; using improbable::EntityAclData; using improbable::Metadata; using improbable::Persistence; using improbable::Position; using improbable::WorkerAttributeSet; using improbable::WorkerRequirementSet; using CreateClientEntity = shoveler::Bootstrap::Commands::CreateClientEntity; using ClientPing = shoveler::Bootstrap::Commands::ClientPing; struct ClientCleanupTickContext { worker::Connection *connection; int64_t maxHeartbeatTimeoutMs; std::map<worker::EntityId, std::pair<std::string, int64_t>> *lastHeartbeatMicrosMap; }; static void clientCleanupTick(void *clientCleanupTickContextPointer); int main(int argc, char **argv) { if (argc != 5) { return 1; } worker::ConnectionParameters parameters; parameters.WorkerType = "ShovelerServer"; parameters.Network.ConnectionType = worker::NetworkConnectionType::kTcp; parameters.Network.UseExternalIp = false; const std::string workerId = argv[1]; const std::string hostname = argv[2]; const std::uint16_t port = static_cast<std::uint16_t>(std::stoi(argv[3])); const std::string logFileLocation = argv[4]; const int tickRateHz = 10; const int clientCleanupTickRateHz = 2; const int64_t maxHeartbeatTimeoutMs = 5000; FILE *logFile = fopen(logFileLocation.c_str(), "r+"); if(logFile == NULL) { std::cerr << "Failed to open output log file at " << logFileLocation << ": " << strerror(errno) << std::endl; return 1; } shovelerSpatialosLogInit(SHOVELER_SPATIALOS_LOG_LEVEL_INFO_UP, logFile); shovelerSpatialosLogInfo("Connecting as worker %s to %s:%d.", workerId.c_str(), hostname.c_str(), port); auto components = worker::Components< shoveler::Bootstrap, shoveler::Client, shoveler::Heartbeat, shoveler::Light, shoveler::Model, improbable::EntityAcl, improbable::Metadata, improbable::Persistence, improbable::Position>{}; worker::Connection connection = worker::Connection::ConnectAsync(components, hostname, port, workerId, parameters).Get(); bool disconnected = false; worker::View view{components}; worker::Dispatcher& dispatcher = view; ShovelerExecutor *tickExecutor = shovelerExecutorCreateDirect(); std::map<worker::EntityId, std::pair<std::string, int64_t>> lastHeartbeatMicrosMap; dispatcher.OnDisconnect([&](const worker::DisconnectOp& op) { shovelerSpatialosLogError("Disconnected from SpatialOS: %s", op.Reason.c_str()); disconnected = true; }); dispatcher.OnMetrics([&](const worker::MetricsOp& op) { auto metrics = op.Metrics; connection.SendMetrics(metrics); }); dispatcher.OnLogMessage([&](const worker::LogMessageOp& op) { switch(op.Level) { case worker::LogLevel::kDebug: shovelerSpatialosLogTrace(op.Message.c_str()); break; case worker::LogLevel::kInfo: shovelerSpatialosLogInfo(op.Message.c_str()); break; case worker::LogLevel::kWarn: shovelerSpatialosLogWarning(op.Message.c_str()); break; case worker::LogLevel::kError: shovelerSpatialosLogError(op.Message.c_str()); break; case worker::LogLevel::kFatal: shovelerSpatialosLogError(op.Message.c_str()); std::terminate(); default: break; } }); dispatcher.OnAddEntity([&](const worker::AddEntityOp& op) { shovelerSpatialosLogInfo("Adding entity %lld.", op.EntityId); }); dispatcher.OnRemoveEntity([&](const worker::RemoveEntityOp& op) { shovelerSpatialosLogInfo("Removing entity %lld.", op.EntityId); }); dispatcher.OnAddComponent<Bootstrap>([&](const worker::AddComponentOp<Bootstrap>& op) { shovelerSpatialosLogInfo("Adding bootstrap to entity %lld.", op.EntityId); }); dispatcher.OnComponentUpdate<Bootstrap>([&](const worker::ComponentUpdateOp<Bootstrap>& op) { shovelerSpatialosLogInfo("Updating bootstrap for entity %lld.", op.EntityId); }); dispatcher.OnRemoveComponent<Bootstrap>([&](const worker::RemoveComponentOp& op) { shovelerSpatialosLogInfo("Removing bootstrap from entity %lld.", op.EntityId); }); dispatcher.OnAuthorityChange<Bootstrap>([&](const worker::AuthorityChangeOp& op) { shovelerSpatialosLogInfo("Authority change to %d for entity %lld.", op.Authority, op.EntityId); }); dispatcher.OnAddComponent<Heartbeat>([&](const worker::AddComponentOp<Heartbeat>& op) { lastHeartbeatMicrosMap[op.EntityId] = std::make_pair("(unknown)", view.Entities[op.EntityId].Get<Heartbeat>()->last_server_heartbeat()); shovelerSpatialosLogInfo("Added client heartbeat for entity %lld.", op.EntityId); }); dispatcher.OnComponentUpdate<Heartbeat>([&](const worker::ComponentUpdateOp<Heartbeat>& op) { if (lastHeartbeatMicrosMap.find(op.EntityId) != lastHeartbeatMicrosMap.end()) { std::string clientWorkerId = "(unknown)"; const auto &clientComponentOption = view.Entities[op.EntityId].Get<Client>(); if (clientComponentOption) { clientWorkerId = clientComponentOption->worker_id(); } lastHeartbeatMicrosMap[op.EntityId] = std::make_pair(clientWorkerId, view.Entities[op.EntityId].Get<Heartbeat>()->last_server_heartbeat()); } shovelerSpatialosLogTrace("Updated client heartbeat for entity %lld.", op.EntityId); }); dispatcher.OnRemoveComponent<Heartbeat>([&](const worker::RemoveComponentOp& op) { shovelerSpatialosLogInfo("Removed client heartbeat for entity %lld.", op.EntityId); }); dispatcher.OnAuthorityChange<Heartbeat>([&](const worker::AuthorityChangeOp& op) { shovelerSpatialosLogInfo("Changing heartbeat authority for entity %lld to %d.", op.EntityId, op.Authority); if (op.Authority == worker::Authority::kAuthoritative) { int64_t now = g_get_monotonic_time(); lastHeartbeatMicrosMap[op.EntityId] = std::make_pair("(unknown)", now); Heartbeat::Update heartbeatUpdate; heartbeatUpdate.set_last_server_heartbeat(now); connection.SendComponentUpdate<Heartbeat>(op.EntityId, heartbeatUpdate); } else if (op.Authority == worker::Authority::kNotAuthoritative) { lastHeartbeatMicrosMap.erase(op.EntityId); } }); dispatcher.OnCommandRequest<CreateClientEntity>([&](const worker::CommandRequestOp<CreateClientEntity>& op) { shovelerSpatialosLogInfo("Received create client entity request from: %s", op.CallerWorkerId.c_str()); Color whiteColor{1.0f, 1.0f, 1.0f}; Drawable pointDrawable{DrawableType::POINT}; Material whiteParticleMaterial{MaterialType::PARTICLE, whiteColor, {}}; worker::Entity clientEntity; clientEntity.Add<Metadata>({"client"}); clientEntity.Add<Client>({op.CallerWorkerId}); clientEntity.Add<Heartbeat>({0, 0}); clientEntity.Add<Persistence>({}); clientEntity.Add<Position>({{0, 0, 0}}); clientEntity.Add<Model>({pointDrawable, whiteParticleMaterial, {0.0f, 0.0f, 0.0f}, {0.1f, 0.1f, 0.0f}, true, true, false, false, PolygonMode::FILL}); clientEntity.Add<Light>({LightType::POINT, 1024, 1024, 1, 0.01f, 80.0f, {0.1f, 0.1f, 0.1f}, {}}); WorkerAttributeSet clientAttributeSet({"client"}); WorkerAttributeSet serverAttributeSet({"server"}); WorkerRequirementSet specificClientRequirementSet({op.CallerAttributeSet}); WorkerRequirementSet serverRequirementSet({serverAttributeSet}); WorkerRequirementSet clientAndServerRequirementSet({clientAttributeSet, serverAttributeSet}); worker::Map<std::uint32_t, WorkerRequirementSet> clientEntityComponentAclMap; clientEntityComponentAclMap.insert({{Client::ComponentId, specificClientRequirementSet}}); clientEntityComponentAclMap.insert({{Heartbeat::ComponentId, serverRequirementSet}}); clientEntityComponentAclMap.insert({{Position::ComponentId, specificClientRequirementSet}}); EntityAclData clientEntityAclData(clientAndServerRequirementSet, clientEntityComponentAclMap); clientEntity.Add<EntityAcl>(clientEntityAclData); connection.SendCreateEntityRequest(clientEntity, {}, {}); connection.SendCommandResponse<CreateClientEntity>(op.RequestId, {}); }); dispatcher.OnCommandRequest<ClientPing>([&](const worker::CommandRequestOp<ClientPing>& op) { worker::EntityId clientEntityId = op.Request.client_entity_id(); worker::Map<worker::EntityId, worker::Map<worker::ComponentId, worker::Authority>>::const_iterator entityAuthorityQuery = view.ComponentAuthority.find(clientEntityId); if(entityAuthorityQuery == view.ComponentAuthority.end()) { shovelerSpatialosLogWarning("Received client ping from %s for unknown client entity %lld, ignoring.", op.CallerWorkerId.c_str(), clientEntityId); return; } const worker::Map<worker::ComponentId, worker::Authority>& componentAuthorityMap = entityAuthorityQuery->second; worker::Map<worker::ComponentId, worker::Authority>::const_iterator componentAuthorityQuery = componentAuthorityMap.find(Heartbeat::ComponentId); if(componentAuthorityQuery == componentAuthorityMap.end()) { shovelerSpatialosLogWarning("Received client ping from %s for client entity %lld without client heartbeat component, ignoring.", op.CallerWorkerId.c_str(), clientEntityId); return; } const worker::Authority& HeartbeatAuthority = componentAuthorityQuery->second; if(HeartbeatAuthority != worker::Authority::kAuthoritative) { shovelerSpatialosLogWarning("Received client ping from %s for client entity %lld without authoritative client heartbeat component, ignoring.", op.CallerWorkerId.c_str(), clientEntityId); return; } int64_t now = g_get_monotonic_time(); Heartbeat::Update heartbeatUpdate; heartbeatUpdate.set_last_client_heartbeat(op.Request.client_heartbeat()); heartbeatUpdate.set_last_server_heartbeat(now); connection.SendComponentUpdate<Heartbeat>(clientEntityId, heartbeatUpdate); connection.SendCommandResponse<ClientPing>(op.RequestId, {now}); shovelerSpatialosLogTrace("Received client ping from %s for client entity %lld.", op.CallerWorkerId.c_str(), clientEntityId); }); ClientCleanupTickContext cleanupTickContext{&connection, maxHeartbeatTimeoutMs, &lastHeartbeatMicrosMap}; uint32_t clientCleanupTickPeriod = (uint32_t) (1000.0 / (double) clientCleanupTickRateHz); shovelerExecutorSchedulePeriodic(tickExecutor, 0, clientCleanupTickPeriod, clientCleanupTick, &cleanupTickContext); uint32_t executorTickPeriod = (uint32_t) (1000.0 / (double) tickRateHz); while(!disconnected) { dispatcher.Process(connection.GetOpList(executorTickPeriod)); shovelerExecutorUpdateNow(tickExecutor); } shovelerExecutorFree(tickExecutor); } static void clientCleanupTick(void *clientCleanupTickContextPointer) { ClientCleanupTickContext *context = (ClientCleanupTickContext *) clientCleanupTickContextPointer; int64_t now = g_get_monotonic_time(); for(const auto& item: *context->lastHeartbeatMicrosMap) { worker::EntityId entityId = item.first; const std::string &workerId = item.second.first; int64_t last = item.second.second; int64_t diff = now - last; if (diff > 1000 * context->maxHeartbeatTimeoutMs) { shovelerSpatialosLogWarning("Removing client entity %lld of worker %s because it exceeded the max ping timeout of %lldms.", entityId, workerId.c_str(), context->maxHeartbeatTimeoutMs); context->connection->SendDeleteEntityRequest(item.first, {}); } } }<commit_msg>changed server to use shoveler logging directly<commit_after>#include <cstdio> #include <cstring> #include <iostream> #include <map> #include <improbable/standard_library.h> #include <improbable/view.h> #include <improbable/worker.h> #include <shoveler.h> extern "C" { #include <glib.h> #include <shoveler/executor.h> #include <shoveler/log.h> } using shoveler::Bootstrap; using shoveler::Client; using shoveler::Heartbeat; using shoveler::Color; using shoveler::CreateClientEntityRequest; using shoveler::CreateClientEntityResponse; using shoveler::Drawable; using shoveler::DrawableType; using shoveler::Light; using shoveler::LightType; using shoveler::Material; using shoveler::MaterialType; using shoveler::Model; using shoveler::PolygonMode; using improbable::EntityAcl; using improbable::EntityAclData; using improbable::Metadata; using improbable::Persistence; using improbable::Position; using improbable::WorkerAttributeSet; using improbable::WorkerRequirementSet; using CreateClientEntity = shoveler::Bootstrap::Commands::CreateClientEntity; using ClientPing = shoveler::Bootstrap::Commands::ClientPing; struct ClientCleanupTickContext { worker::Connection *connection; int64_t maxHeartbeatTimeoutMs; std::map<worker::EntityId, std::pair<std::string, int64_t>> *lastHeartbeatMicrosMap; }; static void clientCleanupTick(void *clientCleanupTickContextPointer); int main(int argc, char **argv) { if (argc != 5) { return 1; } worker::ConnectionParameters parameters; parameters.WorkerType = "ShovelerServer"; parameters.Network.ConnectionType = worker::NetworkConnectionType::kTcp; parameters.Network.UseExternalIp = false; const std::string workerId = argv[1]; const std::string hostname = argv[2]; const std::uint16_t port = static_cast<std::uint16_t>(std::stoi(argv[3])); const std::string logFileLocation = argv[4]; const int tickRateHz = 10; const int clientCleanupTickRateHz = 2; const int64_t maxHeartbeatTimeoutMs = 5000; FILE *logFile = fopen(logFileLocation.c_str(), "r+"); if(logFile == NULL) { std::cerr << "Failed to open output log file at " << logFileLocation << ": " << strerror(errno) << std::endl; return 1; } shovelerLogInit("shoveler-spatialos/workers/cmake/", SHOVELER_LOG_LEVEL_INFO_UP, logFile); shovelerLogInfo("Connecting as worker %s to %s:%d.", workerId.c_str(), hostname.c_str(), port); auto components = worker::Components< shoveler::Bootstrap, shoveler::Client, shoveler::Heartbeat, shoveler::Light, shoveler::Model, improbable::EntityAcl, improbable::Metadata, improbable::Persistence, improbable::Position>{}; worker::Connection connection = worker::Connection::ConnectAsync(components, hostname, port, workerId, parameters).Get(); bool disconnected = false; worker::View view{components}; worker::Dispatcher& dispatcher = view; ShovelerExecutor *tickExecutor = shovelerExecutorCreateDirect(); std::map<worker::EntityId, std::pair<std::string, int64_t>> lastHeartbeatMicrosMap; dispatcher.OnDisconnect([&](const worker::DisconnectOp& op) { shovelerLogError("Disconnected from SpatialOS: %s", op.Reason.c_str()); disconnected = true; }); dispatcher.OnMetrics([&](const worker::MetricsOp& op) { auto metrics = op.Metrics; connection.SendMetrics(metrics); }); dispatcher.OnLogMessage([&](const worker::LogMessageOp& op) { switch(op.Level) { case worker::LogLevel::kDebug: shovelerLogTrace(op.Message.c_str()); break; case worker::LogLevel::kInfo: shovelerLogInfo(op.Message.c_str()); break; case worker::LogLevel::kWarn: shovelerLogWarning(op.Message.c_str()); break; case worker::LogLevel::kError: shovelerLogError(op.Message.c_str()); break; case worker::LogLevel::kFatal: shovelerLogError(op.Message.c_str()); std::terminate(); default: break; } }); dispatcher.OnAddEntity([&](const worker::AddEntityOp& op) { shovelerLogInfo("Adding entity %lld.", op.EntityId); }); dispatcher.OnRemoveEntity([&](const worker::RemoveEntityOp& op) { shovelerLogInfo("Removing entity %lld.", op.EntityId); }); dispatcher.OnAddComponent<Bootstrap>([&](const worker::AddComponentOp<Bootstrap>& op) { shovelerLogInfo("Adding bootstrap to entity %lld.", op.EntityId); }); dispatcher.OnComponentUpdate<Bootstrap>([&](const worker::ComponentUpdateOp<Bootstrap>& op) { shovelerLogInfo("Updating bootstrap for entity %lld.", op.EntityId); }); dispatcher.OnRemoveComponent<Bootstrap>([&](const worker::RemoveComponentOp& op) { shovelerLogInfo("Removing bootstrap from entity %lld.", op.EntityId); }); dispatcher.OnAuthorityChange<Bootstrap>([&](const worker::AuthorityChangeOp& op) { shovelerLogInfo("Authority change to %d for entity %lld.", op.Authority, op.EntityId); }); dispatcher.OnAddComponent<Heartbeat>([&](const worker::AddComponentOp<Heartbeat>& op) { lastHeartbeatMicrosMap[op.EntityId] = std::make_pair("(unknown)", view.Entities[op.EntityId].Get<Heartbeat>()->last_server_heartbeat()); shovelerLogInfo("Added client heartbeat for entity %lld.", op.EntityId); }); dispatcher.OnComponentUpdate<Heartbeat>([&](const worker::ComponentUpdateOp<Heartbeat>& op) { if (lastHeartbeatMicrosMap.find(op.EntityId) != lastHeartbeatMicrosMap.end()) { std::string clientWorkerId = "(unknown)"; const auto &clientComponentOption = view.Entities[op.EntityId].Get<Client>(); if (clientComponentOption) { clientWorkerId = clientComponentOption->worker_id(); } lastHeartbeatMicrosMap[op.EntityId] = std::make_pair(clientWorkerId, view.Entities[op.EntityId].Get<Heartbeat>()->last_server_heartbeat()); } shovelerLogTrace("Updated client heartbeat for entity %lld.", op.EntityId); }); dispatcher.OnRemoveComponent<Heartbeat>([&](const worker::RemoveComponentOp& op) { shovelerLogInfo("Removed client heartbeat for entity %lld.", op.EntityId); }); dispatcher.OnAuthorityChange<Heartbeat>([&](const worker::AuthorityChangeOp& op) { shovelerLogInfo("Changing heartbeat authority for entity %lld to %d.", op.EntityId, op.Authority); if (op.Authority == worker::Authority::kAuthoritative) { int64_t now = g_get_monotonic_time(); lastHeartbeatMicrosMap[op.EntityId] = std::make_pair("(unknown)", now); Heartbeat::Update heartbeatUpdate; heartbeatUpdate.set_last_server_heartbeat(now); connection.SendComponentUpdate<Heartbeat>(op.EntityId, heartbeatUpdate); } else if (op.Authority == worker::Authority::kNotAuthoritative) { lastHeartbeatMicrosMap.erase(op.EntityId); } }); dispatcher.OnCommandRequest<CreateClientEntity>([&](const worker::CommandRequestOp<CreateClientEntity>& op) { shovelerLogInfo("Received create client entity request from: %s", op.CallerWorkerId.c_str()); Color whiteColor{1.0f, 1.0f, 1.0f}; Drawable pointDrawable{DrawableType::POINT}; Material whiteParticleMaterial{MaterialType::PARTICLE, whiteColor, {}}; worker::Entity clientEntity; clientEntity.Add<Metadata>({"client"}); clientEntity.Add<Client>({op.CallerWorkerId}); clientEntity.Add<Heartbeat>({0, 0}); clientEntity.Add<Persistence>({}); clientEntity.Add<Position>({{0, 0, 0}}); clientEntity.Add<Model>({pointDrawable, whiteParticleMaterial, {0.0f, 0.0f, 0.0f}, {0.1f, 0.1f, 0.0f}, true, true, false, false, PolygonMode::FILL}); clientEntity.Add<Light>({LightType::POINT, 1024, 1024, 1, 0.01f, 80.0f, {0.1f, 0.1f, 0.1f}, {}}); WorkerAttributeSet clientAttributeSet({"client"}); WorkerAttributeSet serverAttributeSet({"server"}); WorkerRequirementSet specificClientRequirementSet({op.CallerAttributeSet}); WorkerRequirementSet serverRequirementSet({serverAttributeSet}); WorkerRequirementSet clientAndServerRequirementSet({clientAttributeSet, serverAttributeSet}); worker::Map<std::uint32_t, WorkerRequirementSet> clientEntityComponentAclMap; clientEntityComponentAclMap.insert({{Client::ComponentId, specificClientRequirementSet}}); clientEntityComponentAclMap.insert({{Heartbeat::ComponentId, serverRequirementSet}}); clientEntityComponentAclMap.insert({{Position::ComponentId, specificClientRequirementSet}}); EntityAclData clientEntityAclData(clientAndServerRequirementSet, clientEntityComponentAclMap); clientEntity.Add<EntityAcl>(clientEntityAclData); connection.SendCreateEntityRequest(clientEntity, {}, {}); connection.SendCommandResponse<CreateClientEntity>(op.RequestId, {}); }); dispatcher.OnCommandRequest<ClientPing>([&](const worker::CommandRequestOp<ClientPing>& op) { worker::EntityId clientEntityId = op.Request.client_entity_id(); worker::Map<worker::EntityId, worker::Map<worker::ComponentId, worker::Authority>>::const_iterator entityAuthorityQuery = view.ComponentAuthority.find(clientEntityId); if(entityAuthorityQuery == view.ComponentAuthority.end()) { shovelerLogWarning("Received client ping from %s for unknown client entity %lld, ignoring.", op.CallerWorkerId.c_str(), clientEntityId); return; } const worker::Map<worker::ComponentId, worker::Authority>& componentAuthorityMap = entityAuthorityQuery->second; worker::Map<worker::ComponentId, worker::Authority>::const_iterator componentAuthorityQuery = componentAuthorityMap.find(Heartbeat::ComponentId); if(componentAuthorityQuery == componentAuthorityMap.end()) { shovelerLogWarning("Received client ping from %s for client entity %lld without client heartbeat component, ignoring.", op.CallerWorkerId.c_str(), clientEntityId); return; } const worker::Authority& HeartbeatAuthority = componentAuthorityQuery->second; if(HeartbeatAuthority != worker::Authority::kAuthoritative) { shovelerLogWarning("Received client ping from %s for client entity %lld without authoritative client heartbeat component, ignoring.", op.CallerWorkerId.c_str(), clientEntityId); return; } int64_t now = g_get_monotonic_time(); Heartbeat::Update heartbeatUpdate; heartbeatUpdate.set_last_client_heartbeat(op.Request.client_heartbeat()); heartbeatUpdate.set_last_server_heartbeat(now); connection.SendComponentUpdate<Heartbeat>(clientEntityId, heartbeatUpdate); connection.SendCommandResponse<ClientPing>(op.RequestId, {now}); shovelerLogTrace("Received client ping from %s for client entity %lld.", op.CallerWorkerId.c_str(), clientEntityId); }); ClientCleanupTickContext cleanupTickContext{&connection, maxHeartbeatTimeoutMs, &lastHeartbeatMicrosMap}; uint32_t clientCleanupTickPeriod = (uint32_t) (1000.0 / (double) clientCleanupTickRateHz); shovelerExecutorSchedulePeriodic(tickExecutor, 0, clientCleanupTickPeriod, clientCleanupTick, &cleanupTickContext); uint32_t executorTickPeriod = (uint32_t) (1000.0 / (double) tickRateHz); while(!disconnected) { dispatcher.Process(connection.GetOpList(executorTickPeriod)); shovelerExecutorUpdateNow(tickExecutor); } shovelerExecutorFree(tickExecutor); } static void clientCleanupTick(void *clientCleanupTickContextPointer) { ClientCleanupTickContext *context = (ClientCleanupTickContext *) clientCleanupTickContextPointer; int64_t now = g_get_monotonic_time(); for(const auto& item: *context->lastHeartbeatMicrosMap) { worker::EntityId entityId = item.first; const std::string &workerId = item.second.first; int64_t last = item.second.second; int64_t diff = now - last; if (diff > 1000 * context->maxHeartbeatTimeoutMs) { shovelerLogWarning("Removing client entity %lld of worker %s because it exceeded the max ping timeout of %lldms.", entityId, workerId.c_str(), context->maxHeartbeatTimeoutMs); context->connection->SendDeleteEntityRequest(item.first, {}); } } } <|endoftext|>
<commit_before>#ifndef SHEAR__GRAMMAR_HPP #define SHEAR__GRAMMAR_HPP #include <map> #include <set> #include <queue> #include <boost/mpl/for_each.hpp> #include <boost/mpl/assert.hpp> #include <boost/mpl/has_key.hpp> #include <boost/foreach.hpp> #include <boost/spirit/home/phoenix/core/reference.hpp> #include <boost/spirit/home/phoenix/object/construct.hpp> #include <boost/spirit/home/phoenix/object/new.hpp> #include <boost/spirit/home/phoenix/stl/container.hpp> #include <boost/multi_index_container.hpp> #include <boost/multi_index/hashed_index.hpp> #include <boost/multi_index/mem_fun.hpp> #include <shear/grammar_exception.hpp> #include <shear/compiletime/grammar_base.hpp> #include <shear/runtime/non_terminal.hpp> #include <shear/runtime/production.hpp> namespace shear { template< typename RootSymbol, typename Tokens, typename Productions > class grammar : public compiletime::grammar_base<RootSymbol, Tokens, Productions> { BOOST_MPL_ASSERT(( typename mpl::has_key< typename grammar::non_terminals, typename grammar::root >::type )); public: typedef size_t symbol_index_type; typedef RootSymbol root_symbol; static const symbol_index_type num_symbols = mpl::size<typename grammar::symbol_index_vector>::type::value; static const symbol_index_type end_of_file_code = num_symbols; typedef typename mpl::at< typename grammar::symbol_index_map, typename grammar::root >::type root_index; grammar(); void check() throw(grammar_exception&); void check_for_loops() throw(grammar_loop_exception&); void check_for_non_productive_non_terminals() throw(non_productive_non_terminals_exception&); void check_for_non_reachable_non_terminals() throw(non_reachable_non_terminals_exception&); typedef boost::multi_index_container< runtime::production::ptr, boost::multi_index::indexed_by< boost::multi_index::hashed_non_unique< BOOST_MULTI_INDEX_CONST_MEM_FUN( runtime::production, symbol_index_type, source_index ) > > > ProductionMap; typedef boost::multi_index_container< runtime::non_terminal, boost::multi_index::indexed_by< boost::multi_index::hashed_unique< BOOST_MULTI_INDEX_CONST_MEM_FUN( runtime::non_terminal, symbol_index_type, index ) > > > NonTerminalMap; const NonTerminalMap& non_terminals_r() const { return non_terminals_r_; } void dump_productions(std::ostream&); private: ProductionMap productions_r_; NonTerminalMap non_terminals_r_; }; template<typename R, typename T, typename P> grammar<R, T, P>::grammar() { // Copy compile-time info to runtime versions mpl::for_each< typename grammar::productions, mpl::at<typename grammar::production_index_map, mpl::_1> >(px::insert( px::ref(productions_r_), px::construct<runtime::production::ptr>( px::new_<runtime::production>( arg1, typename grammar::production_index_vector(), typename grammar::symbol_index_map() ) ) )); mpl::for_each< typename grammar::non_terminals, mpl::at<typename grammar::symbol_index_map, mpl::_1> >(px::insert( px::ref(non_terminals_r_), px::construct<runtime::non_terminal>( arg1, px::cref(productions_r_), typename grammar::symbol_index_vector() ) )); // Determine which symbols produce empty bool altered; do { altered = false; BOOST_FOREACH(const typename NonTerminalMap::value_type& nt, non_terminals_r_) { if (!nt.produces_empty()) { BOOST_FOREACH(const runtime::production::ptr& production, nt.productions()) { bool can_be_empty = true; BOOST_FOREACH(symbol_index_type i, production->produced()) { if (!non_terminals_r_.find(i)->produces_empty()) { can_be_empty = false; break; } } if (can_be_empty) { nt.set_produces_empty(); altered = true; break; } } } } } while (altered); } template<typename R, typename T, typename P> void grammar<R, T, P>::check() throw(grammar_exception&) { check_for_loops(); check_for_non_productive_non_terminals(); check_for_non_reachable_non_terminals(); } template<typename R, typename T, typename P> void grammar<R, T, P>::check_for_loops() throw(grammar_loop_exception&) { BOOST_FOREACH(const runtime::non_terminal& checking_non_terminal, non_terminals_r_) { // Create a collection to store those non-terminals which this // one can produce std::set<symbol_index_type> non_terminals_produced; std::queue<symbol_index_type> non_terminals_to_process; non_terminals_to_process.push(checking_non_terminal.index()); while (!non_terminals_to_process.empty()) { // Get next produced non-terminal const runtime::non_terminal& to_process = *non_terminals_r_.find(non_terminals_to_process.front()); non_terminals_to_process.pop(); if (non_terminals_produced.count(to_process.index())) { continue; } // Add it to the collection of those produced non_terminals_produced.insert(to_process.index()); // Look for all rules capable of producing a single symbol BOOST_FOREACH(const runtime::production::ptr& production, to_process.productions()) { size_t min_length = 0; symbol_index_type last_compulsory_symbol = 0; BOOST_FOREACH(symbol_index_type symbol_index, production->produced()) { NonTerminalMap::iterator symbol = non_terminals_r_.find(symbol_index); if (symbol == non_terminals_r_.end() || !symbol->produces_empty()) { last_compulsory_symbol = symbol_index; ++min_length; if (min_length > 1) break; } } switch (min_length) { case 0: // In this case any of the symbols in the list can be produced alone BOOST_FOREACH(symbol_index_type symbol_index, production->produced()) { if (symbol_index == checking_non_terminal.index()) throw grammar_loop_exception(production); if (non_terminals_r_.count(symbol_index)) non_terminals_to_process.push(symbol_index); } break; case 1: // Check for a loop if (last_compulsory_symbol == checking_non_terminal.index()) throw grammar_loop_exception(production); // Enqueue this for further processing if (non_terminals_r_.count(last_compulsory_symbol)) non_terminals_to_process.push(last_compulsory_symbol); break; default: break; } } } } } template<typename R, typename T, typename P> void grammar<R, T, P>::check_for_non_productive_non_terminals() throw(non_productive_non_terminals_exception&) { // Create a collection of all productive non-terminals std::set<symbol_index_type> productive_non_terminals; // Repeatedly search through all non-terminals looking for new ones // to add to the collection size_t num_productive_non_terminals; do { num_productive_non_terminals = productive_non_terminals.size(); BOOST_FOREACH(const runtime::non_terminal& non_terminal, non_terminals_r_) { if (productive_non_terminals.count(non_terminal.index())) continue; BOOST_FOREACH(const runtime::production::ptr& production, non_terminal.productions()) { bool productiveProduction = true; BOOST_FOREACH(symbol_index_type symbol_index, production->produced()) { if (non_terminals_r_.count(symbol_index) && !productive_non_terminals.count(symbol_index)) { productiveProduction = false; break; } } if (productiveProduction) { productive_non_terminals.insert(non_terminal.index()); break; } } } } while (productive_non_terminals.size() > num_productive_non_terminals); if (num_productive_non_terminals < non_terminals_r_.size()) { std::set<runtime::non_terminal> non_productive_non_terminals; BOOST_FOREACH(const runtime::non_terminal& non_terminal, non_terminals_r_) if (!productive_non_terminals.count(non_terminal.index())) non_productive_non_terminals.insert(non_terminal); throw non_productive_non_terminals_exception(non_productive_non_terminals); } } template<typename R, typename T, typename P> void grammar<R, T, P>::check_for_non_reachable_non_terminals() throw(non_reachable_non_terminals_exception&) { // Create a collection of all reachable non-terminals std::set<symbol_index_type> reachable_non_terminals; reachable_non_terminals.insert(root_index::value); std::queue<symbol_index_type> non_terminals_to_process; non_terminals_to_process.push(root_index::value); // Process everything in the Queue until nothing is left while (!non_terminals_to_process.empty()) { symbol_index_type to_process = non_terminals_to_process.front(); non_terminals_to_process.pop(); BOOST_FOREACH(const runtime::production::ptr& production, non_terminals_r_.find(to_process)->productions()) { BOOST_FOREACH(symbol_index_type symbol_index, production->produced()) { if (non_terminals_r_.count(symbol_index) && !reachable_non_terminals.count(symbol_index)) { reachable_non_terminals.insert(symbol_index); non_terminals_to_process.push(symbol_index); } } } } if (reachable_non_terminals.size() < non_terminals_r_.size()) { std::set<symbol_index_type> non_reachable_non_terminals; BOOST_FOREACH(const runtime::non_terminal& non_terminal, non_terminals_r_) if (!reachable_non_terminals.count(non_terminal.index())) non_reachable_non_terminals.insert(non_terminal.index()); throw non_reachable_non_terminals_exception(non_reachable_non_terminals); } } template<typename R, typename T, typename P> void grammar<R, T, P>::dump_productions(std::ostream& o) { BOOST_FOREACH(runtime::production::ptr production, productions_r_) { o << "production "<<production->index() << ":"; BOOST_FOREACH(symbol_index_type symbol_index, production->produced()) { o << ' ' << symbol_index; } o << '\n'; } } } #endif // SHEAR__GRAMMAR_HPP <commit_msg>Avoid dereferencing invalid iterator<commit_after>#ifndef SHEAR__GRAMMAR_HPP #define SHEAR__GRAMMAR_HPP #include <map> #include <set> #include <queue> #include <boost/mpl/for_each.hpp> #include <boost/mpl/assert.hpp> #include <boost/mpl/has_key.hpp> #include <boost/foreach.hpp> #include <boost/spirit/home/phoenix/core/reference.hpp> #include <boost/spirit/home/phoenix/object/construct.hpp> #include <boost/spirit/home/phoenix/object/new.hpp> #include <boost/spirit/home/phoenix/stl/container.hpp> #include <boost/multi_index_container.hpp> #include <boost/multi_index/hashed_index.hpp> #include <boost/multi_index/mem_fun.hpp> #include <shear/grammar_exception.hpp> #include <shear/compiletime/grammar_base.hpp> #include <shear/runtime/non_terminal.hpp> #include <shear/runtime/production.hpp> namespace shear { template< typename RootSymbol, typename Tokens, typename Productions > class grammar : public compiletime::grammar_base<RootSymbol, Tokens, Productions> { BOOST_MPL_ASSERT(( typename mpl::has_key< typename grammar::non_terminals, typename grammar::root >::type )); public: typedef size_t symbol_index_type; typedef RootSymbol root_symbol; static const symbol_index_type num_symbols = mpl::size<typename grammar::symbol_index_vector>::type::value; static const symbol_index_type end_of_file_code = num_symbols; typedef typename mpl::at< typename grammar::symbol_index_map, typename grammar::root >::type root_index; grammar(); void check() throw(grammar_exception&); void check_for_loops() throw(grammar_loop_exception&); void check_for_non_productive_non_terminals() throw(non_productive_non_terminals_exception&); void check_for_non_reachable_non_terminals() throw(non_reachable_non_terminals_exception&); typedef boost::multi_index_container< runtime::production::ptr, boost::multi_index::indexed_by< boost::multi_index::hashed_non_unique< BOOST_MULTI_INDEX_CONST_MEM_FUN( runtime::production, symbol_index_type, source_index ) > > > ProductionMap; typedef boost::multi_index_container< runtime::non_terminal, boost::multi_index::indexed_by< boost::multi_index::hashed_unique< BOOST_MULTI_INDEX_CONST_MEM_FUN( runtime::non_terminal, symbol_index_type, index ) > > > NonTerminalMap; const NonTerminalMap& non_terminals_r() const { return non_terminals_r_; } void dump_productions(std::ostream&); private: ProductionMap productions_r_; NonTerminalMap non_terminals_r_; }; template<typename R, typename T, typename P> grammar<R, T, P>::grammar() { // Copy compile-time info to runtime versions mpl::for_each< typename grammar::productions, mpl::at<typename grammar::production_index_map, mpl::_1> >(px::insert( px::ref(productions_r_), px::construct<runtime::production::ptr>( px::new_<runtime::production>( arg1, typename grammar::production_index_vector(), typename grammar::symbol_index_map() ) ) )); mpl::for_each< typename grammar::non_terminals, mpl::at<typename grammar::symbol_index_map, mpl::_1> >(px::insert( px::ref(non_terminals_r_), px::construct<runtime::non_terminal>( arg1, px::cref(productions_r_), typename grammar::symbol_index_vector() ) )); // Determine which symbols produce empty bool altered; do { altered = false; BOOST_FOREACH(const typename NonTerminalMap::value_type& nt, non_terminals_r_) { if (!nt.produces_empty()) { BOOST_FOREACH(const runtime::production::ptr& production, nt.productions()) { bool can_be_empty = true; BOOST_FOREACH(symbol_index_type i, production->produced()) { NonTerminalMap::iterator it = non_terminals_r_.find(i); if (it == non_terminals_r_.end() || !it->produces_empty()) { can_be_empty = false; break; } } if (can_be_empty) { nt.set_produces_empty(); altered = true; break; } } } } } while (altered); } template<typename R, typename T, typename P> void grammar<R, T, P>::check() throw(grammar_exception&) { check_for_loops(); check_for_non_productive_non_terminals(); check_for_non_reachable_non_terminals(); } template<typename R, typename T, typename P> void grammar<R, T, P>::check_for_loops() throw(grammar_loop_exception&) { BOOST_FOREACH(const runtime::non_terminal& checking_non_terminal, non_terminals_r_) { // Create a collection to store those non-terminals which this // one can produce std::set<symbol_index_type> non_terminals_produced; std::queue<symbol_index_type> non_terminals_to_process; non_terminals_to_process.push(checking_non_terminal.index()); while (!non_terminals_to_process.empty()) { // Get next produced non-terminal const runtime::non_terminal& to_process = *non_terminals_r_.find(non_terminals_to_process.front()); non_terminals_to_process.pop(); if (non_terminals_produced.count(to_process.index())) { continue; } // Add it to the collection of those produced non_terminals_produced.insert(to_process.index()); // Look for all rules capable of producing a single symbol BOOST_FOREACH(const runtime::production::ptr& production, to_process.productions()) { size_t min_length = 0; symbol_index_type last_compulsory_symbol = 0; BOOST_FOREACH(symbol_index_type symbol_index, production->produced()) { NonTerminalMap::iterator symbol = non_terminals_r_.find(symbol_index); if (symbol == non_terminals_r_.end() || !symbol->produces_empty()) { last_compulsory_symbol = symbol_index; ++min_length; if (min_length > 1) break; } } switch (min_length) { case 0: // In this case any of the symbols in the list can be produced alone BOOST_FOREACH(symbol_index_type symbol_index, production->produced()) { if (symbol_index == checking_non_terminal.index()) throw grammar_loop_exception(production); if (non_terminals_r_.count(symbol_index)) non_terminals_to_process.push(symbol_index); } break; case 1: // Check for a loop if (last_compulsory_symbol == checking_non_terminal.index()) throw grammar_loop_exception(production); // Enqueue this for further processing if (non_terminals_r_.count(last_compulsory_symbol)) non_terminals_to_process.push(last_compulsory_symbol); break; default: break; } } } } } template<typename R, typename T, typename P> void grammar<R, T, P>::check_for_non_productive_non_terminals() throw(non_productive_non_terminals_exception&) { // Create a collection of all productive non-terminals std::set<symbol_index_type> productive_non_terminals; // Repeatedly search through all non-terminals looking for new ones // to add to the collection size_t num_productive_non_terminals; do { num_productive_non_terminals = productive_non_terminals.size(); BOOST_FOREACH(const runtime::non_terminal& non_terminal, non_terminals_r_) { if (productive_non_terminals.count(non_terminal.index())) continue; BOOST_FOREACH(const runtime::production::ptr& production, non_terminal.productions()) { bool productiveProduction = true; BOOST_FOREACH(symbol_index_type symbol_index, production->produced()) { if (non_terminals_r_.count(symbol_index) && !productive_non_terminals.count(symbol_index)) { productiveProduction = false; break; } } if (productiveProduction) { productive_non_terminals.insert(non_terminal.index()); break; } } } } while (productive_non_terminals.size() > num_productive_non_terminals); if (num_productive_non_terminals < non_terminals_r_.size()) { std::set<runtime::non_terminal> non_productive_non_terminals; BOOST_FOREACH(const runtime::non_terminal& non_terminal, non_terminals_r_) if (!productive_non_terminals.count(non_terminal.index())) non_productive_non_terminals.insert(non_terminal); throw non_productive_non_terminals_exception(non_productive_non_terminals); } } template<typename R, typename T, typename P> void grammar<R, T, P>::check_for_non_reachable_non_terminals() throw(non_reachable_non_terminals_exception&) { // Create a collection of all reachable non-terminals std::set<symbol_index_type> reachable_non_terminals; reachable_non_terminals.insert(root_index::value); std::queue<symbol_index_type> non_terminals_to_process; non_terminals_to_process.push(root_index::value); // Process everything in the Queue until nothing is left while (!non_terminals_to_process.empty()) { symbol_index_type to_process = non_terminals_to_process.front(); non_terminals_to_process.pop(); BOOST_FOREACH(const runtime::production::ptr& production, non_terminals_r_.find(to_process)->productions()) { BOOST_FOREACH(symbol_index_type symbol_index, production->produced()) { if (non_terminals_r_.count(symbol_index) && !reachable_non_terminals.count(symbol_index)) { reachable_non_terminals.insert(symbol_index); non_terminals_to_process.push(symbol_index); } } } } if (reachable_non_terminals.size() < non_terminals_r_.size()) { std::set<symbol_index_type> non_reachable_non_terminals; BOOST_FOREACH(const runtime::non_terminal& non_terminal, non_terminals_r_) if (!reachable_non_terminals.count(non_terminal.index())) non_reachable_non_terminals.insert(non_terminal.index()); throw non_reachable_non_terminals_exception(non_reachable_non_terminals); } } template<typename R, typename T, typename P> void grammar<R, T, P>::dump_productions(std::ostream& o) { BOOST_FOREACH(runtime::production::ptr production, productions_r_) { o << "production "<<production->index() << ":"; BOOST_FOREACH(symbol_index_type symbol_index, production->produced()) { o << ' ' << symbol_index; } o << '\n'; } } } #endif // SHEAR__GRAMMAR_HPP <|endoftext|>
<commit_before>#include "PressureNeumannBC.h" template<> InputParameters validParams<PressureNeumannBC>() { InputParameters params = validParams<IntegratedBC>(); params.addCoupledVar("p", ""); params.addCoupledVar("pe", ""); params.addCoupledVar("pu", ""); params.addCoupledVar("pv", ""); params.set<Real>("component"); return params; } PressureNeumannBC::PressureNeumannBC(const std::string & name, InputParameters parameters) :IntegratedBC(name, parameters), _p(coupledValue("p")), _pe(coupledValue("pe")), _pu(coupledValue("pu")), _pv(coupledValue("pv")), _pw(_dim == 3 ? coupledValue("pw") : _zero), _component(getParam<Real>("component")), _gamma(getMaterialProperty<Real>("gamma")) { if(_component < 0) { std::cout<<"Must select a component for PressureNeumannBC"<<std::endl; libmesh_error(); } } Real PressureNeumannBC::pressure() { Real _u_vel = _pu[_qp] / _p[_qp]; Real _v_vel = _pv[_qp] / _p[_qp]; Real _w_vel = _pw[_qp] / _p[_qp]; return (_gamma[_qp] - 1)*(_pe[_qp] - (0.5 * _p[_qp] * (_u_vel*_u_vel + _v_vel*_v_vel + _w_vel*_w_vel))); } Real PressureNeumannBC::computeQpResidual() { return pressure()*_normals[_qp](_component)*_phi[_i][_qp]; } <commit_msg>Pressure Neumann BC kernel references pw, so it should be added as a CoupledVar.<commit_after>#include "PressureNeumannBC.h" template<> InputParameters validParams<PressureNeumannBC>() { InputParameters params = validParams<IntegratedBC>(); params.addCoupledVar("p", ""); params.addCoupledVar("pe", ""); params.addCoupledVar("pu", ""); params.addCoupledVar("pv", ""); params.addCoupledVar("pw", ""); params.set<Real>("component"); return params; } PressureNeumannBC::PressureNeumannBC(const std::string & name, InputParameters parameters) :IntegratedBC(name, parameters), _p(coupledValue("p")), _pe(coupledValue("pe")), _pu(coupledValue("pu")), _pv(coupledValue("pv")), _pw(_dim == 3 ? coupledValue("pw") : _zero), _component(getParam<Real>("component")), _gamma(getMaterialProperty<Real>("gamma")) { if(_component < 0) { std::cout<<"Must select a component for PressureNeumannBC"<<std::endl; libmesh_error(); } } Real PressureNeumannBC::pressure() { Real _u_vel = _pu[_qp] / _p[_qp]; Real _v_vel = _pv[_qp] / _p[_qp]; Real _w_vel = _pw[_qp] / _p[_qp]; return (_gamma[_qp] - 1)*(_pe[_qp] - (0.5 * _p[_qp] * (_u_vel*_u_vel + _v_vel*_v_vel + _w_vel*_w_vel))); } Real PressureNeumannBC::computeQpResidual() { return pressure()*_normals[_qp](_component)*_phi[_i][_qp]; } <|endoftext|>
<commit_before>#include "sipp/internals/speed_fwd.hpp" #include "internals/speed_fwd.hpp" <commit_msg>Fixed wrong path in fwd header<commit_after>#pragma once #include "internals/distance_fwd.hpp" #include "internals/speed_fwd.hpp" <|endoftext|>
<commit_before> // (c) COPYRIGHT URI/MIT 1996 // Please read the full copyright statement in the file COPYRIGH. // // Authors: // jhrg,jimg James Gallagher (jgallagher@gso.uri.edu) // This is the source to `geturl'; a simple tool to exercise the Connect // class. It can be used to get naked URLs as well as the DODS DAS and DDS // objects. jhrg. // $Log: getdap.cc,v $ // Revision 1.18 1997/02/12 21:45:03 jimg // Added use of the optional parameter to Connect's ctor; if -t (trace) is // given on the command line, then print www library informational messages. // Changed trace option switch from -v (which is now used for verbose - an // option that is entirely separate from trace) to -t. // // Revision 1.17 1997/02/10 02:36:10 jimg // Modified usage of request_data() to match new return type. // // Revision 1.16 1996/12/18 18:43:32 jimg // Tried to fix the online help - maybe I succeeded? // // Revision 1.15 1996/11/27 22:12:33 jimg // Expanded help to include all the verbose options. // Added PERF macros to code around request_data() call. // // Revision 1.14 1996/11/20 00:37:47 jimg // Modified -D option to correctly process the Asynchronous option. // // Revision 1.13 1996/11/16 00:20:47 jimg // Fixed a bug where multiple urls failed. // // Revision 1.12 1996/10/31 22:24:05 jimg // Fix the help message so that -D is not described as -A... // // Revision 1.11 1996/10/08 17:13:09 jimg // Added test for the -D option so that a Ce can be supplied either with the // -c option or using a ? at the end of the URL. // // Revision 1.10 1996/09/19 16:53:35 jimg // Added code to process sequences correctly when given the -D (get data) // option. // // Revision 1.9 1996/09/05 16:28:06 jimg // Added a new option to geturl, -D, which uses the Connect::request_data // member function to get data. Thus -a, -d and -D can be used to get the // das, dds and data from a DODS server. Because the request_data member // function requires a constraint expression I also added the option -c; this // option takes as a single argument a constraint expression and passes it to // the request_data member function. You must use -c <expr> with -D. // // Revision 1.8 1996/08/13 20:13:36 jimg // Added __unused__ to definition of char rcsid[]. // Added code so that local `URLs' are skipped. // // Revision 1.7 1996/06/22 00:11:20 jimg // Modified to accomodate the new Gui class. // // Revision 1.6 1996/06/18 23:55:33 jimg // Added support for the GUI progress indicator. // // Revision 1.5 1996/06/08 00:18:38 jimg // Initialized vcode to null. // // Revision 1.4 1996/05/29 22:05:57 jimg // Fixed up the copyright header. // // Revision 1.3 1996/05/28 17:35:40 jimg // Fixed verbose arguments. // // Revision 1.2 1996/05/28 15:49:55 jimg // Removed code that read from the stream after the das/dds parser built the // internal object (since there was nothing in that stream after the parse // geturl would always crash). // // Revision 1.1 1996/05/22 23:34:21 jimg // First version. Built to test the new WWW code in the class Connect. // #include "config_dap.h" static char rcsid[] __unused__ = {"$Id: getdap.cc,v 1.18 1997/02/12 21:45:03 jimg Exp $"}; #include <stdio.h> #include <assert.h> #include <GetOpt.h> #include <String.h> #include "Connect.h" void usage(String name) { cerr << "Usage: " << name << "[AdDagV] [c <expr>] [t <codes>] [m <num>] <url> [<url> ...]" << endl; cerr << " " << "A: Use Connect's asynchronous mode." << endl; cerr << " " << "d: For each URL, get the DODS DDS." << endl; cerr << " " << "a: For each URL, get the DODS DAS." << endl; cerr << " " << "D: For each URL, get the DODS Data." << endl; cerr << " " << "g: Show the progress GUI." << endl; cerr << " " << "V: Version." << endl; cerr << " " << "c: <expr> is a contraint expression. Used with -D." << endl; cerr << " " << " NB: You can use a `?' for the CE also." << endl; cerr << " " << "t: <options> trace output; use -td for default." << endl; cerr << " " << " a: show_anchor_trace." << endl; cerr << " " << " b: show_bind_trace." << endl; cerr << " " << " c: show_cache_trace." << endl; cerr << " " << " l: show_sgml_trace." << endl; cerr << " " << " m: show_mem_trace." << endl; cerr << " " << " p: show_protocol_trace." << endl; cerr << " " << " s: show_stream_trace." << endl; cerr << " " << " t: show_thread_trace." << endl; cerr << " " << " u: show_uri_trace." << endl; cerr << " " << "m: Request the same URL <num> times." << endl; cerr << " " << "Without A, use the synchronous mode." << endl; cerr << " " << "Without d or a, print the URL." << endl; } bool read_data(FILE *fp) { char c; if (!fp) { cerr <<"Whoa!!! Null stream pointer." << endl; return false; } // Changed from a loop that used getc() to one that uses fread(). getc() // worked fine for transfers of text information, but *not* for binary // transfers. fread() will handle both. while (fread(&c, 1, 1, fp)) printf("%c", c); // stick with stdio return true; } int main(int argc, char * argv[]) { GetOpt getopt (argc, argv, "AdaDgVc:t:m:"); int option_char; bool async = false; bool get_das = false; bool get_dds = false; bool get_data = false; bool gui = false; bool cexpr = false; bool verbose = false; bool trace = false; bool multi = false; int times = 1; char *tcode = NULL; char *expr = NULL; int topts = 0; while ((option_char = getopt()) != EOF) switch (option_char) { case 'A': async = true; break; case 'd': get_dds = true; break; case 'a': get_das = true; break; case 'D': get_data = true; break; case 'V': verbose = true; break; case 'g': gui = true; break; case 'c': cexpr = true; expr = getopt.optarg; break; case 't': trace = true; topts = strlen(getopt.optarg); if (topts) { tcode = new char[topts + 1]; strcpy(tcode, getopt.optarg); } break; case 'm': multi = true; times = atoi(getopt.optarg); break; case 'h': case '?': default: usage(argv[0]); exit(1); break; } char c, *cc = tcode; if (trace && topts > 0) while ((c = *cc++)) switch (c) { case 'a': WWWTRACE |= SHOW_ANCHOR_TRACE; break; case 'b': WWWTRACE |= SHOW_BIND_TRACE; break; case 'c': WWWTRACE |= SHOW_CACHE_TRACE; break; case 'l': WWWTRACE |= SHOW_SGML_TRACE; break; case 'm': WWWTRACE |= SHOW_MEM_TRACE; break; case 'p': WWWTRACE |= SHOW_PROTOCOL_TRACE; break; case 's': WWWTRACE |= SHOW_STREAM_TRACE; break; case 't': WWWTRACE |= SHOW_THREAD_TRACE; break; case 'u': WWWTRACE |= SHOW_URI_TRACE; break; case 'd': break; default: cerr << "Unrecognized trace option: `" << c << "'" << endl; break; } delete tcode; for (int i = getopt.optind; i < argc; ++i) { if (verbose) cerr << "Fetching " << argv[i] << ":" << endl; String name = argv[i]; Connect url(name, trace); if (url.is_local()) { cerr << "Skipping the URL `" << argv[i] << "' because it lacks the `http' access protocol." << endl; continue; } if (get_das) { for (int j = 0; j < times; ++j) { if (!url.request_das(gui)) continue; if (verbose) cerr << "DAS:" << endl; url.das().print(); } } if (get_dds) { for (int j = 0; j < times; ++j) { if (!url.request_dds(gui)) continue; if (verbose) cerr << "DDS:" << endl; url.dds().print(); } } if (get_data) { if (!(expr || name.contains("?"))) { cerr << "Must supply a constraint expression with -D." << endl; continue; } for (int j = 0; j < times; ++j) { DDS *dds = url.request_data(expr, gui, async); if (!dds) { cerr << "Error reading data" << endl; continue; } cout << "The data:" << endl; for (Pix q = dds->first_var(); q; dds->next_var(q)) { BaseType *v = dds->var(q); switch (v->type()) { // Sequences present a special case because I let // their semantics get out of hand... jhrg 9/12/96 case dods_sequence_c: ((Sequence *)v)->print_all_vals(cout, url.source()); break; default: PERF(cerr << "Deserializing: " << dds.var(q).name() \ << endl); if (async && !dds->var(q)->deserialize(url.source())) { cerr << "Asynchronous read failure." << endl; exit(1); } PERF(cerr << "Deserializing complete" << endl); dds->var(q)->print_val(cout); break; } } } } if (!get_das && !get_dds && !get_data) { if (gui) url.gui()->show_gui(gui); String url_string = argv[i]; for (int j = 0; j < times; ++j) { if (!url.fetch_url(url_string, async)) continue; FILE *fp = url.output(); if (!read_data(fp)) continue; fclose(fp); } } } } <commit_msg>Added version switch. Made compatible with writeval's command line options.<commit_after> // (c) COPYRIGHT URI/MIT 1996 // Please read the full copyright statement in the file COPYRIGH. // // Authors: // jhrg,jimg James Gallagher (jgallagher@gso.uri.edu) // This is the source to `geturl'; a simple tool to exercise the Connect // class. It can be used to get naked URLs as well as the DODS DAS and DDS // objects. jhrg. // $Log: getdap.cc,v $ // Revision 1.19 1997/02/13 00:21:28 jimg // Added version switch. Made compatible with writeval's command line options. // // Revision 1.18 1997/02/12 21:45:03 jimg // Added use of the optional parameter to Connect's ctor; if -t (trace) is // given on the command line, then print www library informational messages. // Changed trace option switch from -v (which is now used for verbose - an // option that is entirely separate from trace) to -t. // // Revision 1.17 1997/02/10 02:36:10 jimg // Modified usage of request_data() to match new return type. // // Revision 1.16 1996/12/18 18:43:32 jimg // Tried to fix the online help - maybe I succeeded? // // Revision 1.15 1996/11/27 22:12:33 jimg // Expanded help to include all the verbose options. // Added PERF macros to code around request_data() call. // // Revision 1.14 1996/11/20 00:37:47 jimg // Modified -D option to correctly process the Asynchronous option. // // Revision 1.13 1996/11/16 00:20:47 jimg // Fixed a bug where multiple urls failed. // // Revision 1.12 1996/10/31 22:24:05 jimg // Fix the help message so that -D is not described as -A... // // Revision 1.11 1996/10/08 17:13:09 jimg // Added test for the -D option so that a Ce can be supplied either with the // -c option or using a ? at the end of the URL. // // Revision 1.10 1996/09/19 16:53:35 jimg // Added code to process sequences correctly when given the -D (get data) // option. // // Revision 1.9 1996/09/05 16:28:06 jimg // Added a new option to geturl, -D, which uses the Connect::request_data // member function to get data. Thus -a, -d and -D can be used to get the // das, dds and data from a DODS server. Because the request_data member // function requires a constraint expression I also added the option -c; this // option takes as a single argument a constraint expression and passes it to // the request_data member function. You must use -c <expr> with -D. // // Revision 1.8 1996/08/13 20:13:36 jimg // Added __unused__ to definition of char rcsid[]. // Added code so that local `URLs' are skipped. // // Revision 1.7 1996/06/22 00:11:20 jimg // Modified to accomodate the new Gui class. // // Revision 1.6 1996/06/18 23:55:33 jimg // Added support for the GUI progress indicator. // // Revision 1.5 1996/06/08 00:18:38 jimg // Initialized vcode to null. // // Revision 1.4 1996/05/29 22:05:57 jimg // Fixed up the copyright header. // // Revision 1.3 1996/05/28 17:35:40 jimg // Fixed verbose arguments. // // Revision 1.2 1996/05/28 15:49:55 jimg // Removed code that read from the stream after the das/dds parser built the // internal object (since there was nothing in that stream after the parse // geturl would always crash). // // Revision 1.1 1996/05/22 23:34:21 jimg // First version. Built to test the new WWW code in the class Connect. // #include "config_dap.h" static char rcsid[] __unused__ = {"$Id: getdap.cc,v 1.19 1997/02/13 00:21:28 jimg Exp $"}; #include <stdio.h> #include <assert.h> #include <GetOpt.h> #include <String.h> #include "Connect.h" const char *VERSION = "$Revision: 1.19 $"; void usage(String name) { cerr << "Usage: " << name << "[dDagVv] [c <expr>] [t <codes>] [m <num>] <url> [<url> ...]" << endl; #if 0 cerr << " " << "A: Use Connect's asynchronous mode." << endl; #endif cerr << " " << "d: For each URL, get the DODS DDS." << endl; cerr << " " << "a: For each URL, get the DODS DAS." << endl; cerr << " " << "D: For each URL, get the DODS Data." << endl; cerr << " " << "g: Show the progress GUI." << endl; cerr << " " << "v: Verbose." << endl; cerr << " " << "V: Version." << endl; cerr << " " << "c: <expr> is a contraint expression. Used with -D." << endl; cerr << " " << " NB: You can use a `?' for the CE also." << endl; cerr << " " << "t: <options> trace output; use -td for default." << endl; cerr << " " << " a: show_anchor_trace." << endl; cerr << " " << " b: show_bind_trace." << endl; cerr << " " << " c: show_cache_trace." << endl; cerr << " " << " l: show_sgml_trace." << endl; cerr << " " << " m: show_mem_trace." << endl; cerr << " " << " p: show_protocol_trace." << endl; cerr << " " << " s: show_stream_trace." << endl; cerr << " " << " t: show_thread_trace." << endl; cerr << " " << " u: show_uri_trace." << endl; cerr << " " << "m: Request the same URL <num> times." << endl; cerr << " " << "Without A, use the synchronous mode." << endl; cerr << " " << "Without d or a, print the URL." << endl; } bool read_data(FILE *fp) { char c; if (!fp) { cerr <<"Whoa!!! Null stream pointer." << endl; return false; } // Changed from a loop that used getc() to one that uses fread(). getc() // worked fine for transfers of text information, but *not* for binary // transfers. fread() will handle both. while (fread(&c, 1, 1, fp)) printf("%c", c); // stick with stdio return true; } int main(int argc, char * argv[]) { GetOpt getopt (argc, argv, "AdaDgVvc:t:m:"); int option_char; bool async = false; bool get_das = false; bool get_dds = false; bool get_data = false; bool gui = false; bool cexpr = false; bool verbose = false; bool trace = false; bool multi = false; int times = 1; char *tcode = NULL; char *expr = NULL; int topts = 0; while ((option_char = getopt()) != EOF) switch (option_char) { case 'A': async = true; break; case 'd': get_dds = true; break; case 'a': get_das = true; break; case 'D': get_data = true; break; case 'V': cerr << "geturl version: " << VERSION << endl; exit(0); case 'v': verbose = true; break; case 'g': gui = true; break; case 'c': cexpr = true; expr = getopt.optarg; break; case 't': trace = true; topts = strlen(getopt.optarg); if (topts) { tcode = new char[topts + 1]; strcpy(tcode, getopt.optarg); } break; case 'm': multi = true; times = atoi(getopt.optarg); break; case 'h': case '?': default: usage(argv[0]); exit(1); break; } char c, *cc = tcode; if (trace && topts > 0) while ((c = *cc++)) switch (c) { case 'a': WWWTRACE |= SHOW_ANCHOR_TRACE; break; case 'b': WWWTRACE |= SHOW_BIND_TRACE; break; case 'c': WWWTRACE |= SHOW_CACHE_TRACE; break; case 'l': WWWTRACE |= SHOW_SGML_TRACE; break; case 'm': WWWTRACE |= SHOW_MEM_TRACE; break; case 'p': WWWTRACE |= SHOW_PROTOCOL_TRACE; break; case 's': WWWTRACE |= SHOW_STREAM_TRACE; break; case 't': WWWTRACE |= SHOW_THREAD_TRACE; break; case 'u': WWWTRACE |= SHOW_URI_TRACE; break; case 'd': break; default: cerr << "Unrecognized trace option: `" << c << "'" << endl; break; } delete tcode; for (int i = getopt.optind; i < argc; ++i) { if (verbose) cerr << "Fetching " << argv[i] << ":" << endl; String name = argv[i]; Connect url(name, trace); if (url.is_local()) { cerr << "Skipping the URL `" << argv[i] << "' because it lacks the `http' access protocol." << endl; continue; } if (get_das) { for (int j = 0; j < times; ++j) { if (!url.request_das(gui)) continue; if (verbose) cerr << "DAS:" << endl; url.das().print(); } } if (get_dds) { for (int j = 0; j < times; ++j) { if (!url.request_dds(gui)) continue; if (verbose) cerr << "DDS:" << endl; url.dds().print(); } } if (get_data) { if (!(expr || name.contains("?"))) { cerr << "Must supply a constraint expression with -D." << endl; continue; } for (int j = 0; j < times; ++j) { DDS *dds = url.request_data(expr, gui, async); if (!dds) { cerr << "Error reading data" << endl; continue; } cout << "The data:" << endl; for (Pix q = dds->first_var(); q; dds->next_var(q)) { BaseType *v = dds->var(q); switch (v->type()) { // Sequences present a special case because I let // their semantics get out of hand... jhrg 9/12/96 case dods_sequence_c: ((Sequence *)v)->print_all_vals(cout, url.source()); break; default: PERF(cerr << "Deserializing: " << dds.var(q).name() \ << endl); if (async && !dds->var(q)->deserialize(url.source())) { cerr << "Asynchronous read failure." << endl; exit(1); } PERF(cerr << "Deserializing complete" << endl); dds->var(q)->print_val(cout); break; } } } } if (!get_das && !get_dds && !get_data) { if (gui) url.gui()->show_gui(gui); String url_string = argv[i]; for (int j = 0; j < times; ++j) { if (!url.fetch_url(url_string, async)) continue; FILE *fp = url.output(); if (!read_data(fp)) continue; fclose(fp); } } } } <|endoftext|>
<commit_before>// // FilteringSpeaker.h // Clock Signal // // Created by Thomas Harte on 15/12/2017. // Copyright 2017 Thomas Harte. All rights reserved. // #ifndef FilteringSpeaker_h #define FilteringSpeaker_h #include "../Speaker.hpp" #include "../../../SignalProcessing/Stepper.hpp" #include "../../../SignalProcessing/FIRFilter.hpp" #include "../../../ClockReceiver/ClockReceiver.hpp" #include "../../../Concurrency/AsyncTaskQueue.hpp" #include <mutex> #include <cstring> namespace Outputs { namespace Speaker { /*! The low-pass speaker expects an Outputs::Speaker::SampleSource-derived template class, and uses the instance supplied to its constructor as the source of a high-frequency stream of audio which it filters down to a lower-frequency output. */ template <typename T> class LowpassSpeaker: public Speaker { public: LowpassSpeaker(T &sample_source) : sample_source_(sample_source) { sample_source.set_sample_volume_range(32767); } // Implemented as per Speaker. float get_ideal_clock_rate_in_range(float minimum, float maximum) { std::lock_guard<std::mutex> lock_guard(filter_parameters_mutex_); // return twice the cut off, if applicable if( filter_parameters_.high_frequency_cutoff > 0.0f && filter_parameters_.input_cycles_per_second >= filter_parameters_.high_frequency_cutoff * 3.0f && filter_parameters_.input_cycles_per_second <= filter_parameters_.high_frequency_cutoff * 3.0f) return filter_parameters_.high_frequency_cutoff * 3.0f; // return exactly the input rate if possible if( filter_parameters_.input_cycles_per_second >= minimum && filter_parameters_.input_cycles_per_second <= maximum) return filter_parameters_.input_cycles_per_second; // if the input rate is lower, return the minimum if(filter_parameters_.input_cycles_per_second < minimum) return minimum; // otherwise, return the maximum return maximum; } // Implemented as per Speaker. void set_output_rate(float cycles_per_second, int buffer_size) { std::lock_guard<std::mutex> lock_guard(filter_parameters_mutex_); filter_parameters_.output_cycles_per_second = cycles_per_second; filter_parameters_.parameters_are_dirty = true; output_buffer_.resize(static_cast<std::size_t>(buffer_size)); } /*! Sets the clock rate of the input audio. */ void set_input_rate(float cycles_per_second) { std::lock_guard<std::mutex> lock_guard(filter_parameters_mutex_); filter_parameters_.input_cycles_per_second = cycles_per_second; filter_parameters_.parameters_are_dirty = true; filter_parameters_.input_rate_changed = true; } /*! Allows a cut-off frequency to be specified for audio. Ordinarily this low-pass speaker will determine a cut-off based on the output audio rate. A caller can manually select an alternative cut-off. This allows machines with a low-pass filter on their audio output path to be explicit about its effect, and get that simulation for free. */ void set_high_frequency_cutoff(float high_frequency) { std::lock_guard<std::mutex> lock_guard(filter_parameters_mutex_); filter_parameters_.high_frequency_cutoff = high_frequency; filter_parameters_.parameters_are_dirty = true; } /*! Schedules an advancement by the number of cycles specified on the provided queue. The speaker will advance by obtaining data from the sample source supplied at construction, filtering it and passing it on to the speaker's delegate if there is one. */ void run_for(Concurrency::DeferringAsyncTaskQueue &queue, const Cycles cycles) { queue.defer([this, cycles] { run_for(cycles); }); } private: /*! Advances by the number of cycles specified, obtaining data from the sample source supplied at construction, filtering it and passing it on to the speaker's delegate if there is one. */ void run_for(const Cycles cycles) { if(!delegate_) return; std::size_t cycles_remaining = static_cast<size_t>(cycles.as_int()); if(!cycles_remaining) return; FilterParameters filter_parameters; { std::lock_guard<std::mutex> lock_guard(filter_parameters_mutex_); filter_parameters = filter_parameters_; filter_parameters_.parameters_are_dirty = false; filter_parameters_.input_rate_changed = false; } if(filter_parameters.parameters_are_dirty) update_filter_coefficients(filter_parameters); if(filter_parameters.input_rate_changed) { delegate_->speaker_did_change_input_clock(this); } // If input and output rates exactly match, and no additional cut-off has been specified, // just accumulate results and pass on. if( filter_parameters.input_cycles_per_second == filter_parameters.output_cycles_per_second && filter_parameters.high_frequency_cutoff < 0.0) { while(cycles_remaining) { std::size_t cycles_to_read = std::min(output_buffer_.size() - output_buffer_pointer_, cycles_remaining); sample_source_.get_samples(cycles_to_read, &output_buffer_[output_buffer_pointer_]); output_buffer_pointer_ += cycles_to_read; // announce to delegate if full if(output_buffer_pointer_ == output_buffer_.size()) { output_buffer_pointer_ = 0; delegate_->speaker_did_complete_samples(this, output_buffer_); } cycles_remaining -= cycles_to_read; } return; } // if the output rate is less than the input rate, or an additional cut-off has been specified, use the filter. if( filter_parameters.input_cycles_per_second > filter_parameters.output_cycles_per_second || (filter_parameters.input_cycles_per_second == filter_parameters.output_cycles_per_second && filter_parameters.high_frequency_cutoff >= 0.0)) { while(cycles_remaining) { std::size_t cycles_to_read = std::min(cycles_remaining, input_buffer_.size() - input_buffer_depth_); sample_source_.get_samples(cycles_to_read, &input_buffer_[input_buffer_depth_]); cycles_remaining -= cycles_to_read; input_buffer_depth_ += cycles_to_read; if(input_buffer_depth_ == input_buffer_.size()) { output_buffer_[output_buffer_pointer_] = filter_->apply(input_buffer_.data()); output_buffer_pointer_++; // Announce to delegate if full. if(output_buffer_pointer_ == output_buffer_.size()) { output_buffer_pointer_ = 0; delegate_->speaker_did_complete_samples(this, output_buffer_); } // If the next loop around is going to reuse some of the samples just collected, use a memmove to // preserve them in the correct locations (TODO: use a longer buffer to fix that) and don't skip // anything. Otherwise skip as required to get to the next sample batch and don't expect to reuse. uint64_t steps = stepper_->step(); if(steps < input_buffer_.size()) { int16_t *input_buffer = input_buffer_.data(); std::memmove( input_buffer, &input_buffer[steps], sizeof(int16_t) * (input_buffer_.size() - steps)); input_buffer_depth_ -= steps; } else { if(steps > input_buffer_.size()) sample_source_.skip_samples(steps - input_buffer_.size()); input_buffer_depth_ = 0; } } } return; } // TODO: input rate is less than output rate } T &sample_source_; std::size_t output_buffer_pointer_ = 0; std::size_t input_buffer_depth_ = 0; std::vector<int16_t> input_buffer_; std::vector<int16_t> output_buffer_; std::unique_ptr<SignalProcessing::Stepper> stepper_; std::unique_ptr<SignalProcessing::FIRFilter> filter_; std::mutex filter_parameters_mutex_; struct FilterParameters { float input_cycles_per_second = 0.0f; float output_cycles_per_second = 0.0f; float high_frequency_cutoff = -1.0; bool parameters_are_dirty = true; bool input_rate_changed = false; } filter_parameters_; void update_filter_coefficients(const FilterParameters &filter_parameters) { float high_pass_frequency = filter_parameters.output_cycles_per_second / 2.0f; if(filter_parameters.high_frequency_cutoff > 0.0) { high_pass_frequency = std::min(filter_parameters.high_frequency_cutoff, high_pass_frequency); } // Make a guess at a good number of taps. std::size_t number_of_taps = static_cast<std::size_t>( ceilf((filter_parameters.input_cycles_per_second + high_pass_frequency) / high_pass_frequency) ); number_of_taps = (number_of_taps * 2) | 1; output_buffer_pointer_ = 0; stepper_.reset(new SignalProcessing::Stepper( static_cast<uint64_t>(filter_parameters.input_cycles_per_second), static_cast<uint64_t>(filter_parameters.output_cycles_per_second))); filter_.reset(new SignalProcessing::FIRFilter( static_cast<unsigned int>(number_of_taps), filter_parameters.input_cycles_per_second, 0.0, high_pass_frequency, SignalProcessing::FIRFilter::DefaultAttenuation)); input_buffer_.resize(static_cast<std::size_t>(number_of_taps)); input_buffer_depth_ = 0; } }; } } #endif /* FilteringSpeaker_h */ <commit_msg>Adds `cmath` in support of `ceilf`.<commit_after>// // FilteringSpeaker.h // Clock Signal // // Created by Thomas Harte on 15/12/2017. // Copyright 2017 Thomas Harte. All rights reserved. // #ifndef FilteringSpeaker_h #define FilteringSpeaker_h #include "../Speaker.hpp" #include "../../../SignalProcessing/Stepper.hpp" #include "../../../SignalProcessing/FIRFilter.hpp" #include "../../../ClockReceiver/ClockReceiver.hpp" #include "../../../Concurrency/AsyncTaskQueue.hpp" #include <mutex> #include <cstring> #include <cmath> namespace Outputs { namespace Speaker { /*! The low-pass speaker expects an Outputs::Speaker::SampleSource-derived template class, and uses the instance supplied to its constructor as the source of a high-frequency stream of audio which it filters down to a lower-frequency output. */ template <typename T> class LowpassSpeaker: public Speaker { public: LowpassSpeaker(T &sample_source) : sample_source_(sample_source) { sample_source.set_sample_volume_range(32767); } // Implemented as per Speaker. float get_ideal_clock_rate_in_range(float minimum, float maximum) { std::lock_guard<std::mutex> lock_guard(filter_parameters_mutex_); // return twice the cut off, if applicable if( filter_parameters_.high_frequency_cutoff > 0.0f && filter_parameters_.input_cycles_per_second >= filter_parameters_.high_frequency_cutoff * 3.0f && filter_parameters_.input_cycles_per_second <= filter_parameters_.high_frequency_cutoff * 3.0f) return filter_parameters_.high_frequency_cutoff * 3.0f; // return exactly the input rate if possible if( filter_parameters_.input_cycles_per_second >= minimum && filter_parameters_.input_cycles_per_second <= maximum) return filter_parameters_.input_cycles_per_second; // if the input rate is lower, return the minimum if(filter_parameters_.input_cycles_per_second < minimum) return minimum; // otherwise, return the maximum return maximum; } // Implemented as per Speaker. void set_output_rate(float cycles_per_second, int buffer_size) { std::lock_guard<std::mutex> lock_guard(filter_parameters_mutex_); filter_parameters_.output_cycles_per_second = cycles_per_second; filter_parameters_.parameters_are_dirty = true; output_buffer_.resize(static_cast<std::size_t>(buffer_size)); } /*! Sets the clock rate of the input audio. */ void set_input_rate(float cycles_per_second) { std::lock_guard<std::mutex> lock_guard(filter_parameters_mutex_); filter_parameters_.input_cycles_per_second = cycles_per_second; filter_parameters_.parameters_are_dirty = true; filter_parameters_.input_rate_changed = true; } /*! Allows a cut-off frequency to be specified for audio. Ordinarily this low-pass speaker will determine a cut-off based on the output audio rate. A caller can manually select an alternative cut-off. This allows machines with a low-pass filter on their audio output path to be explicit about its effect, and get that simulation for free. */ void set_high_frequency_cutoff(float high_frequency) { std::lock_guard<std::mutex> lock_guard(filter_parameters_mutex_); filter_parameters_.high_frequency_cutoff = high_frequency; filter_parameters_.parameters_are_dirty = true; } /*! Schedules an advancement by the number of cycles specified on the provided queue. The speaker will advance by obtaining data from the sample source supplied at construction, filtering it and passing it on to the speaker's delegate if there is one. */ void run_for(Concurrency::DeferringAsyncTaskQueue &queue, const Cycles cycles) { queue.defer([this, cycles] { run_for(cycles); }); } private: /*! Advances by the number of cycles specified, obtaining data from the sample source supplied at construction, filtering it and passing it on to the speaker's delegate if there is one. */ void run_for(const Cycles cycles) { if(!delegate_) return; std::size_t cycles_remaining = static_cast<size_t>(cycles.as_int()); if(!cycles_remaining) return; FilterParameters filter_parameters; { std::lock_guard<std::mutex> lock_guard(filter_parameters_mutex_); filter_parameters = filter_parameters_; filter_parameters_.parameters_are_dirty = false; filter_parameters_.input_rate_changed = false; } if(filter_parameters.parameters_are_dirty) update_filter_coefficients(filter_parameters); if(filter_parameters.input_rate_changed) { delegate_->speaker_did_change_input_clock(this); } // If input and output rates exactly match, and no additional cut-off has been specified, // just accumulate results and pass on. if( filter_parameters.input_cycles_per_second == filter_parameters.output_cycles_per_second && filter_parameters.high_frequency_cutoff < 0.0) { while(cycles_remaining) { std::size_t cycles_to_read = std::min(output_buffer_.size() - output_buffer_pointer_, cycles_remaining); sample_source_.get_samples(cycles_to_read, &output_buffer_[output_buffer_pointer_]); output_buffer_pointer_ += cycles_to_read; // announce to delegate if full if(output_buffer_pointer_ == output_buffer_.size()) { output_buffer_pointer_ = 0; delegate_->speaker_did_complete_samples(this, output_buffer_); } cycles_remaining -= cycles_to_read; } return; } // if the output rate is less than the input rate, or an additional cut-off has been specified, use the filter. if( filter_parameters.input_cycles_per_second > filter_parameters.output_cycles_per_second || (filter_parameters.input_cycles_per_second == filter_parameters.output_cycles_per_second && filter_parameters.high_frequency_cutoff >= 0.0)) { while(cycles_remaining) { std::size_t cycles_to_read = std::min(cycles_remaining, input_buffer_.size() - input_buffer_depth_); sample_source_.get_samples(cycles_to_read, &input_buffer_[input_buffer_depth_]); cycles_remaining -= cycles_to_read; input_buffer_depth_ += cycles_to_read; if(input_buffer_depth_ == input_buffer_.size()) { output_buffer_[output_buffer_pointer_] = filter_->apply(input_buffer_.data()); output_buffer_pointer_++; // Announce to delegate if full. if(output_buffer_pointer_ == output_buffer_.size()) { output_buffer_pointer_ = 0; delegate_->speaker_did_complete_samples(this, output_buffer_); } // If the next loop around is going to reuse some of the samples just collected, use a memmove to // preserve them in the correct locations (TODO: use a longer buffer to fix that) and don't skip // anything. Otherwise skip as required to get to the next sample batch and don't expect to reuse. uint64_t steps = stepper_->step(); if(steps < input_buffer_.size()) { int16_t *input_buffer = input_buffer_.data(); std::memmove( input_buffer, &input_buffer[steps], sizeof(int16_t) * (input_buffer_.size() - steps)); input_buffer_depth_ -= steps; } else { if(steps > input_buffer_.size()) sample_source_.skip_samples(steps - input_buffer_.size()); input_buffer_depth_ = 0; } } } return; } // TODO: input rate is less than output rate } T &sample_source_; std::size_t output_buffer_pointer_ = 0; std::size_t input_buffer_depth_ = 0; std::vector<int16_t> input_buffer_; std::vector<int16_t> output_buffer_; std::unique_ptr<SignalProcessing::Stepper> stepper_; std::unique_ptr<SignalProcessing::FIRFilter> filter_; std::mutex filter_parameters_mutex_; struct FilterParameters { float input_cycles_per_second = 0.0f; float output_cycles_per_second = 0.0f; float high_frequency_cutoff = -1.0; bool parameters_are_dirty = true; bool input_rate_changed = false; } filter_parameters_; void update_filter_coefficients(const FilterParameters &filter_parameters) { float high_pass_frequency = filter_parameters.output_cycles_per_second / 2.0f; if(filter_parameters.high_frequency_cutoff > 0.0) { high_pass_frequency = std::min(filter_parameters.high_frequency_cutoff, high_pass_frequency); } // Make a guess at a good number of taps. std::size_t number_of_taps = static_cast<std::size_t>( ceilf((filter_parameters.input_cycles_per_second + high_pass_frequency) / high_pass_frequency) ); number_of_taps = (number_of_taps * 2) | 1; output_buffer_pointer_ = 0; stepper_.reset(new SignalProcessing::Stepper( static_cast<uint64_t>(filter_parameters.input_cycles_per_second), static_cast<uint64_t>(filter_parameters.output_cycles_per_second))); filter_.reset(new SignalProcessing::FIRFilter( static_cast<unsigned int>(number_of_taps), filter_parameters.input_cycles_per_second, 0.0, high_pass_frequency, SignalProcessing::FIRFilter::DefaultAttenuation)); input_buffer_.resize(static_cast<std::size_t>(number_of_taps)); input_buffer_depth_ = 0; } }; } } #endif /* FilteringSpeaker_h */ <|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ //______________________________________________________________________________ // Analysis task for high pt particle correlations // author: R.Diaz, J. Rak, D.J. Kim // ALICE Group University of Jyvaskyla // Finland // Fill the analysis containers for ESD or AOD // Adapted for AliAnalysisTaskSE and AOD objects ////////////////////////////////////////////////////////////////////////////// #include "TChain.h" //#include "TList.h" //#include "TTree.h" #include "TFile.h" #include "AliAnalysisUtils.h" #include "AliAnalysisTaskSE.h" #include "AliAODHandler.h" #include "AliAODMCParticle.h" #include "AliJFFlucTask.h" #include "AliAnalysisManager.h" #include "AliVEvent.h" #include "AliAODEvent.h" #include "AliJTrack.h" #include "AliJMCTrack.h" //#include "AliJPhoton.h" #include "AliJEventHeader.h" #include "AliJHistManager.h" #include "AliInputEventHandler.h" //______________________________________________________________________________ AliJFFlucTask::AliJFFlucTask(): fInputList(0), AliAnalysisTaskSE(), fFFlucAna(0x0), fOutput() { fEvtNum=0; fFilterBit = 0; fEta_min = 0; fEta_max = 0; // DefineOutput(1, TDirectory::Class()); } //______________________________________________________________________________ AliJFFlucTask::AliJFFlucTask(const char *name, int CollisionCandidates, Bool_t IsMC): fInputList(0), AliAnalysisTaskSE(name), fFFlucAna(0x0), fOutput() { DefineOutput(1, TDirectory::Class()); fEvtNum=0; fFilterBit = 0; fEta_min = 0; fEta_max = 0; fTaskName = name; } //____________________________________________________________________________ AliJFFlucTask::AliJFFlucTask(const AliJFFlucTask& ap) : fInputList(ap.fInputList), AliAnalysisTaskSE(ap.GetName()), fFFlucAna(ap.fFFlucAna), fOutput(ap.fOutput) { AliInfo("----DEBUG AliJFFlucTask COPY ----"); } //_____________________________________________________________________________ AliJFFlucTask& AliJFFlucTask::operator = (const AliJFFlucTask& ap) { // assignment operator AliInfo("----DEBUG AliJFFlucTask operator= ----"); this->~AliJFFlucTask(); new(this) AliJFFlucTask(ap); return *this; } //______________________________________________________________________________ AliJFFlucTask::~AliJFFlucTask() { // destructor delete fFFlucAna; delete fInputList; delete fOutput; } //________________________________________________________________________ void AliJFFlucTask::UserCreateOutputObjects() { fFFlucAna = new AliJFFlucAnalysis( fTaskName ); fFFlucAna->SetDebugLevel(fDebugLevel); //=== create the jcorran outputs objects //=== Get AnalysisManager /* AliAnalysisManager *man = AliAnalysisManager::GetAnalysisManager(); if(!man->GetOutputEventHandler()) { Fatal("UserCreateOutputObjects", "This task needs an AOD handler"); return; } */ fInputList = new TClonesArray("AliJBaseTrack" , 2500); fInputList->SetOwner(kTRUE); OpenFile(1); fOutput = gDirectory; fOutput->cd(); fFFlucAna->UserCreateOutputObjects(); PostData(1, fOutput); } //______________________________________________________________________________ void AliJFFlucTask::UserExec(Option_t* /*option*/) { // Processing of one event if(!((Entry()-1)%100)) AliInfo(Form(" Processing event # %lld", Entry())); // initiaizing variables from last event fInputList->Clear(); float fCent = -999; fEvtNum++; // load current event and save track, event info AliAODEvent *currentEvent = dynamic_cast<AliAODEvent*>(InputEvent()); ReadAODTracks( currentEvent, fInputList ) ; // read tracklist fCent = ReadAODCentrality( currentEvent, "V0M" ) ; // Int_t Ntracks = fInputList->GetEntriesFast(); // Analysis Part fFFlucAna->Init(); fFFlucAna->SetInputList( fInputList ); fFFlucAna->SetEventCentrality( fCent ); fFFlucAna->SetEtaRange( fEta_min, fEta_max ) ; fFFlucAna->UserExec(""); // doing some analysis here. // } //______________________________________________________________________________ float AliJFFlucTask::ReadAODCentrality( AliAODEvent *aod, TString Trig ) { AliCentrality *cent = aod->GetCentrality(); if(!cent){ Printf("No Cent event"); return -999; }; return cent->GetCentralityPercentile(Trig.Data()); } //______________________________________________________________________________ void AliJFFlucTask::Init() { // initiationg all parameters and variables // Intialisation of parameters AliInfo("Doing initialization") ; // } //______________________________________________________________________________ void AliJFFlucTask::ReadAODTracks( AliAODEvent *aod , TClonesArray *TrackList) { //aod->Print(); if( IsMC == kTRUE ){ // how to get a flag to check MC or not ! TClonesArray *mcArray = (TClonesArray*) aod->FindListObject(AliAODMCParticle::StdBranchName()); if(!mcArray){ Printf("Error not a proper MC event"); }; // check mc array Int_t nt = mcArray->GetEntriesFast(); Int_t ntrack =0; for( int it=0; it< nt ; it++){ AliAODMCParticle *track = (AliAODMCParticle*)mcArray->At(it); if(!track) { Error("ReadEventAODMC", "Could not receive particle %d",(int) it); continue; }; if( track->IsPhysicalPrimary() ){ // insert eta cut here // double track_abs_eta = TMath::Abs( track->Eta() ); //if( track_abs_eta > fEta_min && track_abs_eta < fEta_max){ // eta cut //if( track->Pt() < 0.2 || track->Pt() > 5 ) continue ; // test pt cut Int_t pdg = track->GetPdgCode(); Char_t ch = (Char_t) track->Charge(); Int_t label = track->GetLabel(); AliJBaseTrack *itrack = new ((*TrackList)[ntrack++])AliJBaseTrack; itrack->SetLabel( label ); itrack->SetParticleType( pdg); itrack->SetPxPyPzE( track->Px(), track->Py(), track->Pz(), track->E() ); itrack->SetCharge(ch) ; //}; no eta cut in task file } } } // read mc track done. else if( IsMC == kFALSE){ Int_t nt = aod->GetNumberOfTracks(); Int_t ntrack =0; for( int it=0; it<nt ; it++){ AliAODTrack *track = dynamic_cast<AliAODTrack*>(aod->GetTrack(it)); if(!track) { Error("ReadEventAOD", "Could not receive partice %d", (int) it); continue; }; if(track->TestFilterBit( fFilterBit )){ // hybrid cut // double track_abs_eta = TMath::Abs( track->Eta() ); // if( track_abs_eta > fEta_min && track_abs_eta < fEta_max){ // eta cut AliJBaseTrack *itrack = new( (*TrackList)[ntrack++])AliJBaseTrack; //itrack->SetID( track->GetID() ); itrack->SetID( TrackList->GetEntriesFast() ) ; itrack->SetPxPyPzE( track->Px(), track->Py(), track->Pz(), track->E() ); itrack->SetParticleType(kJHadron); itrack->SetCharge(track->Charge() ); itrack->SetStatus(track->GetStatus() ); // } no eta cut in task file } } } //read aod reco track done. } //______________________________________________________________________________ Bool_t AliJFFlucTask::IsGoodEvent( AliAODEvent *event){ Bool_t Trigger_kCentral = kFALSE; // init Trigger_kCentral =(((AliInputEventHandler*)(AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler())) ->IsEventSelected() & AliVEvent::kCentral); return Trigger_kCentral; } // //______________________________________________________________________________ void AliJFFlucTask::Terminate(Option_t *) { // fFFlucAna->Terminate(""); // Processing when the event loop is ended cout<<"AliJFFlucTask Analysis DONE !!"<<endl; } <commit_msg>Adding zvertex cut:DongJo<commit_after>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ //______________________________________________________________________________ // Analysis task for high pt particle correlations // author: R.Diaz, J. Rak, D.J. Kim // ALICE Group University of Jyvaskyla // Finland // Fill the analysis containers for ESD or AOD // Adapted for AliAnalysisTaskSE and AOD objects ////////////////////////////////////////////////////////////////////////////// #include "TChain.h" //#include "TList.h" //#include "TTree.h" #include "TFile.h" #include "AliAnalysisUtils.h" #include "AliAnalysisTaskSE.h" #include "AliAODHandler.h" #include "AliAODMCParticle.h" #include "AliJFFlucTask.h" #include "AliAnalysisManager.h" #include "AliVEvent.h" #include "AliAODEvent.h" #include "AliJTrack.h" #include "AliJMCTrack.h" //#include "AliJPhoton.h" #include "AliJEventHeader.h" #include "AliJHistManager.h" #include "AliInputEventHandler.h" //______________________________________________________________________________ AliJFFlucTask::AliJFFlucTask(): fInputList(0), AliAnalysisTaskSE(), fFFlucAna(0x0), fOutput() { fEvtNum=0; fFilterBit = 0; fEta_min = 0; fEta_max = 0; // DefineOutput(1, TDirectory::Class()); } //______________________________________________________________________________ AliJFFlucTask::AliJFFlucTask(const char *name, int CollisionCandidates, Bool_t IsMC): fInputList(0), AliAnalysisTaskSE(name), fFFlucAna(0x0), fOutput() { DefineOutput(1, TDirectory::Class()); fEvtNum=0; fFilterBit = 0; fEta_min = 0; fEta_max = 0; fTaskName = name; } //____________________________________________________________________________ AliJFFlucTask::AliJFFlucTask(const AliJFFlucTask& ap) : fInputList(ap.fInputList), AliAnalysisTaskSE(ap.GetName()), fFFlucAna(ap.fFFlucAna), fOutput(ap.fOutput) { AliInfo("----DEBUG AliJFFlucTask COPY ----"); } //_____________________________________________________________________________ AliJFFlucTask& AliJFFlucTask::operator = (const AliJFFlucTask& ap) { // assignment operator AliInfo("----DEBUG AliJFFlucTask operator= ----"); this->~AliJFFlucTask(); new(this) AliJFFlucTask(ap); return *this; } //______________________________________________________________________________ AliJFFlucTask::~AliJFFlucTask() { // destructor delete fFFlucAna; delete fInputList; delete fOutput; } //________________________________________________________________________ void AliJFFlucTask::UserCreateOutputObjects() { fFFlucAna = new AliJFFlucAnalysis( fTaskName ); fFFlucAna->SetDebugLevel(fDebugLevel); //=== create the jcorran outputs objects //=== Get AnalysisManager /* AliAnalysisManager *man = AliAnalysisManager::GetAnalysisManager(); if(!man->GetOutputEventHandler()) { Fatal("UserCreateOutputObjects", "This task needs an AOD handler"); return; } */ fInputList = new TClonesArray("AliJBaseTrack" , 2500); fInputList->SetOwner(kTRUE); OpenFile(1); fOutput = gDirectory; fOutput->cd(); fFFlucAna->UserCreateOutputObjects(); PostData(1, fOutput); } //______________________________________________________________________________ void AliJFFlucTask::UserExec(Option_t* /*option*/) { // Processing of one event if(!((Entry()-1)%100)) AliInfo(Form(" Processing event # %lld", Entry())); // initiaizing variables from last event fInputList->Clear(); float fCent = -999; fEvtNum++; // load current event and save track, event info AliAODEvent *currentEvent = dynamic_cast<AliAODEvent*>(InputEvent()); if(!IsGoodEvent( currentEvent )) return; // zBin is set there ReadAODTracks( currentEvent, fInputList ) ; // read tracklist fCent = ReadAODCentrality( currentEvent, "V0M" ) ; // Int_t Ntracks = fInputList->GetEntriesFast(); // Analysis Part fFFlucAna->Init(); fFFlucAna->SetInputList( fInputList ); fFFlucAna->SetEventCentrality( fCent ); fFFlucAna->SetEtaRange( fEta_min, fEta_max ) ; fFFlucAna->UserExec(""); // doing some analysis here. // } //______________________________________________________________________________ float AliJFFlucTask::ReadAODCentrality( AliAODEvent *aod, TString Trig ) { AliCentrality *cent = aod->GetCentrality(); if(!cent){ Printf("No Cent event"); return -999; }; return cent->GetCentralityPercentile(Trig.Data()); } //______________________________________________________________________________ void AliJFFlucTask::Init() { // initiationg all parameters and variables // Intialisation of parameters AliInfo("Doing initialization") ; // } //______________________________________________________________________________ void AliJFFlucTask::ReadAODTracks( AliAODEvent *aod , TClonesArray *TrackList) { //aod->Print(); if( IsMC == kTRUE ){ // how to get a flag to check MC or not ! TClonesArray *mcArray = (TClonesArray*) aod->FindListObject(AliAODMCParticle::StdBranchName()); if(!mcArray){ Printf("Error not a proper MC event"); }; // check mc array Int_t nt = mcArray->GetEntriesFast(); Int_t ntrack =0; for( int it=0; it< nt ; it++){ AliAODMCParticle *track = (AliAODMCParticle*)mcArray->At(it); if(!track) { Error("ReadEventAODMC", "Could not receive particle %d",(int) it); continue; }; if( track->IsPhysicalPrimary() ){ // insert eta cut here // double track_abs_eta = TMath::Abs( track->Eta() ); //if( track_abs_eta > fEta_min && track_abs_eta < fEta_max){ // eta cut //if( track->Pt() < 0.2 || track->Pt() > 5 ) continue ; // test pt cut Int_t pdg = track->GetPdgCode(); Char_t ch = (Char_t) track->Charge(); Int_t label = track->GetLabel(); AliJBaseTrack *itrack = new ((*TrackList)[ntrack++])AliJBaseTrack; itrack->SetLabel( label ); itrack->SetParticleType( pdg); itrack->SetPxPyPzE( track->Px(), track->Py(), track->Pz(), track->E() ); itrack->SetCharge(ch) ; //}; no eta cut in task file } } } // read mc track done. else if( IsMC == kFALSE){ Int_t nt = aod->GetNumberOfTracks(); Int_t ntrack =0; for( int it=0; it<nt ; it++){ AliAODTrack *track = dynamic_cast<AliAODTrack*>(aod->GetTrack(it)); if(!track) { Error("ReadEventAOD", "Could not receive partice %d", (int) it); continue; }; if(track->TestFilterBit( fFilterBit )){ // hybrid cut // double track_abs_eta = TMath::Abs( track->Eta() ); // if( track_abs_eta > fEta_min && track_abs_eta < fEta_max){ // eta cut AliJBaseTrack *itrack = new( (*TrackList)[ntrack++])AliJBaseTrack; //itrack->SetID( track->GetID() ); itrack->SetID( TrackList->GetEntriesFast() ) ; itrack->SetPxPyPzE( track->Px(), track->Py(), track->Pz(), track->E() ); itrack->SetParticleType(kJHadron); itrack->SetCharge(track->Charge() ); itrack->SetStatus(track->GetStatus() ); // } no eta cut in task file } } } //read aod reco track done. } //______________________________________________________________________________ Bool_t AliJFFlucTask::IsGoodEvent( AliAODEvent *event){ // check reconstructed vertex int ncontributors = 0; Bool_t goodRecVertex = kFALSE; const AliVVertex *vtx = event->GetPrimaryVertex(); if(vtx){ ncontributors = vtx->GetNContributors(); if(ncontributors > 0){ double zVert = vtx->GetZ(); if(TMath::Abs(zVert)<10.0) { goodRecVertex = kTRUE; } } } return goodRecVertex; } // //______________________________________________________________________________ void AliJFFlucTask::Terminate(Option_t *) { // fFFlucAna->Terminate(""); // Processing when the event loop is ended cout<<"AliJFFlucTask Analysis DONE !!"<<endl; } <|endoftext|>
<commit_before>//---------------------------------------------------------------------------- /// \file typeinfo.hpp //---------------------------------------------------------------------------- /// \brief This file contains run-time type information inspection functions. //---------------------------------------------------------------------------- // Copyright (c) 2010 Serge Aleynikov <saleyn@gmail.com> // Created: 2010-09-30 //---------------------------------------------------------------------------- /* ***** BEGIN LICENSE BLOCK ***** This file is part of the utxx open-source project. Copyright (C) 2010 Serge Aleynikov <saleyn@gmail.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ***** END LICENSE BLOCK ***** */ #ifndef _UTXX_TYPE_INFO_HPP_ #define _UTXX_TYPE_INFO_HPP_ #include <typeinfo> #if defined(__linux__) #include <cxxabi.h> #endif namespace utxx { namespace detail { inline std::string demangle(const char* a_type_name) { #if defined(_WIN32) || defined(_WIN64) return a_type_name; #else char buf[256]; size_t sz = sizeof(buf); int error; // See http://www.codesourcery.com/public/cxx-abi/abi.html#demangler abi::__cxa_demangle(a_type_name, buf, &sz /*can be NULL*/, &error /*can be NULL*/); return error < 0 ? "***undefined***" : buf; #endif } } // namespace detail /// Return demangled name of a given C++ type. template <typename T> std::string type_to_string() { return detail::demangle(typeid(T).name()); } template <typename T> std::string type_to_string(const T& t) { return detail::demangle(typeid(t).name()); } /// Return demangled name of a given C++ type. template <typename T> std::string type_to_string(T&& t) { return detail::demangle(typeid(t).name()); } /// This function demangles a single C++ type name contained /// in a given string. inline std::string demangle(const char* a_str) { char temp[256]; //first, try to find a dmangled c++ name if (sscanf(a_str, "%*[^(]%*[^_]%255[^)+]", temp) == 1) { return detail::demangle(temp); } //if that didn't work, try to get a regular c symbol if (sscanf(a_str, "%255s", temp) == 1) { return temp; } //if all else fails, just return the symbol return a_str; } } // namespace utxx #endif // _UTXX_TYPE_INFO_HPP_ <commit_msg>Fix test case compilation error<commit_after>//---------------------------------------------------------------------------- /// \file typeinfo.hpp //---------------------------------------------------------------------------- /// \brief This file contains run-time type information inspection functions. //---------------------------------------------------------------------------- // Copyright (c) 2010 Serge Aleynikov <saleyn@gmail.com> // Created: 2010-09-30 //---------------------------------------------------------------------------- /* ***** BEGIN LICENSE BLOCK ***** This file is part of the utxx open-source project. Copyright (C) 2010 Serge Aleynikov <saleyn@gmail.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ***** END LICENSE BLOCK ***** */ #ifndef _UTXX_TYPE_INFO_HPP_ #define _UTXX_TYPE_INFO_HPP_ #include <string> #include <typeinfo> #if defined(__linux__) #include <cxxabi.h> #endif namespace utxx { namespace detail { inline std::string demangle(const char* a_type_name) { #if defined(_WIN32) || defined(_WIN64) return a_type_name; #else char buf[256]; size_t sz = sizeof(buf); int error; // See http://www.codesourcery.com/public/cxx-abi/abi.html#demangler abi::__cxa_demangle(a_type_name, buf, &sz /*can be NULL*/, &error /*can be NULL*/); return error < 0 ? "***undefined***" : buf; #endif } } // namespace detail /// Return demangled name of a given C++ type. template <typename T> std::string type_to_string() { return detail::demangle(typeid(T).name()); } template <typename T> std::string type_to_string(const T& t) { return detail::demangle(typeid(t).name()); } /// Return demangled name of a given C++ type. template <typename T> std::string type_to_string(T&& t) { return detail::demangle(typeid(t).name()); } /// This function demangles a single C++ type name contained /// in a given string. inline std::string demangle(const char* a_str) { char temp[256]; //first, try to find a dmangled c++ name if (sscanf(a_str, "%*[^(]%*[^_]%255[^)+]", temp) == 1) { return detail::demangle(temp); } //if that didn't work, try to get a regular c symbol if (sscanf(a_str, "%255s", temp) == 1) { return temp; } //if all else fails, just return the symbol return a_str; } } // namespace utxx #endif // _UTXX_TYPE_INFO_HPP_ <|endoftext|>
<commit_before>#include "gridmap.hpp" #include "gui.hpp" #include "oddlib/lvlarchive.hpp" #include "renderer.hpp" #include "oddlib/path.hpp" #include "oddlib/bits_factory.hpp" #include "logger.hpp" #include <cassert> #include "sdl_raii.hpp" #include <algorithm> // min/max #include <cmath> Level::Level(GameData& gameData, IAudioController& /*audioController*/, FileSystem& fs) : mGameData(gameData), mFs(fs) { } void Level::Update() { if (mMap) { mMap->Update(); } } void Level::Render(Renderer& rend, GuiContext& gui, int screenW, int screenH) { RenderDebugPathSelection(rend, gui); if (mMap) { mMap->Render(rend, gui, screenW, screenH); } } void Level::RenderDebugPathSelection(Renderer& rend, GuiContext& gui) { gui.next_window_pos = v2i(10, 300); gui_begin_window(&gui, "Paths", v2i(150, 400)); static std::vector<std::pair<std::string, const GameData::PathEntry*>> items; if (items.empty()) { for (const auto& pathGroup : mGameData.Paths()) { for (const auto& path : pathGroup.second) { items.push_back(std::make_pair(pathGroup.first + " " + std::to_string(path.mPathChunkId), &path)); } } } for (const auto& item : items) { if (gui_button(&gui, item.first.c_str())) { const GameData::PathEntry* entry = item.second; const std::string baseLvlNameUpper = item.first.substr(0, 2); // R1, MI etc std::string baseLvlNameLower = baseLvlNameUpper; // Open the LVL std::transform(baseLvlNameLower.begin(), baseLvlNameLower.end(), baseLvlNameLower.begin(), string_util::c_tolower); const std::string lvlName = baseLvlNameLower + ".lvl"; LOG_INFO("Looking for LVL " << lvlName); auto chunkStream = mFs.ResourcePaths().OpenLvlFileChunkById(lvlName, baseLvlNameUpper + "PATH.BND", entry->mPathChunkId); if (chunkStream) { Oddlib::Path path(*chunkStream, entry->mNumberOfCollisionItems, entry->mObjectIndexTableOffset, entry->mObjectDataOffset, entry->mMapXSize, entry->mMapYSize); mMap = std::make_unique<GridMap>(lvlName, path, mFs, rend); } else { LOG_ERROR("LVL or file in LVL not found"); } } } gui_end_window(&gui); } GridScreen::GridScreen(const std::string& lvlName, const std::string& fileName, Renderer& rend) : mLvlName(lvlName), mFileName(fileName) , mTexHandle(0) , mRend(rend) { } GridScreen::~GridScreen() { mRend.destroyTexture(mTexHandle); } int GridScreen::getTexHandle(FileSystem& fs) { if (!mTexHandle) { auto stream = fs.ResourcePaths().OpenLvlFileChunkByType(mLvlName, mFileName, Oddlib::MakeType('B', 'i', 't', 's')); if (stream) { auto bits = Oddlib::MakeBits(*stream); SDL_Surface* surf = bits->GetSurface(); SDL_SurfacePtr converted; if (surf->format->format != SDL_PIXELFORMAT_RGB24) { converted.reset(SDL_ConvertSurfaceFormat(surf, SDL_PIXELFORMAT_RGB24, 0)); surf = converted.get(); } #if 0 SDL_SurfacePtr scaled; { // Scale the surface assert(surf->w == 640); assert(surf->h == 240); scaled.reset(SDL_CreateRGBSurface(0, 640, 480, 24, 0xFF, 0x00FF, 0x0000FF, 0)); uint8_t *src = static_cast<uint8_t*>(surf->pixels); uint8_t *dst = static_cast<uint8_t*>(scaled->pixels); for (int y = 0; y < scaled->h; ++y) { const int src_y = min(y, surf->h); for (int x = 0; x < scaled->w; ++x) { const int src_x = min(x, surf->w); const int dst_ix = x*3 + scaled->pitch*y; const int src_ix = src_x*3 + surf->pitch*src_y; dst[dst_ix + 0] = src[src_ix + 0]; dst[dst_ix + 1] = src[src_ix + 1]; dst[dst_ix + 2] = src[src_ix + 2]; } } } mTexHandle = mRend.createTexture(GL_RGB, scaled->w, scaled->h, GL_RGB, GL_UNSIGNED_BYTE, scaled->pixels, false); #else mTexHandle = mRend.createTexture(GL_RGB, surf->w, surf->h, GL_RGB, GL_UNSIGNED_BYTE, surf->pixels, false); #endif } } return mTexHandle; } bool GridScreen::hasTexture() const { bool onlySpaces = true; for (size_t i = 0; i < mFileName.size(); ++i) { if (mFileName[i] != ' ' && mFileName[i] != '\0') { onlySpaces = false; break; } } return !onlySpaces; } GridMap::GridMap(const std::string& lvlName, Oddlib::Path& path, FileSystem& fs, Renderer& rend) : mFs(fs), mLvlName(lvlName) { mScreens.resize(path.XSize()); for (auto& col : mScreens) { col.resize(path.YSize()); } for (Uint32 x = 0; x < path.XSize(); x++) { for (Uint32 y = 0; y < path.YSize(); y++) { mScreens[x][y] = std::make_unique<GridScreen>(mLvlName, path.CameraFileName(x,y), rend); } } } void GridMap::Update() { } void GridMap::Render(Renderer& rend, GuiContext& gui, int screenW, int screenH) { #if 0 // List of cams gui.next_window_pos = v2i(950, 50); gui_begin_window(&gui, "GridMap", v2i(200, 500)); for (auto x = 0u; x < mScreens.size(); x++) { for (auto y = 0u; y < mScreens[0].size(); y++) { if (gui_button(&gui, gui_str(&gui, "cam_%i_%i|%s", (int)x, (int)y, mScreens[x][y]->FileName().c_str()))) { mEditorScreenX = (int)x; mEditorScreenY = (int)y; } } } gui_end_window(&gui); if (mEditorScreenX >= static_cast<int>(mScreens.size()) || // Invalid x check (mEditorScreenX >= 0 && mEditorScreenY >= static_cast<int>(mScreens[mEditorScreenX].size()))) // Invalid y check { mEditorScreenX = mEditorScreenY = -1; } if (mEditorScreenX >= 0 && mEditorScreenY >= 0) { GridScreen *screen = mScreens[mEditorScreenX][mEditorScreenY].get(); gui.next_window_pos = v2i(100, 100); V2i size = v2i(640, 480); gui_begin_window(&gui, "CAM", size); size = gui_window_client_size(&gui); rend.beginLayer(gui_layer(&gui)); V2i pos = gui_turtle_pos(&gui); rend.drawQuad(screen->getTexHandle(mFs), 1.0f*pos.x, 1.0f*pos.y, 1.0f*size.x, 1.0f*size.y); rend.endLayer(); gui_end_window(&gui); } #else // Proper editor gui gui_begin_frame(&gui, "camArea", v2i(0, 0), v2i(screenW, screenH)); rend.beginLayer(gui_layer(&gui)); bool zoomChanged = false; if (gui.key_state[GUI_KEY_LCTRL] & GUI_KEYSTATE_DOWN_BIT) { mZoomLevel += gui.mouse_scroll; zoomChanged = (gui.mouse_scroll != 0); } const float zoomBase = 1.2f; const float oldZoomMul = std::pow(zoomBase, 1.f*mZoomLevel - gui.mouse_scroll); const float zoomMul = std::pow(zoomBase, 1.f*mZoomLevel); // Use oldZoom because gui_set_frame_scroll below doesn't change scrolling in current frame. Could be changed though. const V2i camSize = v2i((int)(1440*oldZoomMul), (int)(1080*oldZoomMul)); // TODO: Native reso should be constant somewhere const int gap = (int)(20*oldZoomMul); const V2i margin = v2i((int)(2000*oldZoomMul), (int)(2000*oldZoomMul)); // Zoom around cursor if (zoomChanged) { V2f scaledCursorPos = v2i_to_v2f(gui.cursor_pos)*2 - v2f(screenW/2.f, screenH/2.f); V2f oldClientPos = v2i_to_v2f(gui_frame_scroll(&gui)) + scaledCursorPos; V2f worldPos = oldClientPos*(1.f/oldZoomMul); V2f newClientPos = worldPos*zoomMul; V2f newScreenPos = newClientPos - scaledCursorPos; gui_set_frame_scroll(&gui, v2f_to_v2i(newScreenPos)); } for (auto x = 0u; x < mScreens.size(); x++) { for (auto y = 0u; y < mScreens[x].size(); y++) { GridScreen *screen = mScreens[x][y].get(); if (!screen->hasTexture()) continue; V2i pos = gui_turtle_pos(&gui) + v2i((camSize.x + gap)*x, (camSize.y + gap)*y) + margin; rend.drawQuad(screen->getTexHandle(mFs), 1.0f*pos.x, 1.0f*pos.y, 1.0f*camSize.x, 1.0f*camSize.y); gui_enlarge_bounding(&gui, pos + camSize + margin*2); } } rend.endLayer(); gui_end_frame(&gui); #endif } <commit_msg>Changed zoom to not over-translate<commit_after>#include "gridmap.hpp" #include "gui.hpp" #include "oddlib/lvlarchive.hpp" #include "renderer.hpp" #include "oddlib/path.hpp" #include "oddlib/bits_factory.hpp" #include "logger.hpp" #include <cassert> #include "sdl_raii.hpp" #include <algorithm> // min/max #include <cmath> Level::Level(GameData& gameData, IAudioController& /*audioController*/, FileSystem& fs) : mGameData(gameData), mFs(fs) { } void Level::Update() { if (mMap) { mMap->Update(); } } void Level::Render(Renderer& rend, GuiContext& gui, int screenW, int screenH) { RenderDebugPathSelection(rend, gui); if (mMap) { mMap->Render(rend, gui, screenW, screenH); } } void Level::RenderDebugPathSelection(Renderer& rend, GuiContext& gui) { gui.next_window_pos = v2i(10, 300); gui_begin_window(&gui, "Paths", v2i(150, 400)); static std::vector<std::pair<std::string, const GameData::PathEntry*>> items; if (items.empty()) { for (const auto& pathGroup : mGameData.Paths()) { for (const auto& path : pathGroup.second) { items.push_back(std::make_pair(pathGroup.first + " " + std::to_string(path.mPathChunkId), &path)); } } } for (const auto& item : items) { if (gui_button(&gui, item.first.c_str())) { const GameData::PathEntry* entry = item.second; const std::string baseLvlNameUpper = item.first.substr(0, 2); // R1, MI etc std::string baseLvlNameLower = baseLvlNameUpper; // Open the LVL std::transform(baseLvlNameLower.begin(), baseLvlNameLower.end(), baseLvlNameLower.begin(), string_util::c_tolower); const std::string lvlName = baseLvlNameLower + ".lvl"; LOG_INFO("Looking for LVL " << lvlName); auto chunkStream = mFs.ResourcePaths().OpenLvlFileChunkById(lvlName, baseLvlNameUpper + "PATH.BND", entry->mPathChunkId); if (chunkStream) { Oddlib::Path path(*chunkStream, entry->mNumberOfCollisionItems, entry->mObjectIndexTableOffset, entry->mObjectDataOffset, entry->mMapXSize, entry->mMapYSize); mMap = std::make_unique<GridMap>(lvlName, path, mFs, rend); } else { LOG_ERROR("LVL or file in LVL not found"); } } } gui_end_window(&gui); } GridScreen::GridScreen(const std::string& lvlName, const std::string& fileName, Renderer& rend) : mLvlName(lvlName), mFileName(fileName) , mTexHandle(0) , mRend(rend) { } GridScreen::~GridScreen() { mRend.destroyTexture(mTexHandle); } int GridScreen::getTexHandle(FileSystem& fs) { if (!mTexHandle) { auto stream = fs.ResourcePaths().OpenLvlFileChunkByType(mLvlName, mFileName, Oddlib::MakeType('B', 'i', 't', 's')); if (stream) { auto bits = Oddlib::MakeBits(*stream); SDL_Surface* surf = bits->GetSurface(); SDL_SurfacePtr converted; if (surf->format->format != SDL_PIXELFORMAT_RGB24) { converted.reset(SDL_ConvertSurfaceFormat(surf, SDL_PIXELFORMAT_RGB24, 0)); surf = converted.get(); } #if 0 SDL_SurfacePtr scaled; { // Scale the surface assert(surf->w == 640); assert(surf->h == 240); scaled.reset(SDL_CreateRGBSurface(0, 640, 480, 24, 0xFF, 0x00FF, 0x0000FF, 0)); uint8_t *src = static_cast<uint8_t*>(surf->pixels); uint8_t *dst = static_cast<uint8_t*>(scaled->pixels); for (int y = 0; y < scaled->h; ++y) { const int src_y = min(y, surf->h); for (int x = 0; x < scaled->w; ++x) { const int src_x = min(x, surf->w); const int dst_ix = x*3 + scaled->pitch*y; const int src_ix = src_x*3 + surf->pitch*src_y; dst[dst_ix + 0] = src[src_ix + 0]; dst[dst_ix + 1] = src[src_ix + 1]; dst[dst_ix + 2] = src[src_ix + 2]; } } } mTexHandle = mRend.createTexture(GL_RGB, scaled->w, scaled->h, GL_RGB, GL_UNSIGNED_BYTE, scaled->pixels, false); #else mTexHandle = mRend.createTexture(GL_RGB, surf->w, surf->h, GL_RGB, GL_UNSIGNED_BYTE, surf->pixels, false); #endif } } return mTexHandle; } bool GridScreen::hasTexture() const { bool onlySpaces = true; for (size_t i = 0; i < mFileName.size(); ++i) { if (mFileName[i] != ' ' && mFileName[i] != '\0') { onlySpaces = false; break; } } return !onlySpaces; } GridMap::GridMap(const std::string& lvlName, Oddlib::Path& path, FileSystem& fs, Renderer& rend) : mFs(fs), mLvlName(lvlName) { mScreens.resize(path.XSize()); for (auto& col : mScreens) { col.resize(path.YSize()); } for (Uint32 x = 0; x < path.XSize(); x++) { for (Uint32 y = 0; y < path.YSize(); y++) { mScreens[x][y] = std::make_unique<GridScreen>(mLvlName, path.CameraFileName(x,y), rend); } } } void GridMap::Update() { } void GridMap::Render(Renderer& rend, GuiContext& gui, int screenW, int screenH) { #if 0 // List of cams gui.next_window_pos = v2i(950, 50); gui_begin_window(&gui, "GridMap", v2i(200, 500)); for (auto x = 0u; x < mScreens.size(); x++) { for (auto y = 0u; y < mScreens[0].size(); y++) { if (gui_button(&gui, gui_str(&gui, "cam_%i_%i|%s", (int)x, (int)y, mScreens[x][y]->FileName().c_str()))) { mEditorScreenX = (int)x; mEditorScreenY = (int)y; } } } gui_end_window(&gui); if (mEditorScreenX >= static_cast<int>(mScreens.size()) || // Invalid x check (mEditorScreenX >= 0 && mEditorScreenY >= static_cast<int>(mScreens[mEditorScreenX].size()))) // Invalid y check { mEditorScreenX = mEditorScreenY = -1; } if (mEditorScreenX >= 0 && mEditorScreenY >= 0) { GridScreen *screen = mScreens[mEditorScreenX][mEditorScreenY].get(); gui.next_window_pos = v2i(100, 100); V2i size = v2i(640, 480); gui_begin_window(&gui, "CAM", size); size = gui_window_client_size(&gui); rend.beginLayer(gui_layer(&gui)); V2i pos = gui_turtle_pos(&gui); rend.drawQuad(screen->getTexHandle(mFs), 1.0f*pos.x, 1.0f*pos.y, 1.0f*size.x, 1.0f*size.y); rend.endLayer(); gui_end_window(&gui); } #else // Proper editor gui gui_begin_frame(&gui, "camArea", v2i(0, 0), v2i(screenW, screenH)); rend.beginLayer(gui_layer(&gui)); bool zoomChanged = false; if (gui.key_state[GUI_KEY_LCTRL] & GUI_KEYSTATE_DOWN_BIT) { mZoomLevel += gui.mouse_scroll; zoomChanged = (gui.mouse_scroll != 0); } const float zoomBase = 1.2f; const float oldZoomMul = std::pow(zoomBase, 1.f*mZoomLevel - gui.mouse_scroll); const float zoomMul = std::pow(zoomBase, 1.f*mZoomLevel); // Use oldZoom because gui_set_frame_scroll below doesn't change scrolling in current frame. Could be changed though. const V2i camSize = v2i((int)(1440*oldZoomMul), (int)(1080*oldZoomMul)); // TODO: Native reso should be constant somewhere const int gap = (int)(20*oldZoomMul); const V2i margin = v2i((int)(2000*oldZoomMul), (int)(2000*oldZoomMul)); // Zoom around cursor if (zoomChanged) { V2f scaledCursorPos = v2i_to_v2f(gui.cursor_pos);// - v2f(screenW/2.f, screenH/2.f); V2f oldClientPos = v2i_to_v2f(gui_frame_scroll(&gui)) + scaledCursorPos; V2f worldPos = oldClientPos*(1.f/oldZoomMul); V2f newClientPos = worldPos*zoomMul; V2f newScreenPos = newClientPos - scaledCursorPos; gui_set_frame_scroll(&gui, v2f_to_v2i(newScreenPos)); } for (auto x = 0u; x < mScreens.size(); x++) { for (auto y = 0u; y < mScreens[x].size(); y++) { GridScreen *screen = mScreens[x][y].get(); if (!screen->hasTexture()) continue; V2i pos = gui_turtle_pos(&gui) + v2i((camSize.x + gap)*x, (camSize.y + gap)*y) + margin; rend.drawQuad(screen->getTexHandle(mFs), 1.0f*pos.x, 1.0f*pos.y, 1.0f*camSize.x, 1.0f*camSize.y); gui_enlarge_bounding(&gui, pos + camSize + margin*2); } } rend.endLayer(); gui_end_frame(&gui); #endif } <|endoftext|>
<commit_before>/* * * * * * * * * * * * *\ |* ╔═╗ v0.3 *| |* ╔═╦═╦═══╦═══╣ ╚═╦═╦═╗ *| |* ║ ╔═╣ '╔╬═╗╚╣ ║ ║ '║ *| |* ╚═╝ ╚═══╩═══╩═╩═╣ ╔═╝ *| |* * * * * * * * * ╚═╝ * *| |* Manipulation tool for *| |* ESRI Shapefiles *| |* * * * * * * * * * * * *| |* http://www.npolar.no/ *| \* * * * * * * * * * * * */ #include "handler.hpp" #include <cstdlib> #include <cstring> #include <cstdio> namespace reshp { bool handler::argcmp(const char* arg, const char* opt1, const char* opt2) { if(arg && opt1) { if(strcmp(arg, opt1) == 0) return true; if(opt2 && (strcmp(arg, opt2) == 0)) return true; } return false; } void handler::help(const char* topic) { if(!topic) { printf("Usage: %s [option]... [shapefile <parameter>...]\n", exe_name_.c_str()); printf("Command-line tool for manipulating ESRI Shapefiles.\n"); printf("\nAvailable options:\n"); printf(" -h, --help [topic] display help text (about specified topic) and exit\n"); printf(" --version output version information and exit\n"); printf(" -v, --verbose verbosely output performed manipulation operations\n"); printf("\nShapefile parameters:\n"); //printf(" -a, --add <type> <property>... add record with specified type and properties to shapefile\n"); printf(" -g, --grade grade the shapefile ranging from A (best) to F (worst)\n"); printf(" -l, --list list various information about the shapefile\n"); printf(" -L, --list-full list full information about the shapefile, including coordinates\n"); printf(" -o, --output <filename> output (save) modified shapefile to specified filename\n"); printf(" -s, --subtract <input> subtract input shapefile shapes from shapefile\n"); } /* else if(argcmp(topic, "add", "a")) { printf("%s <shapefile> --add <type> [property]...\n", exe_name_.c_str()); printf("Add record with specified type and properties to shapefile.\n"); printf("\nRecord types:\n"); printf(" null empty placeholder shape\n"); printf(" point <x> <y> single 2D point\n"); printf(" polyline <mbr> <parts> <points> polygonal path of 2D points\n"); printf(" polygon <mbr> <parts> <points> filled polygon of 2D points\n"); printf(" multipoint <mbr> <points> collection of 2D points\n"); printf("\nProperties:\n"); printf(" <measure> measure floating number\n"); printf(" <mbr> bounding box with space separated floating numbers: <xmin> <ymin> <xmax> <ymax>\n"); printf(" <parts> number of parts followed by space separated point indices representing each part\n"); printf(" <points> number of points followed by space separated point coordinates: <x> <y>\n"); printf(" <x> x coordinate as floating number\n"); printf(" <y> y coordinate as floating number\n"); printf(" <z> z coordinate as floating number\n"); } */ else if(argcmp(topic, "grade", "g")) { printf("%s --grade\n", exe_name_.c_str()); printf("Validate the shapefile, and output one of the following grades:\n"); printf(" A: Valid ESRI Shapefile, which completely complies with the specifications\n"); printf(" B: Valid ESRI Shapefile, with valid data and clean shapes according to the specifications\n"); printf(" C: Valid ESRI Shapefile, with valid data and no self-intersecting shapes\n"); printf(" D: Valid ESRI Shapefile, with no broken records or missing data\n"); printf(" E: Valid ESRI Shapefile, with broken records or missing data\n"); printf(" F: Not a valid ESRI Shapefile\n"); printf("\n"); printf(" If an output filename is specified, the grading will be performed on this file\n"); } else if(argcmp(topic, "list", "l")) { printf("%s <shapefile> --list\n", exe_name_.c_str()); printf("List various information about shapefile.\n"); } else if(argcmp(topic, "output", "o")) { printf("%s <shapefile> --output [filename]\n", exe_name_.c_str()); printf("Output changes made to the shapefile to specified filename.\n"); } else if(argcmp(topic, "subtract", "s")) { printf("%s <shapefile> --subtract <input>\n", exe_name_.c_str()); printf("Subtract input shapefile shapes from shapes in the shapefile.\n"); } else if(argcmp(topic, "verbose", "v")) { printf("%s --verbose [shapefile <parameter>...]\n", exe_name_.c_str()); printf("Enable verbose output of certain manipulation operations.\n"); } else { printf("Unrecognized help topic: %s\n", topic); printf("Try '%s --help' for more information\n", exe_name_.c_str()); } } handler::handler(int argc, char** argv, const char* version) : build_date_("0000-00-00"), exe_name_(argv[0]), verbose_(false), version_(version) { size_t separator = exe_name_.rfind('/'); std::string builddate(__DATE__); if(separator != std::string::npos) exe_name_.erase(0, separator + 1); build_date_.replace(0, 4, builddate.substr(7, 4)); build_date_.replace(8, 2, builddate.substr(4, 2)); if(build_date_[8] == ' ') build_date_[8] = '0'; if(builddate.substr(0, 3) == "Jan") build_date_.replace(5, 2, "01"); else if(builddate.substr(0, 3) == "Feb") build_date_.replace(5, 2, "02"); else if(builddate.substr(0, 3) == "Mar") build_date_.replace(5, 2, "03"); else if(builddate.substr(0, 3) == "Apr") build_date_.replace(5, 2, "04"); else if(builddate.substr(0, 3) == "May") build_date_.replace(5, 2, "05"); else if(builddate.substr(0, 3) == "Jun") build_date_.replace(5, 2, "06"); else if(builddate.substr(0, 3) == "Jul") build_date_.replace(5, 2, "07"); else if(builddate.substr(0, 3) == "Aug") build_date_.replace(5, 2, "08"); else if(builddate.substr(0, 3) == "Sep") build_date_.replace(5, 2, "09"); else if(builddate.substr(0, 3) == "Oct") build_date_.replace(5, 2, "10"); else if(builddate.substr(0, 3) == "Nov") build_date_.replace(5, 2, "11"); else if(builddate.substr(0, 3) == "Dec") build_date_.replace(5, 2, "12"); // Parse options if(argc >= 2) { for(int o = 1; o < argc; ++o) { if(argcmp(argv[o], "--help", "-h")) { help(argc > o + 1 ? argv[o + 1] : NULL); break; } else if(argcmp(argv[o], "--version")) { printf("reshp (reshape) version %s (built on %s)\n", version_.c_str(), build_date_.c_str()); printf("Command-line tool for manipulating ESRI Shapefiles.\n"); printf("\nWritten by the Norwegian Polar Institute (http://npolar.no/)\n"); printf("This is free software, and comes with absolutely NO WARRANTY\n"); break; } else if(argcmp(argv[o], "--verbose", "-v")) { verbose_ = true; } else if(argc > o + 1) { enum { action_none = 0x00, action_cleanup = 0x01, action_grade = 0x02, action_output = 0x04, action_subtract = 0x08 }; std::string filename(argv[o]); std::string input, output; unsigned action = action_none; // Parse parameters for(int p = o + 1; p < argc; ++p) { if(argcmp(argv[p], "--grade", "-g")) { action |= action_gade; } else if(argcmp(argv[p], "--list", "-l")) { list(filename, false); } else if(argcmp(argv[p], "--list-full", "-L")) { list(filename, true); } else if(argcmp(argv[p], "--output", "-o")) { if(argc > p + 1) { output = std::string(argv[p + 1]); action |= action_output; ++p; } else { printf("missing filename for shapefile output\n"); printf("Try '%s --help output' for more information\n", exe_name_.c_str()); } } else if(argcmp(argv[p], "--subtract", "-s")) { if(argc > p + 1) { input = argv[p + 1]; action |= action_subtract; ++p; } else { printf("missing input shapefile for subtract masking\n"); printf("Try '%s --help subtract' for more information\n", exe_name_.c_str()); } } else { printf("unrecognized parameter: %s\n", argv[p]); printf("Try '%s --help' for more information\n", exe_name_.c_str()); } } // Perform subtraction if specified if(action & action_subtract) subtract(filename, input, (action & action_output ? output.c_str() : NULL)); // Perform validation if specified if(action & action_grade) grade(action & action_output ? output : filename); // Output only if(action == action_output) { reshp::shp shpout; reshp::shx shxout; if(verbose_) { printf("output '%s' to '%s'\n", filename.c_str(), output.c_str()); } if(shpout.load(filename)) { if(verbose_) printf(" writing shapefile to '%s'\n", output.c_str()); if(shpout.save(output, verbose_)) { if(shxout.load(shpout, verbose_)) { std::string shxname(output); if(shxname.substr(shxname.length() - 4) == ".shp") shxname.replace(shxname.length() - 4, 4, ".shx"); else shxname += ".shx"; if(verbose_) printf(" writing shapefile index to '%s'\n", shxname.c_str()); shxout.save(shxname, verbose_); } } } } break; } } } else { printf("%s: missing parameter\n", exe_name_.c_str()); printf("Try '%s --help' for more information\n", exe_name_.c_str()); } } int handler::run() { return EXIT_SUCCESS; } } <commit_msg>Fixed typo<commit_after>/* * * * * * * * * * * * *\ |* ╔═╗ v0.3 *| |* ╔═╦═╦═══╦═══╣ ╚═╦═╦═╗ *| |* ║ ╔═╣ '╔╬═╗╚╣ ║ ║ '║ *| |* ╚═╝ ╚═══╩═══╩═╩═╣ ╔═╝ *| |* * * * * * * * * ╚═╝ * *| |* Manipulation tool for *| |* ESRI Shapefiles *| |* * * * * * * * * * * * *| |* http://www.npolar.no/ *| \* * * * * * * * * * * * */ #include "handler.hpp" #include <cstdlib> #include <cstring> #include <cstdio> namespace reshp { bool handler::argcmp(const char* arg, const char* opt1, const char* opt2) { if(arg && opt1) { if(strcmp(arg, opt1) == 0) return true; if(opt2 && (strcmp(arg, opt2) == 0)) return true; } return false; } void handler::help(const char* topic) { if(!topic) { printf("Usage: %s [option]... [shapefile <parameter>...]\n", exe_name_.c_str()); printf("Command-line tool for manipulating ESRI Shapefiles.\n"); printf("\nAvailable options:\n"); printf(" -h, --help [topic] display help text (about specified topic) and exit\n"); printf(" --version output version information and exit\n"); printf(" -v, --verbose verbosely output performed manipulation operations\n"); printf("\nShapefile parameters:\n"); //printf(" -a, --add <type> <property>... add record with specified type and properties to shapefile\n"); printf(" -g, --grade grade the shapefile ranging from A (best) to F (worst)\n"); printf(" -l, --list list various information about the shapefile\n"); printf(" -L, --list-full list full information about the shapefile, including coordinates\n"); printf(" -o, --output <filename> output (save) modified shapefile to specified filename\n"); printf(" -s, --subtract <input> subtract input shapefile shapes from shapefile\n"); } /* else if(argcmp(topic, "add", "a")) { printf("%s <shapefile> --add <type> [property]...\n", exe_name_.c_str()); printf("Add record with specified type and properties to shapefile.\n"); printf("\nRecord types:\n"); printf(" null empty placeholder shape\n"); printf(" point <x> <y> single 2D point\n"); printf(" polyline <mbr> <parts> <points> polygonal path of 2D points\n"); printf(" polygon <mbr> <parts> <points> filled polygon of 2D points\n"); printf(" multipoint <mbr> <points> collection of 2D points\n"); printf("\nProperties:\n"); printf(" <measure> measure floating number\n"); printf(" <mbr> bounding box with space separated floating numbers: <xmin> <ymin> <xmax> <ymax>\n"); printf(" <parts> number of parts followed by space separated point indices representing each part\n"); printf(" <points> number of points followed by space separated point coordinates: <x> <y>\n"); printf(" <x> x coordinate as floating number\n"); printf(" <y> y coordinate as floating number\n"); printf(" <z> z coordinate as floating number\n"); } */ else if(argcmp(topic, "grade", "g")) { printf("%s --grade\n", exe_name_.c_str()); printf("Validate the shapefile, and output one of the following grades:\n"); printf(" A: Valid ESRI Shapefile, which completely complies with the specifications\n"); printf(" B: Valid ESRI Shapefile, with valid data and clean shapes according to the specifications\n"); printf(" C: Valid ESRI Shapefile, with valid data and no self-intersecting shapes\n"); printf(" D: Valid ESRI Shapefile, with no broken records or missing data\n"); printf(" E: Valid ESRI Shapefile, with broken records or missing data\n"); printf(" F: Not a valid ESRI Shapefile\n"); printf("\n"); printf(" If an output filename is specified, the grading will be performed on this file\n"); } else if(argcmp(topic, "list", "l")) { printf("%s <shapefile> --list\n", exe_name_.c_str()); printf("List various information about shapefile.\n"); } else if(argcmp(topic, "output", "o")) { printf("%s <shapefile> --output [filename]\n", exe_name_.c_str()); printf("Output changes made to the shapefile to specified filename.\n"); } else if(argcmp(topic, "subtract", "s")) { printf("%s <shapefile> --subtract <input>\n", exe_name_.c_str()); printf("Subtract input shapefile shapes from shapes in the shapefile.\n"); } else if(argcmp(topic, "verbose", "v")) { printf("%s --verbose [shapefile <parameter>...]\n", exe_name_.c_str()); printf("Enable verbose output of certain manipulation operations.\n"); } else { printf("Unrecognized help topic: %s\n", topic); printf("Try '%s --help' for more information\n", exe_name_.c_str()); } } handler::handler(int argc, char** argv, const char* version) : build_date_("0000-00-00"), exe_name_(argv[0]), verbose_(false), version_(version) { size_t separator = exe_name_.rfind('/'); std::string builddate(__DATE__); if(separator != std::string::npos) exe_name_.erase(0, separator + 1); build_date_.replace(0, 4, builddate.substr(7, 4)); build_date_.replace(8, 2, builddate.substr(4, 2)); if(build_date_[8] == ' ') build_date_[8] = '0'; if(builddate.substr(0, 3) == "Jan") build_date_.replace(5, 2, "01"); else if(builddate.substr(0, 3) == "Feb") build_date_.replace(5, 2, "02"); else if(builddate.substr(0, 3) == "Mar") build_date_.replace(5, 2, "03"); else if(builddate.substr(0, 3) == "Apr") build_date_.replace(5, 2, "04"); else if(builddate.substr(0, 3) == "May") build_date_.replace(5, 2, "05"); else if(builddate.substr(0, 3) == "Jun") build_date_.replace(5, 2, "06"); else if(builddate.substr(0, 3) == "Jul") build_date_.replace(5, 2, "07"); else if(builddate.substr(0, 3) == "Aug") build_date_.replace(5, 2, "08"); else if(builddate.substr(0, 3) == "Sep") build_date_.replace(5, 2, "09"); else if(builddate.substr(0, 3) == "Oct") build_date_.replace(5, 2, "10"); else if(builddate.substr(0, 3) == "Nov") build_date_.replace(5, 2, "11"); else if(builddate.substr(0, 3) == "Dec") build_date_.replace(5, 2, "12"); // Parse options if(argc >= 2) { for(int o = 1; o < argc; ++o) { if(argcmp(argv[o], "--help", "-h")) { help(argc > o + 1 ? argv[o + 1] : NULL); break; } else if(argcmp(argv[o], "--version")) { printf("reshp (reshape) version %s (built on %s)\n", version_.c_str(), build_date_.c_str()); printf("Command-line tool for manipulating ESRI Shapefiles.\n"); printf("\nWritten by the Norwegian Polar Institute (http://npolar.no/)\n"); printf("This is free software, and comes with absolutely NO WARRANTY\n"); break; } else if(argcmp(argv[o], "--verbose", "-v")) { verbose_ = true; } else if(argc > o + 1) { enum { action_none = 0x00, action_cleanup = 0x01, action_grade = 0x02, action_output = 0x04, action_subtract = 0x08 }; std::string filename(argv[o]); std::string input, output; unsigned action = action_none; // Parse parameters for(int p = o + 1; p < argc; ++p) { if(argcmp(argv[p], "--grade", "-g")) { action |= action_grade; } else if(argcmp(argv[p], "--list", "-l")) { list(filename, false); } else if(argcmp(argv[p], "--list-full", "-L")) { list(filename, true); } else if(argcmp(argv[p], "--output", "-o")) { if(argc > p + 1) { output = std::string(argv[p + 1]); action |= action_output; ++p; } else { printf("missing filename for shapefile output\n"); printf("Try '%s --help output' for more information\n", exe_name_.c_str()); } } else if(argcmp(argv[p], "--subtract", "-s")) { if(argc > p + 1) { input = argv[p + 1]; action |= action_subtract; ++p; } else { printf("missing input shapefile for subtract masking\n"); printf("Try '%s --help subtract' for more information\n", exe_name_.c_str()); } } else { printf("unrecognized parameter: %s\n", argv[p]); printf("Try '%s --help' for more information\n", exe_name_.c_str()); } } // Perform subtraction if specified if(action & action_subtract) subtract(filename, input, (action & action_output ? output.c_str() : NULL)); // Perform validation if specified if(action & action_grade) grade(action & action_output ? output : filename); // Output only if(action == action_output) { reshp::shp shpout; reshp::shx shxout; if(verbose_) { printf("output '%s' to '%s'\n", filename.c_str(), output.c_str()); } if(shpout.load(filename)) { if(verbose_) printf(" writing shapefile to '%s'\n", output.c_str()); if(shpout.save(output, verbose_)) { if(shxout.load(shpout, verbose_)) { std::string shxname(output); if(shxname.substr(shxname.length() - 4) == ".shp") shxname.replace(shxname.length() - 4, 4, ".shx"); else shxname += ".shx"; if(verbose_) printf(" writing shapefile index to '%s'\n", shxname.c_str()); shxout.save(shxname, verbose_); } } } } break; } } } else { printf("%s: missing parameter\n", exe_name_.c_str()); printf("Try '%s --help' for more information\n", exe_name_.c_str()); } } int handler::run() { return EXIT_SUCCESS; } } <|endoftext|>
<commit_before>#include "../include/ChebyshevSolver.h" #include <math.h> #include "../include/HALinkedList.h" using namespace std; const complex<double> i(0, 1); ChebyshevSolver::ChebyshevSolver(){ generatingFunctionLookupTable = NULL; generatingFunctionLookupTable_device = NULL; lookupTableNumCoefficients = 0; lookupTableResolution = 0; } ChebyshevSolver::~ChebyshevSolver(){ if(generatingFunctionLookupTable != NULL){ for(int n = 0; n < lookupTableNumCoefficients; n++) delete [] generatingFunctionLookupTable[n]; delete [] generatingFunctionLookupTable; } } void ChebyshevSolver::setModel(Model *model){ this->model = model; } void ChebyshevSolver::calculateCoefficients(Index to, Index from, complex<double> *coefficients, int numCoefficients){ AmplitudeSet *amplitudeSet = &model->amplitudeSet; int fromBasisIndex = amplitudeSet->getBasisIndex(from); int toBasisIndex = amplitudeSet->getBasisIndex(to); cout << "From Index: " << fromBasisIndex << "\n"; cout << "To Index: " << toBasisIndex << "\n"; cout << "Basis size: " << amplitudeSet->getBasisSize() << "\n"; complex<double> *jIn1 = new complex<double>[amplitudeSet->getBasisSize()]; complex<double> *jIn2 = new complex<double>[amplitudeSet->getBasisSize()]; // complex<double> *jOut = new complex<double>[amplitudeSet->getBasisSize()]; complex<double> *jResult = new complex<double>[amplitudeSet->getBasisSize()]; complex<double> *jTemp = NULL; for(int n = 0; n < amplitudeSet->getBasisSize(); n++){ jIn1[n] = 0.; jIn2[n] = 0.; // jOut[n] = 0.; jResult[n] = 0.; } //Set up initial state (|j0>) jIn1[fromBasisIndex] = 1.; // jOut[toBasisIndex] = 1.; coefficients[0] = jIn1[toBasisIndex]; //Generate a fixed hopping amplitude and inde list, for speed. AmplitudeSet::iterator it = amplitudeSet->getIterator(); HoppingAmplitude *ha; int numHoppingAmplitudes = 0; while((ha = it.getHA())){ numHoppingAmplitudes++; it.searchNextHA(); } complex<double> *hoppingAmplitudes = new complex<double>[numHoppingAmplitudes]; int *toIndices = new int[numHoppingAmplitudes]; int *fromIndices = new int[numHoppingAmplitudes]; it.reset(); int counter = 0; while((ha = it.getHA())){ toIndices[counter] = amplitudeSet->getBasisIndex(ha->toIndex); fromIndices[counter] = amplitudeSet->getBasisIndex(ha->fromIndex); hoppingAmplitudes[counter] = ha->getAmplitude(); it.searchNextHA(); counter++; } //Calculate |j1> for(int n = 0; n < numHoppingAmplitudes; n++){ int from = fromIndices[n]; int to = toIndices[n]; jResult[to] = hoppingAmplitudes[n]*jIn1[from]; } jTemp = jIn2; jIn2 = jIn1; jIn1 = jResult; jResult = jTemp; coefficients[1] = jIn1[toBasisIndex]; //Multiply hopping amplitudes by factor two, to spped up calculation of 2H|j(n-1)> - |j(n-2)>. for(int n = 0; n < numHoppingAmplitudes; n++) hoppingAmplitudes[n] *= 2.; //Iteratively calculate |jn> and corresponding Chebyshev coefficients. for(int n = 2; n < numCoefficients; n++){ for(int c = 0; c < amplitudeSet->getBasisSize(); c++) jResult[c] = -jIn2[c]; for(int c = 0; c < numHoppingAmplitudes; c++){ int from = fromIndices[c]; int to = toIndices[c]; jResult[to] += hoppingAmplitudes[c]*jIn1[from]; } jTemp = jIn2; jIn2 = jIn1; jIn1 = jResult; jResult = jTemp; coefficients[n] = jIn1[toBasisIndex]; if(n%100 == 0) cout << n << "\n"; } delete [] jIn1; delete [] jIn2; // delete [] jOut; delete [] jResult; delete [] hoppingAmplitudes; delete [] toIndices; delete [] fromIndices; //Lorentzian convolution double epsilon = 0.001; double lambda = epsilon*numCoefficients; for(int n = 0; n < numCoefficients; n++) coefficients[n] = coefficients[n]*sinh(lambda*(1 - n/(double)numCoefficients))/sinh(lambda); } void ChebyshevSolver::calculateCoefficients(Index to, Index from, complex<double> *coefficients, int numCoefficients, double componentCutoff){ AmplitudeSet *amplitudeSet = &model->amplitudeSet; int fromBasisIndex = amplitudeSet->getBasisIndex(from); int toBasisIndex = amplitudeSet->getBasisIndex(to); cout << "From index: " << fromBasisIndex << "\n"; cout << "To index: " << toBasisIndex << "\n"; cout << "Basis size: " << amplitudeSet->getBasisSize() << "\n"; complex<double> *jIn1 = new complex<double>[amplitudeSet->getBasisSize()]; complex<double> *jIn2 = new complex<double>[amplitudeSet->getBasisSize()]; // complex<double> *jOut = new complex<double>[amplitudeSet->getBasisSize()]; complex<double> *jResult = new complex<double>[amplitudeSet->getBasisSize()]; complex<double> *jTemp = NULL; for(int n = 0; n < amplitudeSet->getBasisSize(); n++){ jIn1[n] = 0.; jIn2[n] = 0.; // jOut[n] = 0.; jResult[n] = 0.; } //Set up initial state |j0>. jIn1[fromBasisIndex] = 1.; // jOut[toBasisIndex] = 1.; coefficients[0] = jIn1[toBasisIndex]; HALinkedList haLinkedList(*amplitudeSet); haLinkedList.addLinkedList(fromBasisIndex); int *newlyReachedIndices = new int[amplitudeSet->getBasisSize()]; int *everReachedIndices = new int[amplitudeSet->getBasisSize()]; bool *everReachedIndicesAdded = new bool[amplitudeSet->getBasisSize()]; int newlyReachedIndicesCounter = 0; int everReachedIndicesCounter = 0; for(int n = 0; n < amplitudeSet->getBasisSize(); n++){ newlyReachedIndices[n] = -1; everReachedIndices[n] = -1; everReachedIndicesAdded[n] = false; } HALink *link = haLinkedList.getFirstMainLink(); while(link != NULL){ int from = link->from; int to = link->to; jResult[to] += link->amplitude*jIn1[from]; if(!everReachedIndicesAdded[to]){ newlyReachedIndices[newlyReachedIndicesCounter] = to; newlyReachedIndicesCounter++; } link = link->next2; } for(int n = 0; n < newlyReachedIndicesCounter; n++){ if(abs(jResult[newlyReachedIndices[n]]) > componentCutoff){ haLinkedList.addLinkedList(newlyReachedIndices[n]); if(!everReachedIndicesAdded[newlyReachedIndices[n]]){ everReachedIndicesAdded[newlyReachedIndices[n]] = true; everReachedIndices[everReachedIndicesCounter] = newlyReachedIndices[n]; everReachedIndicesCounter++; } } else{ jResult[newlyReachedIndices[n]] = 0.; } } jTemp = jIn2; jIn2 = jIn1; jIn1 = jResult; jResult = jTemp; coefficients[1] = jIn1[toBasisIndex]; //Multiply hopping amplitudes by factor two, to speed up calculation of 2H|j(n-1)> - |j(n-2)>. HALink *links = haLinkedList.getLinkArray(); for(int n = 0; n < haLinkedList.getLinkArraySize(); n++) links[n].amplitude *= 2.; //Iteratively calcuate |jn> and corresponding coefficients. for(int n = 2; n < numCoefficients; n++){ for(int c = 0; c < everReachedIndicesCounter; c++) jResult[everReachedIndices[c]] = -jIn2[everReachedIndices[c]]; newlyReachedIndicesCounter = 0.; HALink *link = haLinkedList.getFirstMainLink(); while(link != NULL){ int from = link->from; int to = link->to; jResult[to] += link->amplitude*jIn1[from]; if(!everReachedIndicesAdded[to]){ newlyReachedIndices[newlyReachedIndicesCounter] = to; newlyReachedIndicesCounter++; } link = link->next2; } for(int c = 0; c < newlyReachedIndicesCounter; c++){ if(abs(jResult[newlyReachedIndices[c]]) > componentCutoff){ haLinkedList.addLinkedList(newlyReachedIndices[c]); if(!everReachedIndicesAdded[newlyReachedIndices[c]]){ everReachedIndicesAdded[newlyReachedIndices[c]] = true; everReachedIndices[everReachedIndicesCounter] = newlyReachedIndices[c]; everReachedIndicesCounter++; } else{ jResult[newlyReachedIndices[c]] = 0.; } } } jTemp = jIn2; jIn2 = jIn1; jIn1 = jResult; jResult = jTemp; coefficients[n] = jIn1[toBasisIndex]; if(n%100 == 0) cout << n << "\t" << everReachedIndicesCounter << "\t" << everReachedIndicesCounter/(double)amplitudeSet->getBasisSize() << "\t" << abs(coefficients[n]) // << "\t" << sqrt(abs(scalarProduct(jIn1, jIn1, amplitudeSet->getBasisSize()))) << "\n"; } delete [] jIn1; delete [] jIn2; // delete [] jOut; delete [] jResult; delete [] newlyReachedIndices; delete [] everReachedIndices; //Lorentzian convolution double epsilon = 0.001; double lambda = epsilon*numCoefficients; for(int n = 0; n < numCoefficients; n++) coefficients[n] = coefficients[n]*sinh(lambda*(1 - n/(double)numCoefficients))/sinh(lambda); } void ChebyshevSolver::generateLookupTable(int numCoefficients, int energyResolution){ cout << "Generating lookup table\n"; cout << "\tNum coefficients: " << numCoefficients << "\n"; cout << "\tEnergy resolution: " << energyResolution << "\n"; if(generatingFunctionLookupTable != NULL){ for(int n = 0; n < lookupTableNumCoefficients; n++) delete [] generatingFunctionLookupTable[n]; delete [] generatingFunctionLookupTable; } lookupTableNumCoefficients = numCoefficients; lookupTableResolution = energyResolution; generatingFunctionLookupTable = new complex<double>*[numCoefficients]; for(int n = 0; n < numCoefficients; n++) generatingFunctionLookupTable[n] = new complex<double>[energyResolution]; const double DELTA = 0.0001; #pragma omp parallel for for(int n = 0; n < numCoefficients; n++){ double denominator = 1.; if(n == 0) denominator = 2.; for(int e = 0; e < energyResolution; e++){ double E = -1 + 2.*e/(double)energyResolution; generatingFunctionLookupTable[n][e] = (-2.*i/sqrt(1+DELTA - E*E))*exp(-i*((double)n)*acos(E))/denominator; } } } void ChebyshevSolver::generateGreensFunction(complex<double> *greensFunction, complex<double> *coefficients, int numCoefficients, int energyResolution){ for(int e = 0; e < energyResolution; e++) greensFunction[e] = 0.; const double DELTA = 0.0001; for(int n = 0; n < numCoefficients; n++){ double denominator = 1.; if(n == 0) denominator = 2.; for(int e = 0; e < energyResolution; e++){ double E = -1 + 2.*e/(double)energyResolution; greensFunction[e] += (-2.*i/sqrt(1+DELTA - E*E))*coefficients[n]*exp(-i*((double)n)*acos(E))/denominator; } } } void ChebyshevSolver::generateGreensFunction(complex<double> *greensFunction, complex<double> *coefficients){ if(generatingFunctionLookupTable == NULL){ cout << "Error in ChebyshevSolver::generateGreensFunction: Lookup table has not been generated."; exit(1); } else{ for(int e = 0; e < lookupTableResolution; e++) greensFunction[e] = 0.; for(int n = 0; n < lookupTableNumCoefficients; n++){ for(int e = 0; e < lookupTableResolution; e++){ greensFunction[e] += generatingFunctionLookupTable[n][e]*coefficients[n]; } } } } <commit_msg>Parallelized CPU version of ChebyshevSolver.calculateCoefficients with openmp<commit_after>#include "../include/ChebyshevSolver.h" #include <math.h> #include "../include/HALinkedList.h" using namespace std; const complex<double> i(0, 1); ChebyshevSolver::ChebyshevSolver(){ generatingFunctionLookupTable = NULL; generatingFunctionLookupTable_device = NULL; lookupTableNumCoefficients = 0; lookupTableResolution = 0; } ChebyshevSolver::~ChebyshevSolver(){ if(generatingFunctionLookupTable != NULL){ for(int n = 0; n < lookupTableNumCoefficients; n++) delete [] generatingFunctionLookupTable[n]; delete [] generatingFunctionLookupTable; } } void ChebyshevSolver::setModel(Model *model){ this->model = model; } void ChebyshevSolver::calculateCoefficients(Index to, Index from, complex<double> *coefficients, int numCoefficients){ AmplitudeSet *amplitudeSet = &model->amplitudeSet; int fromBasisIndex = amplitudeSet->getBasisIndex(from); int toBasisIndex = amplitudeSet->getBasisIndex(to); cout << "From Index: " << fromBasisIndex << "\n"; cout << "To Index: " << toBasisIndex << "\n"; cout << "Basis size: " << amplitudeSet->getBasisSize() << "\n"; complex<double> *jIn1 = new complex<double>[amplitudeSet->getBasisSize()]; complex<double> *jIn2 = new complex<double>[amplitudeSet->getBasisSize()]; // complex<double> *jOut = new complex<double>[amplitudeSet->getBasisSize()]; complex<double> *jResult = new complex<double>[amplitudeSet->getBasisSize()]; complex<double> *jTemp = NULL; for(int n = 0; n < amplitudeSet->getBasisSize(); n++){ jIn1[n] = 0.; jIn2[n] = 0.; // jOut[n] = 0.; jResult[n] = 0.; } //Set up initial state (|j0>) jIn1[fromBasisIndex] = 1.; // jOut[toBasisIndex] = 1.; coefficients[0] = jIn1[toBasisIndex]; //Generate a fixed hopping amplitude and inde list, for speed. AmplitudeSet::iterator it = amplitudeSet->getIterator(); HoppingAmplitude *ha; int numHoppingAmplitudes = 0; while((ha = it.getHA())){ numHoppingAmplitudes++; it.searchNextHA(); } complex<double> *hoppingAmplitudes = new complex<double>[numHoppingAmplitudes]; int *toIndices = new int[numHoppingAmplitudes]; int *fromIndices = new int[numHoppingAmplitudes]; it.reset(); int counter = 0; while((ha = it.getHA())){ toIndices[counter] = amplitudeSet->getBasisIndex(ha->toIndex); fromIndices[counter] = amplitudeSet->getBasisIndex(ha->fromIndex); hoppingAmplitudes[counter] = ha->getAmplitude(); it.searchNextHA(); counter++; } //Calculate |j1> for(int n = 0; n < numHoppingAmplitudes; n++){ int from = fromIndices[n]; int to = toIndices[n]; jResult[to] = hoppingAmplitudes[n]*jIn1[from]; } jTemp = jIn2; jIn2 = jIn1; jIn1 = jResult; jResult = jTemp; coefficients[1] = jIn1[toBasisIndex]; //Multiply hopping amplitudes by factor two, to spped up calculation of 2H|j(n-1)> - |j(n-2)>. for(int n = 0; n < numHoppingAmplitudes; n++) hoppingAmplitudes[n] *= 2.; //Iteratively calculate |jn> and corresponding Chebyshev coefficients. for(int n = 2; n < numCoefficients; n++){ #pragma omp parallel for for(int c = 0; c < amplitudeSet->getBasisSize(); c++) jResult[c] = -jIn2[c]; #pragma omp parallel for for(int c = 0; c < numHoppingAmplitudes; c++){ int from = fromIndices[c]; int to = toIndices[c]; jResult[to] += hoppingAmplitudes[c]*jIn1[from]; } jTemp = jIn2; jIn2 = jIn1; jIn1 = jResult; jResult = jTemp; coefficients[n] = jIn1[toBasisIndex]; if(n%100 == 0) cout << n << "\n"; } delete [] jIn1; delete [] jIn2; // delete [] jOut; delete [] jResult; delete [] hoppingAmplitudes; delete [] toIndices; delete [] fromIndices; //Lorentzian convolution double epsilon = 0.001; double lambda = epsilon*numCoefficients; for(int n = 0; n < numCoefficients; n++) coefficients[n] = coefficients[n]*sinh(lambda*(1 - n/(double)numCoefficients))/sinh(lambda); } void ChebyshevSolver::calculateCoefficients(Index to, Index from, complex<double> *coefficients, int numCoefficients, double componentCutoff){ AmplitudeSet *amplitudeSet = &model->amplitudeSet; int fromBasisIndex = amplitudeSet->getBasisIndex(from); int toBasisIndex = amplitudeSet->getBasisIndex(to); cout << "From index: " << fromBasisIndex << "\n"; cout << "To index: " << toBasisIndex << "\n"; cout << "Basis size: " << amplitudeSet->getBasisSize() << "\n"; complex<double> *jIn1 = new complex<double>[amplitudeSet->getBasisSize()]; complex<double> *jIn2 = new complex<double>[amplitudeSet->getBasisSize()]; // complex<double> *jOut = new complex<double>[amplitudeSet->getBasisSize()]; complex<double> *jResult = new complex<double>[amplitudeSet->getBasisSize()]; complex<double> *jTemp = NULL; for(int n = 0; n < amplitudeSet->getBasisSize(); n++){ jIn1[n] = 0.; jIn2[n] = 0.; // jOut[n] = 0.; jResult[n] = 0.; } //Set up initial state |j0>. jIn1[fromBasisIndex] = 1.; // jOut[toBasisIndex] = 1.; coefficients[0] = jIn1[toBasisIndex]; HALinkedList haLinkedList(*amplitudeSet); haLinkedList.addLinkedList(fromBasisIndex); int *newlyReachedIndices = new int[amplitudeSet->getBasisSize()]; int *everReachedIndices = new int[amplitudeSet->getBasisSize()]; bool *everReachedIndicesAdded = new bool[amplitudeSet->getBasisSize()]; int newlyReachedIndicesCounter = 0; int everReachedIndicesCounter = 0; for(int n = 0; n < amplitudeSet->getBasisSize(); n++){ newlyReachedIndices[n] = -1; everReachedIndices[n] = -1; everReachedIndicesAdded[n] = false; } HALink *link = haLinkedList.getFirstMainLink(); while(link != NULL){ int from = link->from; int to = link->to; jResult[to] += link->amplitude*jIn1[from]; if(!everReachedIndicesAdded[to]){ newlyReachedIndices[newlyReachedIndicesCounter] = to; newlyReachedIndicesCounter++; } link = link->next2; } for(int n = 0; n < newlyReachedIndicesCounter; n++){ if(abs(jResult[newlyReachedIndices[n]]) > componentCutoff){ haLinkedList.addLinkedList(newlyReachedIndices[n]); if(!everReachedIndicesAdded[newlyReachedIndices[n]]){ everReachedIndicesAdded[newlyReachedIndices[n]] = true; everReachedIndices[everReachedIndicesCounter] = newlyReachedIndices[n]; everReachedIndicesCounter++; } } else{ jResult[newlyReachedIndices[n]] = 0.; } } jTemp = jIn2; jIn2 = jIn1; jIn1 = jResult; jResult = jTemp; coefficients[1] = jIn1[toBasisIndex]; //Multiply hopping amplitudes by factor two, to speed up calculation of 2H|j(n-1)> - |j(n-2)>. HALink *links = haLinkedList.getLinkArray(); for(int n = 0; n < haLinkedList.getLinkArraySize(); n++) links[n].amplitude *= 2.; //Iteratively calcuate |jn> and corresponding coefficients. for(int n = 2; n < numCoefficients; n++){ for(int c = 0; c < everReachedIndicesCounter; c++) jResult[everReachedIndices[c]] = -jIn2[everReachedIndices[c]]; newlyReachedIndicesCounter = 0.; HALink *link = haLinkedList.getFirstMainLink(); while(link != NULL){ int from = link->from; int to = link->to; jResult[to] += link->amplitude*jIn1[from]; if(!everReachedIndicesAdded[to]){ newlyReachedIndices[newlyReachedIndicesCounter] = to; newlyReachedIndicesCounter++; } link = link->next2; } for(int c = 0; c < newlyReachedIndicesCounter; c++){ if(abs(jResult[newlyReachedIndices[c]]) > componentCutoff){ haLinkedList.addLinkedList(newlyReachedIndices[c]); if(!everReachedIndicesAdded[newlyReachedIndices[c]]){ everReachedIndicesAdded[newlyReachedIndices[c]] = true; everReachedIndices[everReachedIndicesCounter] = newlyReachedIndices[c]; everReachedIndicesCounter++; } else{ jResult[newlyReachedIndices[c]] = 0.; } } } jTemp = jIn2; jIn2 = jIn1; jIn1 = jResult; jResult = jTemp; coefficients[n] = jIn1[toBasisIndex]; if(n%100 == 0) cout << n << "\t" << everReachedIndicesCounter << "\t" << everReachedIndicesCounter/(double)amplitudeSet->getBasisSize() << "\t" << abs(coefficients[n]) // << "\t" << sqrt(abs(scalarProduct(jIn1, jIn1, amplitudeSet->getBasisSize()))) << "\n"; } delete [] jIn1; delete [] jIn2; // delete [] jOut; delete [] jResult; delete [] newlyReachedIndices; delete [] everReachedIndices; //Lorentzian convolution double epsilon = 0.001; double lambda = epsilon*numCoefficients; for(int n = 0; n < numCoefficients; n++) coefficients[n] = coefficients[n]*sinh(lambda*(1 - n/(double)numCoefficients))/sinh(lambda); } void ChebyshevSolver::generateLookupTable(int numCoefficients, int energyResolution){ cout << "Generating lookup table\n"; cout << "\tNum coefficients: " << numCoefficients << "\n"; cout << "\tEnergy resolution: " << energyResolution << "\n"; if(generatingFunctionLookupTable != NULL){ for(int n = 0; n < lookupTableNumCoefficients; n++) delete [] generatingFunctionLookupTable[n]; delete [] generatingFunctionLookupTable; } lookupTableNumCoefficients = numCoefficients; lookupTableResolution = energyResolution; generatingFunctionLookupTable = new complex<double>*[numCoefficients]; for(int n = 0; n < numCoefficients; n++) generatingFunctionLookupTable[n] = new complex<double>[energyResolution]; const double DELTA = 0.0001; #pragma omp parallel for for(int n = 0; n < numCoefficients; n++){ double denominator = 1.; if(n == 0) denominator = 2.; for(int e = 0; e < energyResolution; e++){ double E = -1 + 2.*e/(double)energyResolution; generatingFunctionLookupTable[n][e] = (-2.*i/sqrt(1+DELTA - E*E))*exp(-i*((double)n)*acos(E))/denominator; } } } void ChebyshevSolver::generateGreensFunction(complex<double> *greensFunction, complex<double> *coefficients, int numCoefficients, int energyResolution){ for(int e = 0; e < energyResolution; e++) greensFunction[e] = 0.; const double DELTA = 0.0001; for(int n = 0; n < numCoefficients; n++){ double denominator = 1.; if(n == 0) denominator = 2.; for(int e = 0; e < energyResolution; e++){ double E = -1 + 2.*e/(double)energyResolution; greensFunction[e] += (-2.*i/sqrt(1+DELTA - E*E))*coefficients[n]*exp(-i*((double)n)*acos(E))/denominator; } } } void ChebyshevSolver::generateGreensFunction(complex<double> *greensFunction, complex<double> *coefficients){ if(generatingFunctionLookupTable == NULL){ cout << "Error in ChebyshevSolver::generateGreensFunction: Lookup table has not been generated."; exit(1); } else{ for(int e = 0; e < lookupTableResolution; e++) greensFunction[e] = 0.; for(int n = 0; n < lookupTableNumCoefficients; n++){ for(int e = 0; e < lookupTableResolution; e++){ greensFunction[e] += generatingFunctionLookupTable[n][e]*coefficients[n]; } } } } <|endoftext|>
<commit_before>#include <iostream> using namespace std; a int main(int argc, char const *argv[]) { int n; int s=0,a; while(cin >>n;){ s=(n+1)*n/2; cout<<s; } return 0; } <commit_msg>update hdu1001<commit_after>#include <iostream> using namespace std; int main(int argc, char const *argv[]) { int n; int s=0,a; while(cin >>n;){ s=(n+1)*n/2; cout<<s; } return 0; } <|endoftext|>
<commit_before>#include <iostream> using namespace std; int main(int argc, char const *argv[]) { int n; cin >>n; int s=0,a; while(n--){ cin>>a; s+=a; } cout<<a; return 0; } <commit_msg>update hdu1001<commit_after>#include <iostream> using namespace std; int main(int argc, char const *argv[]) { int n; cin >>n; int s=0,a; while(n--){ cin>>a; s+=a; } cout<<s; return 0; } <|endoftext|>