text
stringlengths
54
60.6k
<commit_before>#ifdef ANALYSIS #include <stdio.h> /* printf */ #include <math.h> #include "analysis.h" #include "../io.h" #ifdef MPI_CHOLLA #include "../mpi_routines.h" #endif void Grid3D::Compute_Phase_Diagram(){ int n_temp, n_dens; Real temp_min, temp_max, dens_min, dens_max; Real log_temp_min, log_temp_max, log_dens_min, log_dens_max; Real log_delta_dens, log_delta_temp; n_dens = Analysis.n_dens; n_temp = Analysis.n_temp; dens_min = Analysis.dens_min; dens_max = Analysis.dens_max; temp_min = Analysis.temp_min; temp_max = Analysis.temp_max; log_dens_min = log10( dens_min ); log_dens_max = log10( dens_max ); log_temp_min = log10( temp_min ); log_temp_max = log10( temp_max ); log_delta_dens = ( log_dens_max - log_dens_min ) / n_dens; log_delta_temp = ( log_temp_max - log_temp_min ) / n_temp; int nx_local, ny_local, nz_local, n_ghost; int nx_grid, ny_grid, nz_grid; nx_local = Analysis.nx_local; ny_local = Analysis.ny_local; nz_local = Analysis.nz_local; n_ghost = Analysis.n_ghost; nx_grid = nx_local + 2*n_ghost; ny_grid = ny_local + 2*n_ghost; nz_grid = nz_local + 2*n_ghost; Real dens, log_dens, temp, log_temp; int k, j, i, id_grid; int indx_dens, indx_temp, indx_phase; //Clear Phase Dikagram for (indx_phase=0; indx_phase<n_temp*n_dens; indx_phase++) Analysis.phase_diagram[indx_phase] = 0; for ( k=0; k<nz_local; k++ ){ for ( j=0; j<ny_local; j++ ){ for ( i=0; i<nx_local; i++ ){ id_grid = (i+n_ghost) + (j+n_ghost)*nx_grid + (k+n_ghost)*nx_grid*ny_grid; dens = C.density[id_grid] * Cosmo.rho_0_gas / Cosmo.rho_mean_baryon; // Baryionic overdensity // chprintf( "%f %f \n", dens, temp); #ifdef COOLING_GRACKLE temp = Cool.temperature[id_grid]; #endif if ( dens < dens_min || dens > dens_max || temp < temp_min || temp > temp_max ){ printf("%f %f\n", dens, temp ); continue; } log_dens = log10(dens); log_temp = log10(temp); indx_dens = ( log_dens - log_dens_min ) / log_delta_dens; indx_temp = ( log_temp - log_temp_min ) / log_delta_temp; indx_phase = indx_temp + indx_dens*n_temp; Analysis.phase_diagram[indx_phase] += 1; } } } // Real phase_sum_local = 0; // for (indx_phase=0; indx_phase<n_temp*n_dens; indx_phase++) phase_sum_local += Analysis.phase_diagram[indx_phase]; // printf(" Phase Diagram Sum Local: %f\n", phase_sum_local ); #ifdef MPI_CHOLLA MPI_Reduce( Analysis.phase_diagram, Analysis.phase_diagram_global, n_temp*n_dens, MPI_FLOAT, MPI_SUM, 0, world ); if ( procID == 0) for (indx_phase=0; indx_phase<n_temp*n_dens; indx_phase++) Analysis.phase_diagram[indx_phase] = Analysis.phase_diagram_global[indx_phase]; #endif //Compute the sum for normalization Real phase_sum = 0; for (indx_phase=0; indx_phase<n_temp*n_dens; indx_phase++) phase_sum += Analysis.phase_diagram[indx_phase]; chprintf(" Phase Diagram Sum Global: %f\n", phase_sum ); //Normalize the Phase Diagram for (indx_phase=0; indx_phase<n_temp*n_dens; indx_phase++) Analysis.phase_diagram[indx_phase] /= phase_sum; } void Analysis_Module::Initialize_Phase_Diagram( struct parameters *P ){ //Size of the diagram n_dens = 1000; n_temp = 1000; dens_min = 1e-3; dens_max = 1e6; temp_min = 1e0; temp_max = 1e8; phase_diagram = (float *) malloc(n_dens*n_temp*sizeof(float)); #ifdef MPI_CHOLLA if (procID == 0) phase_diagram_global = (float *) malloc(n_dens*n_temp*sizeof(float)); #endif chprintf(" Phase Diagram Initialized.\n"); } #endif<commit_msg>don't print out of phase diagram dens and temp<commit_after>#ifdef ANALYSIS #include <stdio.h> /* printf */ #include <math.h> #include "analysis.h" #include "../io.h" #ifdef MPI_CHOLLA #include "../mpi_routines.h" #endif void Grid3D::Compute_Phase_Diagram(){ int n_temp, n_dens; Real temp_min, temp_max, dens_min, dens_max; Real log_temp_min, log_temp_max, log_dens_min, log_dens_max; Real log_delta_dens, log_delta_temp; n_dens = Analysis.n_dens; n_temp = Analysis.n_temp; dens_min = Analysis.dens_min; dens_max = Analysis.dens_max; temp_min = Analysis.temp_min; temp_max = Analysis.temp_max; log_dens_min = log10( dens_min ); log_dens_max = log10( dens_max ); log_temp_min = log10( temp_min ); log_temp_max = log10( temp_max ); log_delta_dens = ( log_dens_max - log_dens_min ) / n_dens; log_delta_temp = ( log_temp_max - log_temp_min ) / n_temp; int nx_local, ny_local, nz_local, n_ghost; int nx_grid, ny_grid, nz_grid; nx_local = Analysis.nx_local; ny_local = Analysis.ny_local; nz_local = Analysis.nz_local; n_ghost = Analysis.n_ghost; nx_grid = nx_local + 2*n_ghost; ny_grid = ny_local + 2*n_ghost; nz_grid = nz_local + 2*n_ghost; Real dens, log_dens, temp, log_temp; int k, j, i, id_grid; int indx_dens, indx_temp, indx_phase; //Clear Phase Dikagram for (indx_phase=0; indx_phase<n_temp*n_dens; indx_phase++) Analysis.phase_diagram[indx_phase] = 0; for ( k=0; k<nz_local; k++ ){ for ( j=0; j<ny_local; j++ ){ for ( i=0; i<nx_local; i++ ){ id_grid = (i+n_ghost) + (j+n_ghost)*nx_grid + (k+n_ghost)*nx_grid*ny_grid; dens = C.density[id_grid] * Cosmo.rho_0_gas / Cosmo.rho_mean_baryon; // Baryionic overdensity // chprintf( "%f %f \n", dens, temp); #ifdef COOLING_GRACKLE temp = Cool.temperature[id_grid]; #endif if ( dens < dens_min || dens > dens_max || temp < temp_min || temp > temp_max ){ // printf("%f %f\n", dens, temp ); continue; } log_dens = log10(dens); log_temp = log10(temp); indx_dens = ( log_dens - log_dens_min ) / log_delta_dens; indx_temp = ( log_temp - log_temp_min ) / log_delta_temp; indx_phase = indx_temp + indx_dens*n_temp; Analysis.phase_diagram[indx_phase] += 1; } } } // Real phase_sum_local = 0; // for (indx_phase=0; indx_phase<n_temp*n_dens; indx_phase++) phase_sum_local += Analysis.phase_diagram[indx_phase]; // printf(" Phase Diagram Sum Local: %f\n", phase_sum_local ); #ifdef MPI_CHOLLA MPI_Reduce( Analysis.phase_diagram, Analysis.phase_diagram_global, n_temp*n_dens, MPI_FLOAT, MPI_SUM, 0, world ); if ( procID == 0) for (indx_phase=0; indx_phase<n_temp*n_dens; indx_phase++) Analysis.phase_diagram[indx_phase] = Analysis.phase_diagram_global[indx_phase]; #endif //Compute the sum for normalization Real phase_sum = 0; for (indx_phase=0; indx_phase<n_temp*n_dens; indx_phase++) phase_sum += Analysis.phase_diagram[indx_phase]; chprintf(" Phase Diagram Sum Global: %f\n", phase_sum ); //Normalize the Phase Diagram for (indx_phase=0; indx_phase<n_temp*n_dens; indx_phase++) Analysis.phase_diagram[indx_phase] /= phase_sum; } void Analysis_Module::Initialize_Phase_Diagram( struct parameters *P ){ //Size of the diagram n_dens = 1000; n_temp = 1000; dens_min = 1e-3; dens_max = 1e6; temp_min = 1e0; temp_max = 1e8; phase_diagram = (float *) malloc(n_dens*n_temp*sizeof(float)); #ifdef MPI_CHOLLA if (procID == 0) phase_diagram_global = (float *) malloc(n_dens*n_temp*sizeof(float)); #endif chprintf(" Phase Diagram Initialized.\n"); } #endif<|endoftext|>
<commit_before>//===--- ImageInspectionELF.cpp - ELF image inspection --------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// /// \file /// /// This file includes routines that interact with ld*.so on ELF-based platforms /// to extract runtime metadata embedded in dynamically linked ELF images /// generated by the Swift compiler. /// //===----------------------------------------------------------------------===// #if defined(__ELF__) || defined(__ANDROID__) #include "ImageInspection.h" #include "swift/Runtime/Debug.h" #include <dlfcn.h> #include <elf.h> #include <link.h> #include <string.h> using namespace swift; /// The symbol name in the image that identifies the beginning of the /// protocol conformances table. static const char ProtocolConformancesSymbol[] = ".swift2_protocol_conformances_start"; /// The symbol name in the image that identifies the beginning of the /// type metadata record table. static const char TypeMetadataRecordsSymbol[] = ".swift2_type_metadata_start"; /// Context arguments passed down from dl_iterate_phdr to its callback. struct InspectArgs { /// Symbol name to look up. const char *symbolName; /// Callback function to invoke with the metadata block. void (*addBlock)(const void *start, uintptr_t size); /// Set to true when initialize*Lookup() is called. bool didInitializeLookup; }; static InspectArgs ProtocolConformanceArgs = { ProtocolConformancesSymbol, addImageProtocolConformanceBlockCallback, false }; static InspectArgs TypeMetadataRecordArgs = { TypeMetadataRecordsSymbol, addImageTypeMetadataRecordBlockCallback, false }; // Extract the section information for a named section in an image. imageName // can be nullptr to specify the main executable. static SectionInfo getSectionInfo(const char *imageName, const char *sectionName) { SectionInfo sectionInfo = { 0, nullptr }; void *handle = dlopen(imageName, RTLD_LAZY | RTLD_NOLOAD); if (!handle) { fatalError(/* flags = */ 0, "dlopen() failed on `%s': %s", imageName, dlerror()); } void *symbol = dlsym(handle, sectionName); if (symbol) { // Extract the size of the section data from the head of the section. const char *section = reinterpret_cast<const char *>(symbol); memcpy(&sectionInfo.size, section, sizeof(uint64_t)); sectionInfo.data = section + sizeof(uint64_t); } dlclose(handle); return sectionInfo; } static int iteratePHDRCallback(struct dl_phdr_info *info, size_t size, void *data) { InspectArgs *inspectArgs = reinterpret_cast<InspectArgs *>(data); const char *fname = info->dlpi_name; // While dl_iterate_phdr() is in progress it holds a lock to prevent other // images being loaded. The initialize flag is set here inside the callback so // that addNewDSOImage() sees a consistent state. If it was set outside the // dl_iterate_phdr() call then it could result in images being missed or // added twice. inspectArgs->didInitializeLookup = true; if (fname == nullptr || fname[0] == '\0') { // The filename may be null for both the dynamic loader and main executable. // So ignore null image name here and explicitly add the main executable // in initialize*Lookup() to avoid adding the data twice. return 0; } SectionInfo block = getSectionInfo(fname, inspectArgs->symbolName); if (block.size > 0) { inspectArgs->addBlock(block.data, block.size); } return 0; } // Add the section information in an image specified by an address in that // image. static void addBlockInImage(const InspectArgs *inspectArgs, const void *addr) { const char *fname = nullptr; if (addr) { Dl_info info; if (dladdr(addr, &info) == 0 || info.dli_fname == nullptr) { return; } fname = info.dli_fname; } SectionInfo block = getSectionInfo(fname, inspectArgs->symbolName); if (block.size > 0) { inspectArgs->addBlock(block.data, block.size); } } static void initializeSectionLookup(InspectArgs *inspectArgs) { // Add section data in the main executable. addBlockInImage(inspectArgs, nullptr); // Search the loaded dls. This only searches the already // loaded ones. Any images loaded after this are processed by // addNewDSOImage() below. dl_iterate_phdr(iteratePHDRCallback, reinterpret_cast<void *>(inspectArgs)); } void swift::initializeProtocolConformanceLookup() { initializeSectionLookup(&ProtocolConformanceArgs); } void swift::initializeTypeMetadataRecordLookup() { initializeSectionLookup(&TypeMetadataRecordArgs); } // As ELF images are loaded, ImageInspectionInit:sectionDataInit() will call // addNewDSOImage() with an address in the image that can later be used via // dladdr() to dlopen() the image after the appropriate initialize*Lookup() // function has been called. SWIFT_RUNTIME_EXPORT void swift_addNewDSOImage(const void *addr) { if (ProtocolConformanceArgs.didInitializeLookup) { addBlockInImage(&ProtocolConformanceArgs, addr); } if (TypeMetadataRecordArgs.didInitializeLookup) { addBlockInImage(&TypeMetadataRecordArgs, addr); } } int swift::lookupSymbol(const void *address, SymbolInfo *info) { Dl_info dlinfo; if (dladdr(address, &dlinfo) == 0) { return 0; } info->fileName = dlinfo.dli_fname; info->baseAddress = dlinfo.dli_fbase; info->symbolName = dlinfo.dli_sname; info->symbolAddress = dlinfo.dli_saddr; return 1; } #endif // defined(__ELF__) || defined(__ANDROID__) <commit_msg>Remove cause of crash on Android<commit_after>//===--- ImageInspectionELF.cpp - ELF image inspection --------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// /// \file /// /// This file includes routines that interact with ld*.so on ELF-based platforms /// to extract runtime metadata embedded in dynamically linked ELF images /// generated by the Swift compiler. /// //===----------------------------------------------------------------------===// #if defined(__ELF__) || defined(__ANDROID__) #include "ImageInspection.h" #include "swift/Runtime/Debug.h" #include <dlfcn.h> #include <elf.h> #include <link.h> #include <string.h> using namespace swift; /// The symbol name in the image that identifies the beginning of the /// protocol conformances table. static const char ProtocolConformancesSymbol[] = ".swift2_protocol_conformances_start"; /// The symbol name in the image that identifies the beginning of the /// type metadata record table. static const char TypeMetadataRecordsSymbol[] = ".swift2_type_metadata_start"; /// Context arguments passed down from dl_iterate_phdr to its callback. struct InspectArgs { /// Symbol name to look up. const char *symbolName; /// Callback function to invoke with the metadata block. void (*addBlock)(const void *start, uintptr_t size); /// Set to true when initialize*Lookup() is called. bool didInitializeLookup; }; static InspectArgs ProtocolConformanceArgs = { ProtocolConformancesSymbol, addImageProtocolConformanceBlockCallback, false }; static InspectArgs TypeMetadataRecordArgs = { TypeMetadataRecordsSymbol, addImageTypeMetadataRecordBlockCallback, false }; // Extract the section information for a named section in an image. imageName // can be nullptr to specify the main executable. static SectionInfo getSectionInfo(const char *imageName, const char *sectionName) { SectionInfo sectionInfo = { 0, nullptr }; void *handle = dlopen(imageName, RTLD_LAZY | RTLD_NOLOAD); if (!handle) { #ifdef __ANDROID__ return sectionInfo; #else fatalError(/* flags = */ 0, "dlopen() failed on `%s': %s", imageName, dlerror()); #endif } void *symbol = dlsym(handle, sectionName); if (symbol) { // Extract the size of the section data from the head of the section. const char *section = reinterpret_cast<const char *>(symbol); memcpy(&sectionInfo.size, section, sizeof(uint64_t)); sectionInfo.data = section + sizeof(uint64_t); } dlclose(handle); return sectionInfo; } static int iteratePHDRCallback(struct dl_phdr_info *info, size_t size, void *data) { InspectArgs *inspectArgs = reinterpret_cast<InspectArgs *>(data); const char *fname = info->dlpi_name; // While dl_iterate_phdr() is in progress it holds a lock to prevent other // images being loaded. The initialize flag is set here inside the callback so // that addNewDSOImage() sees a consistent state. If it was set outside the // dl_iterate_phdr() call then it could result in images being missed or // added twice. inspectArgs->didInitializeLookup = true; if (fname == nullptr || fname[0] == '\0') { // The filename may be null for both the dynamic loader and main executable. // So ignore null image name here and explicitly add the main executable // in initialize*Lookup() to avoid adding the data twice. return 0; } SectionInfo block = getSectionInfo(fname, inspectArgs->symbolName); if (block.size > 0) { inspectArgs->addBlock(block.data, block.size); } return 0; } // Add the section information in an image specified by an address in that // image. static void addBlockInImage(const InspectArgs *inspectArgs, const void *addr) { const char *fname = nullptr; if (addr) { Dl_info info; if (dladdr(addr, &info) == 0 || info.dli_fname == nullptr) { return; } fname = info.dli_fname; } SectionInfo block = getSectionInfo(fname, inspectArgs->symbolName); if (block.size > 0) { inspectArgs->addBlock(block.data, block.size); } } static void initializeSectionLookup(InspectArgs *inspectArgs) { // Add section data in the main executable. addBlockInImage(inspectArgs, nullptr); // Search the loaded dls. This only searches the already // loaded ones. Any images loaded after this are processed by // addNewDSOImage() below. dl_iterate_phdr(iteratePHDRCallback, reinterpret_cast<void *>(inspectArgs)); } void swift::initializeProtocolConformanceLookup() { initializeSectionLookup(&ProtocolConformanceArgs); } void swift::initializeTypeMetadataRecordLookup() { initializeSectionLookup(&TypeMetadataRecordArgs); } // As ELF images are loaded, ImageInspectionInit:sectionDataInit() will call // addNewDSOImage() with an address in the image that can later be used via // dladdr() to dlopen() the image after the appropriate initialize*Lookup() // function has been called. SWIFT_RUNTIME_EXPORT void swift_addNewDSOImage(const void *addr) { if (ProtocolConformanceArgs.didInitializeLookup) { addBlockInImage(&ProtocolConformanceArgs, addr); } if (TypeMetadataRecordArgs.didInitializeLookup) { addBlockInImage(&TypeMetadataRecordArgs, addr); } } int swift::lookupSymbol(const void *address, SymbolInfo *info) { Dl_info dlinfo; if (dladdr(address, &dlinfo) == 0) { return 0; } info->fileName = dlinfo.dli_fname; info->baseAddress = dlinfo.dli_fbase; info->symbolName = dlinfo.dli_sname; info->symbolAddress = dlinfo.dli_saddr; return 1; } #endif // defined(__ELF__) || defined(__ANDROID__) <|endoftext|>
<commit_before>#pragma once #include "fwd.hpp" #include <string> #include <vector> #include <map> #include <boost/filesystem/path.hpp> #include <boost/variant/variant.hpp> #include <boost/optional.hpp> namespace configure { class ShellFormatter { protected: Build const& _build; public: ShellFormatter(Build const& b); virtual ~ShellFormatter(); public: virtual std::string operator()(ShellCommand const& command, std::string value) const; virtual std::string operator()(ShellCommand const& command, boost::filesystem::path const& value) const; virtual std::string operator()(ShellCommand const& command, Node const& value) const; }; // Dynamic shell argument class ShellArg { public: virtual ~ShellArg(); virtual std::vector<std::string> string(Build const& build, DependencyLink const& link, ShellFormatter const& formatter) const = 0; virtual std::string dump() const; }; // Store one shell command. class ShellCommand { public: typedef boost::variant< std::string, boost::filesystem::path, ShellArgPtr, NodePtr > Arg; typedef std::map<std::string, std::string> Environ; private: std::vector<Arg> _args; boost::optional<boost::filesystem::path> _working_directory; boost::optional<Environ> _env; public: ShellCommand() {} ShellCommand(ShellCommand&& other) : _args(std::move(other._args)) , _working_directory(std::move(other._working_directory)) , _env(std::move(other._env)) {} ShellCommand(ShellCommand const& other) : _args(other._args) , _working_directory(other._working_directory) , _env(other._env) {} ShellCommand& operator =(ShellCommand const& other) { if (this != &other) _args = other._args; return *this; } ShellCommand& operator =(ShellCommand&& other) { if (this != &other) _args = std::move(other._args); return *this; } ~ShellCommand(); // Raw arguments std::vector<Arg> const& args() const { return _args; } bool has_working_directory() const { return static_cast<bool>(_working_directory); } boost::filesystem::path const& working_directory() const { return *_working_directory; } void working_directory(boost::filesystem::path dir) { _working_directory = boost::in_place(std::move(dir)); } bool has_env() const { return static_cast<bool>(_env); } Environ const& env() const { return *_env; } void env(Environ value) { _env = boost::in_place(std::move(value)); } // Add one or more arguments. template<typename T, typename... Args> void append(T&& arg, Args&&... args) { _insert(std::forward<T>(arg)); this->append(std::forward<Args>(args)...); } // Extend arguments with a container. template<typename T> void extend(T&& arg) { for (auto&& el: std::forward<T>(arg)) this->append(el); // XXX use std::move() ? } // Generate a shell command. std::vector<std::string> string(Build const& build, DependencyLink const& link, ShellFormatter const& formatter) const; std::vector<std::string> string(Build const& build, DependencyLink const& link) const; // Dump command without any build context (for debugging purposes). std::vector<std::string> dump() const; private: void append() {} // End case template<typename T> void _insert(T&& arg) { _args.push_back(Arg(std::forward<T>(arg))); } void _insert(char const* str) { _args.push_back(std::string(str)); } }; } <commit_msg>Add missing include<commit_after>#pragma once #include "fwd.hpp" #include <string> #include <vector> #include <map> #include <boost/filesystem/path.hpp> #include <boost/variant/variant.hpp> #include <boost/utility/in_place_factory.hpp> #include <boost/optional.hpp> namespace configure { class ShellFormatter { protected: Build const& _build; public: ShellFormatter(Build const& b); virtual ~ShellFormatter(); public: virtual std::string operator()(ShellCommand const& command, std::string value) const; virtual std::string operator()(ShellCommand const& command, boost::filesystem::path const& value) const; virtual std::string operator()(ShellCommand const& command, Node const& value) const; }; // Dynamic shell argument class ShellArg { public: virtual ~ShellArg(); virtual std::vector<std::string> string(Build const& build, DependencyLink const& link, ShellFormatter const& formatter) const = 0; virtual std::string dump() const; }; // Store one shell command. class ShellCommand { public: typedef boost::variant< std::string, boost::filesystem::path, ShellArgPtr, NodePtr > Arg; typedef std::map<std::string, std::string> Environ; private: std::vector<Arg> _args; boost::optional<boost::filesystem::path> _working_directory; boost::optional<Environ> _env; public: ShellCommand() {} ShellCommand(ShellCommand&& other) : _args(std::move(other._args)) , _working_directory(std::move(other._working_directory)) , _env(std::move(other._env)) {} ShellCommand(ShellCommand const& other) : _args(other._args) , _working_directory(other._working_directory) , _env(other._env) {} ShellCommand& operator =(ShellCommand const& other) { if (this != &other) _args = other._args; return *this; } ShellCommand& operator =(ShellCommand&& other) { if (this != &other) _args = std::move(other._args); return *this; } ~ShellCommand(); // Raw arguments std::vector<Arg> const& args() const { return _args; } bool has_working_directory() const { return static_cast<bool>(_working_directory); } boost::filesystem::path const& working_directory() const { return *_working_directory; } void working_directory(boost::filesystem::path dir) { _working_directory = boost::in_place(std::move(dir)); } bool has_env() const { return static_cast<bool>(_env); } Environ const& env() const { return *_env; } void env(Environ value) { _env = boost::in_place(std::move(value)); } // Add one or more arguments. template<typename T, typename... Args> void append(T&& arg, Args&&... args) { _insert(std::forward<T>(arg)); this->append(std::forward<Args>(args)...); } // Extend arguments with a container. template<typename T> void extend(T&& arg) { for (auto&& el: std::forward<T>(arg)) this->append(el); // XXX use std::move() ? } // Generate a shell command. std::vector<std::string> string(Build const& build, DependencyLink const& link, ShellFormatter const& formatter) const; std::vector<std::string> string(Build const& build, DependencyLink const& link) const; // Dump command without any build context (for debugging purposes). std::vector<std::string> dump() const; private: void append() {} // End case template<typename T> void _insert(T&& arg) { _args.push_back(Arg(std::forward<T>(arg))); } void _insert(char const* str) { _args.push_back(std::string(str)); } }; } <|endoftext|>
<commit_before>/* * KernelConn.cpp * * Created on: Aug 6, 2009 * Author: gkenyon */ #include "KernelConn.hpp" #include <assert.h> #include "../io/io.h" namespace PV { KernelConn::KernelConn() { initialize_base(); } KernelConn::KernelConn(const char * name, HyPerCol * hc, HyPerLayer * pre, HyPerLayer * post, int channel) { initialize_base(); initialize(name, hc, pre, post, channel); } KernelConn::KernelConn(const char * name, HyPerCol * hc, HyPerLayer * pre, HyPerLayer * post) { initialize_base(); initialize(name, hc, pre, post, channel, NULL); // use default channel } // provide filename or set to NULL KernelConn::KernelConn(const char * name, HyPerCol * hc, HyPerLayer * pre, HyPerLayer * post, int channel, const char * filename) { initialize_base(); initialize(name, hc, pre, post, channel, filename); } int KernelConn::initialize_base() { kernelPatches = NULL; return HyPerConn::initialize_base(); } PVPatch ** KernelConn::allocWeights(PVPatch ** patches, int nPatches, int nxPatch, int nyPatch, int nfPatch) { const int arbor = 0; int numKernelPatches = numDataPatches(arbor); PVPatch ** kernel_patches = (PVPatch**) calloc(sizeof(PVPatch*), numKernelPatches); assert(kernel_patches != NULL); for (int kernelIndex = 0; kernelIndex < numKernelPatches; kernelIndex++) { kernel_patches[kernelIndex] = pvpatch_inplace_new(nxPatch, nyPatch, nfPatch); assert(kernel_patches[kernelIndex] != NULL ); } for (int patchIndex = 0; patchIndex < nPatches; patchIndex++) { patches[patchIndex] = pvpatch_new(nxPatch, nyPatch, nfPatch); } for (int patchIndex = 0; patchIndex < nPatches; patchIndex++) { int kernelIndex = patchIndexToKernelIndex(patchIndex); patches[patchIndex]->data = kernel_patches[kernelIndex]->data; } return kernel_patches; } PVPatch ** KernelConn::createWeights(PVPatch ** patches, int nPatches, int nxPatch, int nyPatch, int nfPatch) { // could create only a single patch with following call // return createPatches(numAxonalArborLists, nxp, nyp, nfp); assert(numAxonalArborLists == 1); // TODO IMPORTANT ################# free memory in patches as well // GTK: call delete weights? if (patches != NULL) { free(patches); } patches = (PVPatch**) calloc(sizeof(PVPatch*), nPatches); assert(patches != NULL); // TODO - allocate space for them all at once (inplace) kernelPatches = allocWeights(patches, nPatches, nxPatch, nyPatch, nfPatch); return patches; } int KernelConn::deleteWeights() { const int arbor = 0; for (int k = 0; k < numDataPatches(arbor); k++) { pvpatch_inplace_delete(kernelPatches[k]); } free(kernelPatches); return HyPerConn::deleteWeights(); } PVPatch ** KernelConn::initializeWeights(PVPatch ** patches, int numPatches, const char * filename) { int arbor = 0; HyPerConn::initializeWeights(kernelPatches, numDataPatches(arbor), filename); return wPatches[arbor]; } PVPatch ** KernelConn::readWeights(PVPatch ** patches, int numPatches, const char * filename) { HyPerConn::readWeights(patches, numPatches, filename); return HyPerConn::normalizeWeights(patches, numPatches); } int KernelConn::numDataPatches(int arbor) { int xScaleFac = (post->clayer->xScale > pre->clayer->xScale) ? pow(2, post->clayer->xScale - pre->clayer->xScale) : 1; int yScaleFac = (post->clayer->yScale > pre->clayer->yScale) ? pow(2, post->clayer->yScale - pre->clayer->yScale) : 1; int numKernelPatches = pre->clayer->numFeatures * xScaleFac * yScaleFac; return numKernelPatches; } // k is ignored, writes all weights int KernelConn::writeWeights(float time, bool last) { const int arbor = 0; const int numPatches = numDataPatches(arbor); return HyPerConn::writeWeights(kernelPatches, numPatches, NULL, time, last); } int KernelConn::kernelIndexToPatchIndex(int kernelIndex){ int patchIndex; int xScaleFac = (post->clayer->xScale > pre->clayer->xScale) ? pow(2, post->clayer->xScale - pre->clayer->xScale) : 1; int yScaleFac = (post->clayer->yScale > pre->clayer->yScale) ? pow(2, post->clayer->yScale - pre->clayer->yScale) : 1; int nfPre = pre->clayer->numFeatures; int kxPre = kxPos( kernelIndex, xScaleFac, yScaleFac, nfPre); int kyPre = kyPos( kernelIndex, xScaleFac, yScaleFac, nfPre); int kfPre = featureIndex( kernelIndex, xScaleFac, yScaleFac, nfPre); int nxPre = pre->clayer->loc.nx; int nyPre = pre->clayer->loc.ny; patchIndex = kIndex( kxPre, kyPre, kfPre, nxPre, nyPre, nfPre); return patchIndex; } // many to one mapping from weight patches to kernels int KernelConn::patchIndexToKernelIndex(int patchIndex){ int kernelIndex; int nxPre = pre->clayer->loc.nx; int nyPre = pre->clayer->loc.ny; int nfPre = pre->clayer->numFeatures; int kxPre = kxPos( patchIndex, nxPre, nyPre, nfPre); int kyPre = kyPos( patchIndex, nxPre, nyPre, nfPre); int kfPre = featureIndex( patchIndex, nxPre, nyPre, nfPre); int xScaleFac = (post->clayer->xScale > pre->clayer->xScale) ? pow(2, post->clayer->xScale - pre->clayer->xScale) : 1; int yScaleFac = (post->clayer->yScale > pre->clayer->yScale) ? pow(2, post->clayer->yScale - pre->clayer->yScale) : 1; kxPre = kxPre % xScaleFac; kyPre = kyPre % yScaleFac; kernelIndex = kIndex( kxPre, kyPre, kfPre, xScaleFac, yScaleFac, nfPre); return kernelIndex; } } // namespace PV <commit_msg>added local variable for ease in debugging<commit_after>/* * KernelConn.cpp * * Created on: Aug 6, 2009 * Author: gkenyon */ #include "KernelConn.hpp" #include <assert.h> #include "../io/io.h" namespace PV { KernelConn::KernelConn() { initialize_base(); } KernelConn::KernelConn(const char * name, HyPerCol * hc, HyPerLayer * pre, HyPerLayer * post, int channel) { initialize_base(); initialize(name, hc, pre, post, channel); } KernelConn::KernelConn(const char * name, HyPerCol * hc, HyPerLayer * pre, HyPerLayer * post) { initialize_base(); initialize(name, hc, pre, post, channel, NULL); // use default channel } // provide filename or set to NULL KernelConn::KernelConn(const char * name, HyPerCol * hc, HyPerLayer * pre, HyPerLayer * post, int channel, const char * filename) { initialize_base(); initialize(name, hc, pre, post, channel, filename); } int KernelConn::initialize_base() { kernelPatches = NULL; return HyPerConn::initialize_base(); } PVPatch ** KernelConn::allocWeights(PVPatch ** patches, int nPatches, int nxPatch, int nyPatch, int nfPatch) { const int arbor = 0; int numKernelPatches = numDataPatches(arbor); PVPatch ** kernel_patches = (PVPatch**) calloc(sizeof(PVPatch*), numKernelPatches); assert(kernel_patches != NULL); for (int kernelIndex = 0; kernelIndex < numKernelPatches; kernelIndex++) { kernel_patches[kernelIndex] = pvpatch_inplace_new(nxPatch, nyPatch, nfPatch); assert(kernel_patches[kernelIndex] != NULL ); } for (int patchIndex = 0; patchIndex < nPatches; patchIndex++) { patches[patchIndex] = pvpatch_new(nxPatch, nyPatch, nfPatch); } for (int patchIndex = 0; patchIndex < nPatches; patchIndex++) { int kernelIndex = patchIndexToKernelIndex(patchIndex); patches[patchIndex]->data = kernel_patches[kernelIndex]->data; } return kernel_patches; } PVPatch ** KernelConn::createWeights(PVPatch ** patches, int nPatches, int nxPatch, int nyPatch, int nfPatch) { // could create only a single patch with following call // return createPatches(numAxonalArborLists, nxp, nyp, nfp); assert(numAxonalArborLists == 1); // TODO IMPORTANT ################# free memory in patches as well // GTK: call delete weights? if (patches != NULL) { free(patches); } patches = (PVPatch**) calloc(sizeof(PVPatch*), nPatches); assert(patches != NULL); // TODO - allocate space for them all at once (inplace) kernelPatches = allocWeights(patches, nPatches, nxPatch, nyPatch, nfPatch); return patches; } int KernelConn::deleteWeights() { const int arbor = 0; for (int k = 0; k < numDataPatches(arbor); k++) { pvpatch_inplace_delete(kernelPatches[k]); } free(kernelPatches); return HyPerConn::deleteWeights(); } PVPatch ** KernelConn::initializeWeights(PVPatch ** patches, int numPatches, const char * filename) { int arbor = 0; int numKernelPatches = numDataPatches(arbor); HyPerConn::initializeWeights(kernelPatches, numKernelPatches, filename); return wPatches[arbor]; } PVPatch ** KernelConn::readWeights(PVPatch ** patches, int numPatches, const char * filename) { HyPerConn::readWeights(patches, numPatches, filename); return HyPerConn::normalizeWeights(patches, numPatches); } int KernelConn::numDataPatches(int arbor) { int xScaleFac = (post->clayer->xScale > pre->clayer->xScale) ? pow(2, post->clayer->xScale - pre->clayer->xScale) : 1; int yScaleFac = (post->clayer->yScale > pre->clayer->yScale) ? pow(2, post->clayer->yScale - pre->clayer->yScale) : 1; int numKernelPatches = pre->clayer->numFeatures * xScaleFac * yScaleFac; return numKernelPatches; } // k is ignored, writes all weights int KernelConn::writeWeights(float time, bool last) { const int arbor = 0; const int numPatches = numDataPatches(arbor); return HyPerConn::writeWeights(kernelPatches, numPatches, NULL, time, last); } int KernelConn::kernelIndexToPatchIndex(int kernelIndex){ int patchIndex; int xScaleFac = (post->clayer->xScale > pre->clayer->xScale) ? pow(2, post->clayer->xScale - pre->clayer->xScale) : 1; int yScaleFac = (post->clayer->yScale > pre->clayer->yScale) ? pow(2, post->clayer->yScale - pre->clayer->yScale) : 1; int nfPre = pre->clayer->numFeatures; int kxPre = kxPos( kernelIndex, xScaleFac, yScaleFac, nfPre); int kyPre = kyPos( kernelIndex, xScaleFac, yScaleFac, nfPre); int kfPre = featureIndex( kernelIndex, xScaleFac, yScaleFac, nfPre); int nxPre = pre->clayer->loc.nx; int nyPre = pre->clayer->loc.ny; patchIndex = kIndex( kxPre, kyPre, kfPre, nxPre, nyPre, nfPre); return patchIndex; } // many to one mapping from weight patches to kernels int KernelConn::patchIndexToKernelIndex(int patchIndex){ int kernelIndex; int nxPre = pre->clayer->loc.nx; int nyPre = pre->clayer->loc.ny; int nfPre = pre->clayer->numFeatures; int kxPre = kxPos( patchIndex, nxPre, nyPre, nfPre); int kyPre = kyPos( patchIndex, nxPre, nyPre, nfPre); int kfPre = featureIndex( patchIndex, nxPre, nyPre, nfPre); int xScaleFac = (post->clayer->xScale > pre->clayer->xScale) ? pow(2, post->clayer->xScale - pre->clayer->xScale) : 1; int yScaleFac = (post->clayer->yScale > pre->clayer->yScale) ? pow(2, post->clayer->yScale - pre->clayer->yScale) : 1; kxPre = kxPre % xScaleFac; kyPre = kyPre % yScaleFac; kernelIndex = kIndex( kxPre, kyPre, kfPre, xScaleFac, yScaleFac, nfPre); return kernelIndex; } } // namespace PV <|endoftext|>
<commit_before>#include<bits/stdc++.h> #define uint unsigned int using namespace std; template<size_t Sigma> class SAM{ public: struct Node{ Node *next,*ch[Sigma]; uint max; Node(const int maxx):ch(),next(NULL),max(maxx){} inline uint getMin(){ return next->max+1; } }*root,*last; inline void prelude(){ root=last=new Node; } inline Node *extend(int c){ Node *u=new Node(last->max+1),*v=last; for(;v&&!v->ch[c];v=v->next) v->ch[c]=u; if(!v) u->next=root; else if(v->ch[c]->max==v->max+1) u->next=v->ch[c]; else{ Node *n=new Node(v->max+1),*o=v->ch[c]; copy(o->ch,o->ch+Sigma,n->ch); n->next=o->next; o->next=u->next=n; for(;v&&v->ch[c]==o;v=v->next) v->ch[c]=n; } last=u; return u; } }; <commit_msg>Update SAM.cpp<commit_after>#include<bits/stdc++.h> #define MAXN 10000005 using namespace std; template<size_t Sigma> struct SAM{ struct Node{ Node *next,*ch[Sigma]; int max; Node(int max=0):max(max),next(NULL),ch(){} }*root,*last; inline void prelude(){ root=last=new Node; } inline Node *extend(int c){ Node *u=new Node(last->max+1),*v=last; for(;v&&!v->ch[c];v=v->next) v->ch[c]=u; if(!v) u->next=root; else if(v->ch[c]->max==v->max+1) u->next=v->ch[c]; else{ Node *n=new Node(v->max+1),*o=v->ch[c]; copy(o->ch,o->ch+Sigma,n->ch); n->next=o->next; u->next=o->next=n; for(;v&&v->ch[c]==o;v=v->next) v->ch[c]=n; } last=u; return u; } }; SAM<4> sss; inline int idx(char ch){ switch(ch){ case 'N': return 0; case 'S': return 1; case 'W': return 2; case 'E': return 3; default: return -1; } } inline int solve(char *s){ int len=strlen(s); SAM<4>::Node *v=sss.root; for (int i=0;i<len;++i){ int c=idx(s[i]); if(v->ch[c]) v=v->ch[c]; else return i; } return len; } int main(){ int n,m; static char s[MAXN+1]; scanf("%d %d\n%s",&n,&m,s); sss.prelude(); for(register int i=0;i<n;++i) sss.extend(idx(s[i])); while(m--){ static char s[MAXN+1]; scanf("%s",s); printf("%d\n",solve(s)); } return 0; } <|endoftext|>
<commit_before>/* -*- mode: c++; c-default-style: "google"; indent-tabs-mode: nil -*- */ /* ------------------------------------------------------------------------- ATS License: see $ATS_DIR/COPYRIGHT Author: Ethan Coon Interface for the Coordinator. Coordinator is basically just a class to hold the cycle driver, which runs the overall, top level timestep loop. It instantiates states, ensures they are initialized, and runs the timestep loop including Vis and restart/checkpoint dumps. It contains one and only one PK -- most likely this PK is an MPC of some type -- to do the actual work. ------------------------------------------------------------------------- */ #ifndef _COORDINATOR_HH_ #define _COORDINATOR_HH_ #include "Teuchos_RCP.hpp" #include "Teuchos_ParameterList.hpp" #include "Teuchos_VerboseObject.hpp" #include "Epetra_MpiComm.h" #include "tree_vector.hh" #include "state.hh" #include "PK.hh" #include "pk_factory.hh" #include "ObservationData.H" #include "unstructured_observations.hh" #include "visualization.hh" #include "checkpoint.hh" namespace Amanzi { class Coordinator : public VerboseObject { public: Coordinator(Teuchos::ParameterList parameter_list, Teuchos::RCP<Amanzi::AmanziMesh::Mesh>& mesh, Epetra_MpiComm* comm ); // Amanzi::ObservationData& output_observations); // PK methods void initialize(); void cycle_driver(); private: void coordinator_init(); void read_parameter_list(); // PK container and factory Teuchos::RCP<PK> pk_; // states Teuchos::RCP<State> S_; Teuchos::RCP<State> S_inter_; Teuchos::RCP<State> S_next_; Teuchos::RCP<TreeVector> soln_; // misc setup information Teuchos::ParameterList parameter_list_; Teuchos::RCP<AmanziMesh::Mesh> mesh_; Teuchos::ParameterList coordinator_plist_; double t0_, t1_; double max_dt_, min_dt_; int end_cycle_; // Epetra communicator Epetra_MpiComm* comm_; // observations // ObservationData& output_observations_; // Teuchos::RCP<UnstructuredObservations> observations_; // vis and checkpointing std::vector<Teuchos::RCP<Visualization> > visualization_; Teuchos::RCP<Checkpoint> checkpoint_; // fancy OS Teuchos::RCP<Teuchos::FancyOStream> out_; Teuchos::EVerbosityLevel verbosity_; }; } // close namespace Amanzi #endif <commit_msg>bug fix in last commit<commit_after>/* -*- mode: c++; c-default-style: "google"; indent-tabs-mode: nil -*- */ /* ------------------------------------------------------------------------- ATS License: see $ATS_DIR/COPYRIGHT Author: Ethan Coon Interface for the Coordinator. Coordinator is basically just a class to hold the cycle driver, which runs the overall, top level timestep loop. It instantiates states, ensures they are initialized, and runs the timestep loop including Vis and restart/checkpoint dumps. It contains one and only one PK -- most likely this PK is an MPC of some type -- to do the actual work. ------------------------------------------------------------------------- */ #ifndef _COORDINATOR_HH_ #define _COORDINATOR_HH_ #include "Teuchos_RCP.hpp" #include "Teuchos_ParameterList.hpp" #include "Teuchos_VerboseObject.hpp" #include "Epetra_MpiComm.h" #include "tree_vector.hh" #include "state.hh" #include "PK.hh" #include "pk_factory.hh" #include "ObservationData.H" #include "unstructured_observations.hh" #include "visualization.hh" #include "checkpoint.hh" namespace Amanzi { class Coordinator : public Teuchos::VerboseObject<Coordinator> { public: Coordinator(Teuchos::ParameterList parameter_list, Teuchos::RCP<Amanzi::AmanziMesh::Mesh>& mesh, Epetra_MpiComm* comm ); // Amanzi::ObservationData& output_observations); // PK methods void initialize(); void cycle_driver(); private: void coordinator_init(); void read_parameter_list(); // PK container and factory Teuchos::RCP<PK> pk_; // states Teuchos::RCP<State> S_; Teuchos::RCP<State> S_inter_; Teuchos::RCP<State> S_next_; Teuchos::RCP<TreeVector> soln_; // misc setup information Teuchos::ParameterList parameter_list_; Teuchos::RCP<AmanziMesh::Mesh> mesh_; Teuchos::ParameterList coordinator_plist_; double t0_, t1_; double max_dt_, min_dt_; int end_cycle_; // Epetra communicator Epetra_MpiComm* comm_; // observations // ObservationData& output_observations_; // Teuchos::RCP<UnstructuredObservations> observations_; // vis and checkpointing std::vector<Teuchos::RCP<Visualization> > visualization_; Teuchos::RCP<Checkpoint> checkpoint_; // fancy OS Teuchos::RCP<Teuchos::FancyOStream> out_; Teuchos::EVerbosityLevel verbosity_; }; } // close namespace Amanzi #endif <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/usr/isteps/istep10/call_proc_build_smp.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #include <errl/errlentry.H> #include <errl/errludtarget.H> #include <errl/errlmanager.H> #include <isteps/hwpisteperror.H> #include <initservice/isteps_trace.H> #include <fsi/fsiif.H> // targeting support #include <targeting/common/commontargeting.H> #include <targeting/common/utilFilter.H> #include <targeting/common/target.H> #include <pbusLinkSvc.H> #include <fapi2/target.H> #include <fapi2/plat_hwp_invoker.H> #include <intr/interrupt.H> //@TODO RTC:150562 - Remove when BAR setting handled by INTRRP #include <devicefw/userif.H> #include <p9_build_smp.H> using namespace ISTEP_ERROR; using namespace ISTEP; using namespace TARGETING; using namespace ERRORLOG; namespace ISTEP_10 { void* call_proc_build_smp (void *io_pArgs) { IStepError l_StepError; errlHndl_t l_errl = NULL; TARGETING::TargetHandleList l_cpuTargetList; getAllChips(l_cpuTargetList, TYPE_PROC); // // Identify the master processor // TARGETING::Target * l_masterProc = NULL; (void)TARGETING::targetService().masterProcChipTargetHandle( l_masterProc ); std::vector<fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>> l_procList; // Loop through all proc chips for (const auto & curproc: l_cpuTargetList) { if (curproc != l_masterProc) { //---PHBBAR - PSI Host Bridge Base Address Register //Get base BAR Value from attribute uint64_t l_baseBarValue = curproc-> getAttr<TARGETING::ATTR_PSI_BRIDGE_BASE_ADDR>(); uint64_t l_barValue = l_baseBarValue; uint64_t size = sizeof(l_barValue); l_errl = deviceWrite(curproc, &l_barValue, size, DEVICE_SCOM_ADDRESS(0x0501290A)); if(l_errl) { TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,ERR_MRK "Unable to set PSI BRIDGE BAR Address"); break; } //Now set the enable bit l_barValue += 0x0000000000000001ULL; //PSI BRIDGE BAR ENABLE Bit size = sizeof(l_barValue); TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "Setting PSI BRIDGE Bar enable value for Target with " "huid: 0x%x, PSI BRIDGE BAR value: 0x%016lx", TARGETING::get_huid(curproc),l_barValue); l_errl = deviceWrite(curproc, &l_barValue, size, DEVICE_SCOM_ADDRESS(0x0501290A)); if(l_errl) { TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, ERR_MRK"Error enabling FSP BAR"); break; } //---FSPBAR - FSP Base Address Register //Get base BAR Value from attribute l_baseBarValue = curproc-> getAttr<TARGETING::ATTR_FSP_BASE_ADDR>(); TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "Setting FSP Bar enable value for Target with " "huid: 0x%x, FSP BAR value: 0x%016lx", TARGETING::get_huid(curproc),l_baseBarValue); l_errl = deviceWrite(curproc, &l_baseBarValue, size, DEVICE_SCOM_ADDRESS(0x0501290B)); if(l_errl) { TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, ERR_MRK"Error enabling FSP BAR"); break; } } const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> l_fapi2_proc_target (curproc); l_procList.push_back(l_fapi2_proc_target); } if(l_errl) { l_StepError.addErrorDetails( l_errl); errlCommit( l_errl, ISTEP_COMP_ID ); } TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "call_proc_build_smp entry" ); const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> l_fapi2_master_proc (l_masterProc); do { FAPI_INVOKE_HWP( l_errl, p9_build_smp, l_procList, l_fapi2_master_proc, SMP_ACTIVATE_PHASE1 ); if(l_errl) { TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "ERROR : call p9_build_smp, PLID=0x%x", l_errl->plid() ); // Create IStep error log and cross reference error that occurred l_StepError.addErrorDetails(l_errl); // Commit error errlCommit( l_errl, HWPF_COMP_ID ); break; } // At the point where we can now change the proc chips to use // XSCOM rather than SBESCOM which is the default. TARGETING::TargetHandleList procChips; getAllChips(procChips, TYPE_PROC); TARGETING::TargetHandleList::iterator curproc = procChips.begin(); // Loop through all proc chips while(curproc != procChips.end()) { TARGETING::Target* l_proc_target = *curproc; if (l_proc_target != l_masterProc) { //Enable PSIHB Interrupts for slave proc -- moved from above l_errl = INTR::enablePsiIntr(l_proc_target); if(l_errl) { // capture the target data in the elog ErrlUserDetailsTarget(l_proc_target).addToLog( l_errl ); break; } } // If the proc chip supports xscom.. if (l_proc_target->getAttr<ATTR_PRIMARY_CAPABILITIES>() .supportsXscom) { ScomSwitches l_switches = l_proc_target->getAttr<ATTR_SCOM_SWITCHES>(); // If Xscom is not already enabled. if ((l_switches.useXscom != 1) || (l_switches.useSbeScom != 0)) { l_switches.useSbeScom = 0; l_switches.useXscom = 1; // Turn off SBE scom and turn on Xscom. l_proc_target->setAttr<ATTR_SCOM_SWITCHES>(l_switches); // Reset the FSI2OPB logic on the new chips l_errl = FSI::resetPib2Opb(l_proc_target); if(l_errl) { TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "ERROR : resetPib2Opb on %.8X", TARGETING::get_huid(l_proc_target)); // Create IStep error log and // cross reference error that occurred l_StepError.addErrorDetails(l_errl); // Commit error errlCommit( l_errl, HWPF_COMP_ID ); break; } } } ++curproc; } } while (0); TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "call_proc_build_smp exit" ); // end task, returning any errorlogs to IStepDisp return l_StepError.getErrorHandle(); } }; <commit_msg>Secure Boot: Enable PSI interrupts after XSCOM switchover<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/usr/isteps/istep10/call_proc_build_smp.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #include <errl/errlentry.H> #include <errl/errludtarget.H> #include <errl/errlmanager.H> #include <isteps/hwpisteperror.H> #include <initservice/isteps_trace.H> #include <fsi/fsiif.H> // targeting support #include <targeting/common/commontargeting.H> #include <targeting/common/utilFilter.H> #include <targeting/common/target.H> #include <pbusLinkSvc.H> #include <fapi2/target.H> #include <fapi2/plat_hwp_invoker.H> #include <intr/interrupt.H> //@TODO RTC:150562 - Remove when BAR setting handled by INTRRP #include <devicefw/userif.H> #include <p9_build_smp.H> using namespace ISTEP_ERROR; using namespace ISTEP; using namespace TARGETING; using namespace ERRORLOG; namespace ISTEP_10 { void* call_proc_build_smp (void *io_pArgs) { IStepError l_StepError; errlHndl_t l_errl = NULL; TARGETING::TargetHandleList l_cpuTargetList; getAllChips(l_cpuTargetList, TYPE_PROC); // // Identify the master processor // TARGETING::Target * l_masterProc = NULL; (void)TARGETING::targetService().masterProcChipTargetHandle( l_masterProc ); std::vector<fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>> l_procList; // Loop through all proc chips for (const auto & curproc: l_cpuTargetList) { if (curproc != l_masterProc) { //---PHBBAR - PSI Host Bridge Base Address Register //Get base BAR Value from attribute uint64_t l_baseBarValue = curproc-> getAttr<TARGETING::ATTR_PSI_BRIDGE_BASE_ADDR>(); uint64_t l_barValue = l_baseBarValue; uint64_t size = sizeof(l_barValue); l_errl = deviceWrite(curproc, &l_barValue, size, DEVICE_SCOM_ADDRESS(0x0501290A)); if(l_errl) { TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,ERR_MRK "Unable to set PSI BRIDGE BAR Address"); break; } //Now set the enable bit l_barValue += 0x0000000000000001ULL; //PSI BRIDGE BAR ENABLE Bit size = sizeof(l_barValue); TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "Setting PSI BRIDGE Bar enable value for Target with " "huid: 0x%x, PSI BRIDGE BAR value: 0x%016lx", TARGETING::get_huid(curproc),l_barValue); l_errl = deviceWrite(curproc, &l_barValue, size, DEVICE_SCOM_ADDRESS(0x0501290A)); if(l_errl) { TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, ERR_MRK"Error enabling FSP BAR"); break; } //---FSPBAR - FSP Base Address Register //Get base BAR Value from attribute l_baseBarValue = curproc-> getAttr<TARGETING::ATTR_FSP_BASE_ADDR>(); TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "Setting FSP Bar enable value for Target with " "huid: 0x%x, FSP BAR value: 0x%016lx", TARGETING::get_huid(curproc),l_baseBarValue); l_errl = deviceWrite(curproc, &l_baseBarValue, size, DEVICE_SCOM_ADDRESS(0x0501290B)); if(l_errl) { TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, ERR_MRK"Error enabling FSP BAR"); break; } } const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> l_fapi2_proc_target (curproc); l_procList.push_back(l_fapi2_proc_target); } if(l_errl) { l_StepError.addErrorDetails( l_errl); errlCommit( l_errl, ISTEP_COMP_ID ); } TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "call_proc_build_smp entry" ); const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> l_fapi2_master_proc (l_masterProc); do { FAPI_INVOKE_HWP( l_errl, p9_build_smp, l_procList, l_fapi2_master_proc, SMP_ACTIVATE_PHASE1 ); if(l_errl) { TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "ERROR : call p9_build_smp, PLID=0x%x", l_errl->plid() ); // Create IStep error log and cross reference error that occurred l_StepError.addErrorDetails(l_errl); // Commit error errlCommit( l_errl, HWPF_COMP_ID ); break; } // At the point where we can now change the proc chips to use // XSCOM rather than SBESCOM which is the default. TARGETING::TargetHandleList procChips; getAllChips(procChips, TYPE_PROC); TARGETING::TargetHandleList::iterator curproc = procChips.begin(); // Loop through all proc chips while(curproc != procChips.end()) { TARGETING::Target* l_proc_target = *curproc; // If the proc chip supports xscom.. if (l_proc_target->getAttr<ATTR_PRIMARY_CAPABILITIES>() .supportsXscom) { ScomSwitches l_switches = l_proc_target->getAttr<ATTR_SCOM_SWITCHES>(); // If Xscom is not already enabled. if ((l_switches.useXscom != 1) || (l_switches.useSbeScom != 0)) { l_switches.useSbeScom = 0; l_switches.useXscom = 1; // Turn off SBE scom and turn on Xscom. l_proc_target->setAttr<ATTR_SCOM_SWITCHES>(l_switches); // Reset the FSI2OPB logic on the new chips l_errl = FSI::resetPib2Opb(l_proc_target); if(l_errl) { TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "ERROR : resetPib2Opb on %.8X", TARGETING::get_huid(l_proc_target)); // Create IStep error log and // cross reference error that occurred l_StepError.addErrorDetails(l_errl); // Commit error errlCommit( l_errl, HWPF_COMP_ID ); break; } } } if (l_proc_target != l_masterProc) { //Enable PSIHB Interrupts for slave proc -- moved from above l_errl = INTR::enablePsiIntr(l_proc_target); if(l_errl) { // capture the target data in the elog ErrlUserDetailsTarget(l_proc_target).addToLog( l_errl ); break; } } ++curproc; } } while (0); TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "call_proc_build_smp exit" ); // end task, returning any errorlogs to IStepDisp return l_StepError.getErrorHandle(); } }; <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999 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/>. */ /** * $Log$ * Revision 1.1 1999/12/17 22:24:03 rahulj * Added missing UnixWare files to the repository. * * Created by Ron Record (rr@sco.com) based on SolarisDefs * 13-Nov-1999 */ // --------------------------------------------------------------------------- // UnixWare runs in little endian mode // --------------------------------------------------------------------------- #define ENDIANMODE_LITTLW typedef void* FileHandle; #ifndef UNIXWARE #define UNIXWARE #endif <commit_msg>Fixed the typo in Little endian #define.<commit_after>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999 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/>. */ /** * $Log$ * Revision 1.2 1999/12/17 23:31:29 rahulj * Fixed the typo in Little endian #define. * * Revision 1.1 1999/12/17 22:24:03 rahulj * Added missing UnixWare files to the repository. * * Created by Ron Record (rr@sco.com) based on SolarisDefs * 13-Nov-1999 */ // --------------------------------------------------------------------------- // UnixWare runs in little endian mode // --------------------------------------------------------------------------- #define ENDIANMODE_LITTLE typedef void* FileHandle; #ifndef UNIXWARE #define UNIXWARE #endif <|endoftext|>
<commit_before>#include <string> #include <iostream> using namespace std #include "StudentTestScores.h" #include "StudentTestScores.cpp" int main(){ return 0; } <commit_msg>Update test.cpp<commit_after>#include <string> #include <iostream> using namespace std; #include "StudentTestScores.h" int main(){ StudentTestScores x("joe", 4); cin >> x; StudentTestScores y("Chris"); cout << y; y=x; cout << x; x.addTestScore(79); cout << x; cout << y; char ch; cin >> ch; return 0; } <|endoftext|>
<commit_before>// // Copyright (c) 2017 The Khronos Group Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "testBase.h" #if !defined(_WIN32) #include <unistd.h> #endif const char *sample_async_kernel[] = { "__kernel void sample_test(__global float *src, __global int *dst)\n" "{\n" " int tid = get_global_id(0);\n" "\n" " dst[tid] = (int)src[tid];\n" "\n" "}\n" }; volatile int buildNotificationSent; void CL_CALLBACK test_notify_build_complete( cl_program program, void *userData ) { if( userData == NULL || strcmp( (char *)userData, "userData" ) != 0 ) { log_error( "ERROR: User data passed in to build notify function was not correct!\n" ); buildNotificationSent = -1; } else buildNotificationSent = 1; log_info( "\n <-- program successfully built\n" ); } int test_async_build(cl_device_id deviceID, cl_context context, cl_command_queue queue, int num_elements) { int error; cl_program program; cl_build_status status; buildNotificationSent = 0; /* First, test by doing the slow method of the individual calls */ error = create_single_kernel_helper_create_program(context, &program, 1, sample_async_kernel); test_error(error, "Unable to create program from source"); /* Compile the program */ error = clBuildProgram( program, 1, &deviceID, NULL, test_notify_build_complete, (void *)"userData" ); test_error( error, "Unable to build program source" ); /* Wait for build to complete (just keep polling, since we're just a test */ if( ( error = clGetProgramBuildInfo( program, deviceID, CL_PROGRAM_BUILD_STATUS, sizeof( status ), &status, NULL ) ) != CL_SUCCESS ) { print_error( error, "Unable to get program build status" ); return -1; } while( (int)status == CL_BUILD_IN_PROGRESS ) { log_info( "\n -- still waiting for build... (status is %d)", status ); sleep( 1 ); error = clGetProgramBuildInfo( program, deviceID, CL_PROGRAM_BUILD_STATUS, sizeof( status ), &status, NULL ); test_error( error, "Unable to get program build status" ); } if( status != CL_BUILD_SUCCESS ) { log_error( "ERROR: build failed! (status: %d)\n", (int)status ); return -1; } if( buildNotificationSent == 0 ) { log_error( "ERROR: Async build completed, but build notification was not sent!\n" ); return -1; } error = clReleaseProgram( program ); test_error( error, "Unable to release program object" ); return 0; } <commit_msg>Improve async build callback testing (#797)<commit_after>// // Copyright (c) 2017-2020 The Khronos Group Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "testBase.h" #if !defined(_WIN32) #include <unistd.h> #endif #include <atomic> #include <string> namespace { const char *sample_async_kernel[] = { "__kernel void sample_test(__global float *src, __global int *dst)\n" "{\n" " size_t tid = get_global_id(0);\n" "\n" " dst[tid] = (int)src[tid];\n" "\n" "}\n" }; const char *sample_async_kernel_error[] = { "__kernel void sample_test(__global float *src, __global int *dst)\n" "{\n" " size_t tid = get_global_id(0);\n" "\n" " dst[tid] = badcodehere;\n" "\n" "}\n" }; // Data passed to a program completion callback struct TestData { cl_device_id device; cl_build_status expectedStatus; }; std::atomic<int> callbackResult; } void CL_CALLBACK test_notify_build_complete(cl_program program, void *userData) { TestData *data = reinterpret_cast<TestData *>(userData); // Check user data is valid if (data == nullptr) { log_error("ERROR: User data passed to callback was not valid!\n"); callbackResult = -1; return; } // Get program build status cl_build_status status; cl_int err = clGetProgramBuildInfo(program, data->device, CL_PROGRAM_BUILD_STATUS, sizeof(cl_build_status), &status, NULL); if (err != CL_SUCCESS) { log_info("ERROR: failed to get build status from callback\n"); callbackResult = -1; return; } log_info("Program completion callback received build status %d\n", status); // Check program build status matches expectation if (status != data->expectedStatus) { log_info("ERROR: build status %d != expected status %d\n", status, data->expectedStatus); callbackResult = -1; } else { callbackResult = 1; } } int test_async_build(cl_device_id deviceID, cl_context context, cl_command_queue queue, int num_elements) { cl_int error; struct TestDef { const char **source; cl_build_status expectedStatus; }; TestDef testDefs[] = { { sample_async_kernel, CL_BUILD_SUCCESS }, { sample_async_kernel_error, CL_BUILD_ERROR } }; for (TestDef &testDef : testDefs) { log_info("\nTesting program that should produce status %d\n", testDef.expectedStatus); // Create the program clProgramWrapper program; error = create_single_kernel_helper_create_program(context, &program, 1, testDef.source); test_error(error, "Unable to create program from source"); // Start an asynchronous build, registering the completion callback TestData testData = { deviceID, testDef.expectedStatus }; callbackResult = 0; error = clBuildProgram(program, 1, &deviceID, NULL, test_notify_build_complete, (void *)&testData); // Allow implementations to return synchronous build failures. // They still need to call the callback. if (!(error == CL_BUILD_PROGRAM_FAILURE && testDef.expectedStatus == CL_BUILD_ERROR)) test_error(error, "Unable to start build"); // Wait for callback to fire int timeout = 20; while (callbackResult == 0) { if (timeout < 0) { log_error("Timeout while waiting for callback to fire.\n\n"); return -1; } log_info(" -- still waiting for callback...\n"); sleep(1); timeout--; } // Check the callback result if (callbackResult == 1) { log_error("Test passed.\n\n"); } else { log_error("Async build callback indicated test failure.\n\n"); return -1; } } return 0; } <|endoftext|>
<commit_before>/* * Copyright (c) 2015, 2016, 2017, 2018, 2019, 2020, Intel Corporation * * 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 Intel Corporation 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 LOG OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include <mpi.h> #include <cmath> #include <string> #include <vector> #include <memory> #include "geopm.h" #include "Profile.hpp" #include "Exception.hpp" #include "ModelRegion.hpp" int main(int argc, char **argv) { // Start MPI MPI_Init(&argc, &argv); bool is_verbose = false; geopm::Profile &prof = geopm::Profile::default_profile(); // Run twelve trials with region duration ranging from 100 us - 400 ms size_t num_duration = 7; double duration = 0.2048; double repeat = 200; // Each trial takes 41 seconds and the // whole execution takes 16 minutes at // sticker frequency. for (size_t duration_idx = 0; duration_idx != num_duration; ++duration_idx) { // Create scaling and scaling_timed model regions std::unique_ptr<geopm::ModelRegion> model_scaling( geopm::ModelRegion::model_region("scaling", duration, is_verbose)); std::unique_ptr<geopm::ModelRegion> model_timed( geopm::ModelRegion::model_region("timed_scaling", duration, is_verbose)); // Rename model regions std::string scaling_name = "scaling_" + std::to_string(duration_idx); std::string timed_name = "timed_" + std::to_string(duration_idx); uint64_t scaling_rid = prof.region(scaling_name, GEOPM_REGION_HINT_UNKNOWN); uint64_t timed_rid = prof.region(timed_name, GEOPM_REGION_HINT_UNKNOWN); // Execute the regions back to back repeatedly for (int idx = 0; idx != repeat; ++idx) { prof.enter(scaling_rid); model_scaling->run(); prof.exit(scaling_rid); prof.enter(timed_rid); model_timed->run(); prof.exit(timed_rid); } repeat *= 2; duration /= 2.0; } // Shutdown MPI MPI_Finalize(); return 0; } <commit_msg>Add barriers to test_ee_short_region_slop test<commit_after>/* * Copyright (c) 2015, 2016, 2017, 2018, 2019, 2020, Intel Corporation * * 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 Intel Corporation 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 LOG OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include <mpi.h> #include <cmath> #include <string> #include <vector> #include <memory> #include "geopm.h" #include "Profile.hpp" #include "Exception.hpp" #include "ModelRegion.hpp" int main(int argc, char **argv) { // Start MPI MPI_Init(&argc, &argv); bool is_verbose = false; geopm::Profile &prof = geopm::Profile::default_profile(); // Run twelve trials with region duration ranging from 100 us - 400 ms size_t num_duration = 7; double duration = 0.2048; double repeat = 200; // Each trial takes 41 seconds and the // whole execution takes 16 minutes at // sticker frequency. for (size_t duration_idx = 0; duration_idx != num_duration; ++duration_idx) { // Create scaling and scaling_timed model regions std::unique_ptr<geopm::ModelRegion> model_scaling( geopm::ModelRegion::model_region("scaling", duration, is_verbose)); std::unique_ptr<geopm::ModelRegion> model_timed( geopm::ModelRegion::model_region("timed_scaling", duration, is_verbose)); // Rename model regions std::string scaling_name = "scaling_" + std::to_string(duration_idx); std::string timed_name = "timed_" + std::to_string(duration_idx); std::string barrier_scaling_name = "barrier_scaling_" + std::to_string(duration_idx); std::string barrier_timed_name = "barrier_timed_" + std::to_string(duration_idx); uint64_t scaling_rid = prof.region(scaling_name, GEOPM_REGION_HINT_UNKNOWN); uint64_t timed_rid = prof.region(timed_name, GEOPM_REGION_HINT_UNKNOWN); uint64_t barrier_scaling_rid = prof.region(barrier_scaling_name, GEOPM_REGION_HINT_UNKNOWN); uint64_t barrier_timed_rid = prof.region(barrier_timed_name, GEOPM_REGION_HINT_UNKNOWN); // Execute the regions back to back repeatedly for (int idx = 0; idx != repeat; ++idx) { prof.enter(scaling_rid); model_scaling->run(); prof.exit(scaling_rid); prof.enter(barrier_scaling_rid); MPI_Barrier(MPI_COMM_WORLD); prof.exit(barrier_scaling_rid); prof.enter(timed_rid); model_timed->run(); prof.exit(timed_rid); prof.enter(barrier_timed_rid); MPI_Barrier(MPI_COMM_WORLD); prof.exit(barrier_timed_rid); } repeat *= 2; duration /= 2.0; } // Shutdown MPI MPI_Finalize(); return 0; } <|endoftext|>
<commit_before>/* The MIT License Copyright (c) 2011 by Jorrit Tyberghein 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 "../apparesed.h" #include "physicallayer/pl.h" #include "physicallayer/entity.h" #include "physicallayer/entitytpl.h" #include "physicallayer/propclas.h" #include "propclass/camera.h" #include "propclass/mesh.h" #include "propclass/mechsys.h" #include "playmode.h" //--------------------------------------------------------------------------- DynworldSnapshot::DynworldSnapshot (iPcDynamicWorld* dynworld) { csRef<iDynamicCellIterator> cellIt = dynworld->GetCells (); while (cellIt->HasNext ()) { iDynamicCell* cell = cellIt->NextCell (); for (size_t i = 0 ; i < cell->GetObjectCount () ; i++) { iDynamicObject* dynobj = cell->GetObject (i); Obj obj; obj.cell = dynobj->GetCell (); obj.fact = dynobj->GetFactory (); obj.isStatic = dynobj->IsStatic (); obj.trans = dynobj->GetTransform (); if (dynobj->GetEntityTemplate ()) obj.templateName = dynobj->GetEntityTemplate ()->GetName (); obj.entityName = dynobj->GetEntityName (); for (size_t j = 0 ; j < dynobj->GetFactory ()->GetJointCount () ; j++) { obj.connectedObjects.Push (FindObjIndex (dynobj->GetCell (), dynobj->GetConnectedObject (j))); } objects.Push (obj); } } } size_t DynworldSnapshot::FindObjIndex (iDynamicCell* cell, iDynamicObject* dynobj) { if (dynobj == 0) return csArrayItemNotFound; for (size_t i = 0 ; i < cell->GetObjectCount () ; i++) { if (dynobj == cell->GetObject (i)) return i; } return csArrayItemNotFound; } struct DynIdx { iDynamicObject* dynobj; size_t idx; }; void DynworldSnapshot::Restore (iPcDynamicWorld* dynworld) { csRef<iDynamicCellIterator> cellIt = dynworld->GetCells (); while (cellIt->HasNext ()) { iDynamicCell* cell = cellIt->NextCell (); cell->DeleteObjects (); } csArray<DynIdx> dynidx; for (size_t i = 0 ; i < objects.GetSize () ; i++) { Obj& obj = objects[i]; iDynamicObject* dynobj = obj.cell->AddObject (obj.fact->GetName (), obj.trans); if (!obj.templateName.IsEmpty ()) dynobj->SetEntity (obj.entityName, obj.templateName, 0); if (obj.isStatic) dynobj->MakeStatic (); else dynobj->MakeDynamic (); if (obj.connectedObjects.GetSize () > 0) { DynIdx di; di.dynobj = dynobj; di.idx = i; dynidx.Push (di); } } // Connect all joints. for (size_t i = 0 ; i < dynidx.GetSize () ; i++) { for (size_t j = 0 ; j < objects[dynidx[i].idx].connectedObjects.GetSize () ; j++) { size_t idx = objects[dynidx[i].idx].connectedObjects[j]; dynidx[i].dynobj->Connect (j, dynidx[i].dynobj->GetCell ()->GetObject (idx)); } } } //--------------------------------------------------------------------------- PlayMode::PlayMode (AresEdit3DView* aresed3d) : EditingMode (aresed3d, "Play") { snapshot = 0; } PlayMode::~PlayMode () { delete snapshot; } void PlayMode::Start () { aresed3d->GetSelection ()->SetCurrentObject (0); delete snapshot; iPcDynamicWorld* dynworld = aresed3d->GetDynamicWorld (); dynworld->InhibitEntities (false); dynworld->EnableGameMode (true); snapshot = new DynworldSnapshot (dynworld); // Set entities for all dynamic objects and find the player object. iDynamicFactory* playerFact = dynworld->FindFactory ("Player"); csReversibleTransform playerTrans; iDynamicCell* foundCell = 0; iDynamicObject* foundPlayerDynobj = 0; csRef<iDynamicCellIterator> cellIt = dynworld->GetCells (); while (cellIt->HasNext ()) { iDynamicCell* cell = cellIt->NextCell (); for (size_t i = 0 ; i < cell->GetObjectCount () ; i++) { iDynamicObject* dynobj = cell->GetObject (i); if (dynobj->GetFactory () == playerFact) { playerTrans = dynobj->GetTransform (); foundCell = cell; foundPlayerDynobj = dynobj; } else { csString tplName = dynobj->GetFactory ()->GetDefaultEntityTemplate (); if (tplName.IsEmpty ()) tplName = dynobj->GetFactory ()->GetName (); printf ("Setting entity %s with template %s\n", dynobj->GetEntityName (), tplName.GetData ()); dynobj->SetEntity (dynobj->GetEntityName (), tplName, 0); } } } if (foundPlayerDynobj) { dynworld->SetCurrentCell (foundCell); foundCell->DeleteObject (foundPlayerDynobj); } else { playerTrans.SetOrigin (csVector3 (0, 3, 0)); } iCelPlLayer* pl = aresed3d->GetPL (); iCelEntity* zoneEntity = pl->FindEntity ("Zone"); csRef<iPcMechanicsSystem> mechsys = celQueryPropertyClassEntity<iPcMechanicsSystem> (zoneEntity); mechsys->SetDynamicSystem (dynworld->GetCurrentCell ()->GetDynamicSystem ()); world = pl->CreateEntity (pl->FindEntityTemplate ("World"), "World", 0); player = pl->CreateEntity (pl->FindEntityTemplate ("Player"), "Player", 0); csRef<iPcMechanicsObject> mechPlayer = celQueryPropertyClassEntity<iPcMechanicsObject> (player); iRigidBody* body = mechPlayer->GetBody (); csRef<CS::Physics::Bullet::iRigidBody> bulletBody = scfQueryInterface<CS::Physics::Bullet::iRigidBody> (body); //bulletBody->MakeKinematic (); csRef<iPcCamera> pccamera = celQueryPropertyClassEntity<iPcCamera> (player); csRef<iPcMesh> pcmesh = celQueryPropertyClassEntity<iPcMesh> (player); // @@@ Need support for setting transform on pcmesh. pcmesh->MoveMesh (dynworld->GetCurrentCell ()->GetSector (), playerTrans.GetOrigin ()); body->SetTransform (playerTrans); iELCM* elcm = aresed3d->GetELCM (); elcm->SetPlayer (player); cellIt = dynworld->GetCells (); while (cellIt->HasNext ()) { iDynamicCell* cell = cellIt->NextCell (); for (size_t i = 0 ; i < cell->GetObjectCount () ; i++) { iDynamicObject* dynobj = cell->GetObject (i); if (dynobj->GetFactory () != playerFact) dynobj->ForceEntity (); } } } void PlayMode::Stop () { if (!snapshot) return; iCelPlLayer* pl = aresed3d->GetPL (); pl->RemoveEntity (world); world = 0; pl->RemoveEntity (player); player = 0; iELCM* elcm = aresed3d->GetELCM (); elcm->SetPlayer (0); iPcDynamicWorld* dynworld = aresed3d->GetDynamicWorld (); dynworld->InhibitEntities (true); dynworld->EnableGameMode (false); snapshot->Restore (dynworld); delete snapshot; snapshot = 0; aresed3d->GetG2D ()->SetMouseCursor (csmcArrow); } bool PlayMode::OnKeyboard(iEvent& ev, utf32_char code) { if (code == CSKEY_ESC) { aresed3d->GetApp ()->SwitchToMainMode (); return true; } return false; } <commit_msg>Fixed a bug when restoring from playmode with joints that have no connections.<commit_after>/* The MIT License Copyright (c) 2011 by Jorrit Tyberghein 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 "../apparesed.h" #include "physicallayer/pl.h" #include "physicallayer/entity.h" #include "physicallayer/entitytpl.h" #include "physicallayer/propclas.h" #include "propclass/camera.h" #include "propclass/mesh.h" #include "propclass/mechsys.h" #include "playmode.h" //--------------------------------------------------------------------------- DynworldSnapshot::DynworldSnapshot (iPcDynamicWorld* dynworld) { csRef<iDynamicCellIterator> cellIt = dynworld->GetCells (); while (cellIt->HasNext ()) { iDynamicCell* cell = cellIt->NextCell (); for (size_t i = 0 ; i < cell->GetObjectCount () ; i++) { iDynamicObject* dynobj = cell->GetObject (i); Obj obj; obj.cell = dynobj->GetCell (); obj.fact = dynobj->GetFactory (); obj.isStatic = dynobj->IsStatic (); obj.trans = dynobj->GetTransform (); if (dynobj->GetEntityTemplate ()) obj.templateName = dynobj->GetEntityTemplate ()->GetName (); obj.entityName = dynobj->GetEntityName (); for (size_t j = 0 ; j < dynobj->GetFactory ()->GetJointCount () ; j++) { obj.connectedObjects.Push (FindObjIndex (dynobj->GetCell (), dynobj->GetConnectedObject (j))); } objects.Push (obj); } } } size_t DynworldSnapshot::FindObjIndex (iDynamicCell* cell, iDynamicObject* dynobj) { if (dynobj == 0) return csArrayItemNotFound; for (size_t i = 0 ; i < cell->GetObjectCount () ; i++) { if (dynobj == cell->GetObject (i)) return i; } return csArrayItemNotFound; } struct DynIdx { iDynamicObject* dynobj; size_t idx; }; void DynworldSnapshot::Restore (iPcDynamicWorld* dynworld) { csRef<iDynamicCellIterator> cellIt = dynworld->GetCells (); while (cellIt->HasNext ()) { iDynamicCell* cell = cellIt->NextCell (); cell->DeleteObjects (); } csArray<DynIdx> dynidx; for (size_t i = 0 ; i < objects.GetSize () ; i++) { Obj& obj = objects[i]; iDynamicObject* dynobj = obj.cell->AddObject (obj.fact->GetName (), obj.trans); if (!obj.templateName.IsEmpty ()) dynobj->SetEntity (obj.entityName, obj.templateName, 0); if (obj.isStatic) dynobj->MakeStatic (); else dynobj->MakeDynamic (); if (obj.connectedObjects.GetSize () > 0) { DynIdx di; di.dynobj = dynobj; di.idx = i; dynidx.Push (di); } } // Connect all joints. for (size_t i = 0 ; i < dynidx.GetSize () ; i++) { for (size_t j = 0 ; j < objects[dynidx[i].idx].connectedObjects.GetSize () ; j++) { size_t idx = objects[dynidx[i].idx].connectedObjects[j]; if (idx != csArrayItemNotFound) dynidx[i].dynobj->Connect (j, dynidx[i].dynobj->GetCell ()->GetObject (idx)); } } } //--------------------------------------------------------------------------- PlayMode::PlayMode (AresEdit3DView* aresed3d) : EditingMode (aresed3d, "Play") { snapshot = 0; } PlayMode::~PlayMode () { delete snapshot; } void PlayMode::Start () { aresed3d->GetSelection ()->SetCurrentObject (0); delete snapshot; iPcDynamicWorld* dynworld = aresed3d->GetDynamicWorld (); dynworld->InhibitEntities (false); dynworld->EnableGameMode (true); snapshot = new DynworldSnapshot (dynworld); // Set entities for all dynamic objects and find the player object. iDynamicFactory* playerFact = dynworld->FindFactory ("Player"); csReversibleTransform playerTrans; iDynamicCell* foundCell = 0; iDynamicObject* foundPlayerDynobj = 0; csRef<iDynamicCellIterator> cellIt = dynworld->GetCells (); while (cellIt->HasNext ()) { iDynamicCell* cell = cellIt->NextCell (); for (size_t i = 0 ; i < cell->GetObjectCount () ; i++) { iDynamicObject* dynobj = cell->GetObject (i); if (dynobj->GetFactory () == playerFact) { playerTrans = dynobj->GetTransform (); foundCell = cell; foundPlayerDynobj = dynobj; } else { csString tplName = dynobj->GetFactory ()->GetDefaultEntityTemplate (); if (tplName.IsEmpty ()) tplName = dynobj->GetFactory ()->GetName (); printf ("Setting entity %s with template %s\n", dynobj->GetEntityName (), tplName.GetData ()); dynobj->SetEntity (dynobj->GetEntityName (), tplName, 0); } } } if (foundPlayerDynobj) { dynworld->SetCurrentCell (foundCell); foundCell->DeleteObject (foundPlayerDynobj); } else { playerTrans.SetOrigin (csVector3 (0, 3, 0)); } iCelPlLayer* pl = aresed3d->GetPL (); iCelEntity* zoneEntity = pl->FindEntity ("Zone"); csRef<iPcMechanicsSystem> mechsys = celQueryPropertyClassEntity<iPcMechanicsSystem> (zoneEntity); mechsys->SetDynamicSystem (dynworld->GetCurrentCell ()->GetDynamicSystem ()); world = pl->CreateEntity (pl->FindEntityTemplate ("World"), "World", 0); player = pl->CreateEntity (pl->FindEntityTemplate ("Player"), "Player", 0); csRef<iPcMechanicsObject> mechPlayer = celQueryPropertyClassEntity<iPcMechanicsObject> (player); iRigidBody* body = mechPlayer->GetBody (); csRef<CS::Physics::Bullet::iRigidBody> bulletBody = scfQueryInterface<CS::Physics::Bullet::iRigidBody> (body); //bulletBody->MakeKinematic (); csRef<iPcCamera> pccamera = celQueryPropertyClassEntity<iPcCamera> (player); csRef<iPcMesh> pcmesh = celQueryPropertyClassEntity<iPcMesh> (player); // @@@ Need support for setting transform on pcmesh. pcmesh->MoveMesh (dynworld->GetCurrentCell ()->GetSector (), playerTrans.GetOrigin ()); body->SetTransform (playerTrans); iELCM* elcm = aresed3d->GetELCM (); elcm->SetPlayer (player); cellIt = dynworld->GetCells (); while (cellIt->HasNext ()) { iDynamicCell* cell = cellIt->NextCell (); for (size_t i = 0 ; i < cell->GetObjectCount () ; i++) { iDynamicObject* dynobj = cell->GetObject (i); if (dynobj->GetFactory () != playerFact) dynobj->ForceEntity (); } } } void PlayMode::Stop () { if (!snapshot) return; iCelPlLayer* pl = aresed3d->GetPL (); pl->RemoveEntity (world); world = 0; pl->RemoveEntity (player); player = 0; iELCM* elcm = aresed3d->GetELCM (); elcm->SetPlayer (0); iPcDynamicWorld* dynworld = aresed3d->GetDynamicWorld (); dynworld->InhibitEntities (true); dynworld->EnableGameMode (false); snapshot->Restore (dynworld); delete snapshot; snapshot = 0; aresed3d->GetG2D ()->SetMouseCursor (csmcArrow); } bool PlayMode::OnKeyboard(iEvent& ev, utf32_char code) { if (code == CSKEY_ESC) { aresed3d->GetApp ()->SwitchToMainMode (); return true; } return false; } <|endoftext|>
<commit_before>// This file is part of playd. // playd is licensed under the MIT licence: see LICENSE.txt. /** * @file * Implementation of the SndfileAudioSource class. * @see audio/audio_source.hpp */ #ifndef NO_SNDFILE #include <cassert> #include <cstdint> #include <cstdlib> #include <iostream> #include <map> #include <memory> #include <sstream> #include <string> #include <sndfile.h> #include "../../errors.hpp" #include "../../messages.h" #include "../sample_formats.hpp" #include "../audio_source.hpp" #include "sndfile.hpp" SndfileAudioSource::SndfileAudioSource(const std::string &path) : AudioSource(path), file(nullptr), buffer() { this->info.format = 0; // See http://www.mega-nerd.com/libsndfile/api.html#open // for more details. this->file = sf_open(path.c_str(), SFM_READ, &this->info); if (this->file == nullptr) { throw FileError("sndfile: can't open " + path + ": " + sf_strerror(nullptr)); } // Reserve enough space for a given number of frames. // (Frames being what libsndfile calls multi-channel samples, for some // reason; incidentally, it calls mono-samples items.) assert(0 < this->info.channels); this->buffer.clear(); this->buffer.insert(this->buffer.begin(), 4096 * this->info.channels, 0); } SndfileAudioSource::~SndfileAudioSource() { if (this->file != nullptr) sf_close(this->file); } std::uint8_t SndfileAudioSource::ChannelCount() const { assert(0 < this->info.channels); return static_cast<std::uint8_t>(this->info.channels); } double SndfileAudioSource::SampleRate() const { assert(0 < this->info.samplerate); return static_cast<double>(this->info.samplerate); } std::uint64_t SndfileAudioSource::Seek(std::uint64_t position) { auto samples = this->SamplesFromMicros(position); // Have we tried to seek past the end of the file? auto clen = static_cast<unsigned long>(this->info.frames); if (clen < samples) { Debug() << "sndfile: seek at" << samples << "past EOF at" << clen << std::endl; Debug() << "sndfile: requested position micros:" << position << std::endl; throw SeekError(MSG_SEEK_FAIL); } auto new_samples = sf_seek(this->file, samples, SEEK_SET); if (new_samples == -1) { Debug() << "sndfile: seek failed" << std::endl; throw SeekError(MSG_SEEK_FAIL); } return new_samples; } SndfileAudioSource::DecodeResult SndfileAudioSource::Decode() { auto read = sf_read_int(this->file, &*this->buffer.begin(), this->buffer.size()); // Have we hit the end of the file? if (read == 0) { return std::make_pair(DecodeState::END_OF_FILE, DecodeVector()); } // Else, we're good to go (hopefully). uint8_t *begin = reinterpret_cast<uint8_t *>(&*this->buffer.begin()); // The end is 'read' 32-bit items--read*4 bytes--after. uint8_t *end = begin + (read * 4); return std::make_pair(DecodeState::DECODING, DecodeVector(begin, end)); } SampleFormat SndfileAudioSource::OutputSampleFormat() const { // Because we use int-sized reads, assume this corresponds to 32-bit signed int. // Really, we shouldn't assume int is 32-bit! return SampleFormat::PACKED_SIGNED_INT_32; } #endif // NO_SNDFILE <commit_msg>Add static assertion for int assumption.<commit_after>// This file is part of playd. // playd is licensed under the MIT licence: see LICENSE.txt. /** * @file * Implementation of the SndfileAudioSource class. * @see audio/audio_source.hpp */ #ifndef NO_SNDFILE #include <cassert> #include <cstdint> #include <cstdlib> #include <iostream> #include <map> #include <memory> #include <sstream> #include <string> #include <sndfile.h> #include "../../errors.hpp" #include "../../messages.h" #include "../sample_formats.hpp" #include "../audio_source.hpp" #include "sndfile.hpp" SndfileAudioSource::SndfileAudioSource(const std::string &path) : AudioSource(path), file(nullptr), buffer() { this->info.format = 0; // See http://www.mega-nerd.com/libsndfile/api.html#open // for more details. this->file = sf_open(path.c_str(), SFM_READ, &this->info); if (this->file == nullptr) { throw FileError("sndfile: can't open " + path + ": " + sf_strerror(nullptr)); } // Reserve enough space for a given number of frames. // (Frames being what libsndfile calls multi-channel samples, for some // reason; incidentally, it calls mono-samples items.) assert(0 < this->info.channels); this->buffer.clear(); this->buffer.insert(this->buffer.begin(), 4096 * this->info.channels, 0); } SndfileAudioSource::~SndfileAudioSource() { if (this->file != nullptr) sf_close(this->file); } std::uint8_t SndfileAudioSource::ChannelCount() const { assert(0 < this->info.channels); return static_cast<std::uint8_t>(this->info.channels); } double SndfileAudioSource::SampleRate() const { assert(0 < this->info.samplerate); return static_cast<double>(this->info.samplerate); } std::uint64_t SndfileAudioSource::Seek(std::uint64_t position) { auto samples = this->SamplesFromMicros(position); // Have we tried to seek past the end of the file? auto clen = static_cast<unsigned long>(this->info.frames); if (clen < samples) { Debug() << "sndfile: seek at" << samples << "past EOF at" << clen << std::endl; Debug() << "sndfile: requested position micros:" << position << std::endl; throw SeekError(MSG_SEEK_FAIL); } auto new_samples = sf_seek(this->file, samples, SEEK_SET); if (new_samples == -1) { Debug() << "sndfile: seek failed" << std::endl; throw SeekError(MSG_SEEK_FAIL); } return new_samples; } SndfileAudioSource::DecodeResult SndfileAudioSource::Decode() { auto read = sf_read_int(this->file, &*this->buffer.begin(), this->buffer.size()); // Have we hit the end of the file? if (read == 0) { return std::make_pair(DecodeState::END_OF_FILE, DecodeVector()); } // Else, we're good to go (hopefully). uint8_t *begin = reinterpret_cast<uint8_t *>(&*this->buffer.begin()); // The end is 'read' 32-bit items--read*4 bytes--after. uint8_t *end = begin + (read * 4); return std::make_pair(DecodeState::DECODING, DecodeVector(begin, end)); } SampleFormat SndfileAudioSource::OutputSampleFormat() const { // Because we use int-sized reads, assume this corresponds to 32-bit signed int. // Really, we shouldn't assume int is 32-bit! static_assert(sizeof(int) == 4, "sndfile outputs int, which we need to be 4 bytes"); return SampleFormat::PACKED_SIGNED_INT_32; } #endif // NO_SNDFILE <|endoftext|>
<commit_before>//******************************************************************* // // License: See top level LICENSE.txt file. // // DESCRIPTION: // Contains implementation of class ossimPreferences. This class provides // a static keywordlist for global preferences. Objects needing access to // application-wide global parameters shall do so through this class. // // SOFTWARE HISTORY: //> // 23Apr2001 Oscar Kramer (okramer@imagelinks.com) // Initial coding. //< //***************************************************************************** #include <cstdlib> /* for getenv() */ #include <ossim/base/ossimPreferences.h> #include <ossim/base/ossimNotify.h> //RTTI_DEF1(ossimPreferences, "ossimPreferences" , ossimObject) //*** // Define Trace flags for use within this file: //*** #include <ossim/base/ossimTrace.h> static ossimTrace traceExec ("ossimPreferences:exec"); static ossimTrace traceDebug ("ossimPreferences:debug"); static const char* PREF_FILE_ENV_VAR_NAME = "OSSIM_PREFS_FILE"; ossimPreferences* ossimPreferences::theInstance = NULL; ossimPreferences::ossimPreferences() { /*! * If $(env_var_name) is found in the preferences file, * expand it in place. */ theKWL.setExpandEnvVarsFlag( true ); loadPreferences(); } ossimPreferences::~ossimPreferences() { theInstance = NULL; } /*!**************************************************************************** * METHOD: ossimPreferences::instance() * * This is the method by which run-time objects access this singleton instance * *****************************************************************************/ ossimPreferences* ossimPreferences::instance() { /*! * Simply return the instance if already created: */ if (theInstance) return theInstance; /*! * Create the static instance of this class: */ theInstance = new ossimPreferences(); return theInstance; } /*!**************************************************************************** * METHOD: loadPreferences() * * Loads the preferences file specified in the runtime environment. * *****************************************************************************/ bool ossimPreferences::loadPreferences() { static const char MODULE[] = "ossimPreferences::loadPreferences()"; if (traceExec()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG: " << MODULE << " entering...\n"; } bool parsed_ok = false; /*! * Fetch preferences file name from environment: */ char* pref_filename = getenv(PREF_FILE_ENV_VAR_NAME); if (pref_filename) { /*! * Load the preferences file into the static keywordlist object: */ thePrefFilename = pref_filename; parsed_ok = theKWL.addFile(pref_filename); /*! * Check for error opening KWL: */ if (!parsed_ok) { ossimNotify(ossimNotifyLevel_WARN) << "WARNING: " << MODULE << ", an error was encountered loading the prefererences " << "file at \"" << thePrefFilename << "\" as specified by the " << "environment variable \"" << PREF_FILE_ENV_VAR_NAME << "\"." << "Preferences were not loaded.\n"; } } // else // { // if (traceDebug()) // { // // No ENV var found. Print warning: // CLOG << "WARNING: the preferences file environment variable \"" // << PREF_FILE_ENV_VAR_NAME << "\" is not defined. No preferences " // << "were loaded. The environment variable should be set to " // << "the full path to the preferences keywordlist file desired." // << endl; // } // } if (traceExec()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG: " << MODULE << "returning...\n"; } return parsed_ok; } /*!**************************************************************************** * METHOD: loadPreferences(filename) * * Loads the preferences file specified in the arg. * *****************************************************************************/ bool ossimPreferences::loadPreferences(const ossimFilename& pathname) { static const char MODULE[] = "ossimPreferences::loadPreferences(filename)"; if (traceExec()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG: " << MODULE << ", entering...\n"; } bool parsed_ok; /*! * First clear the existing KWL: */ theKWL.clear(); theInstanceIsModified = true; /*! * Load the preferences file into the static keywordlist object: */ thePrefFilename = pathname; parsed_ok = theKWL.addFile(pathname); /*! * Check for error opening KWL: */ if (!parsed_ok) { ossimNotify(ossimNotifyLevel_WARN) << "WARNING: " << MODULE << ", an error was encountered loading the prefererences " << "file at \"" << pathname << "\". Preferences were not " << "loaded.\n"; } if (traceExec()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG: " << MODULE<< ", returning...\n"; } return parsed_ok; } /*!**************************************************************************** * METHOD: ossimPreferences::savePreferences() * * Saves KWL to the current filename. * *****************************************************************************/ bool ossimPreferences::savePreferences() const { static const char MODULE[] = "ossimPreferences::savePreferences()"; if (traceExec()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG: " << MODULE << ", entering...\n"; } bool success = true; /*! * Save the file to current preferences filename: */ if (theInstanceIsModified) { theKWL.write(thePrefFilename); theInstanceIsModified = false; } if (traceExec()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG:" << MODULE << ", returning...\n"; } return success; } /*!**************************************************************************** * METHOD: ossimPreferences::savePreferences(filename) * * Saves KWL to the specified filename. * *****************************************************************************/ bool ossimPreferences::savePreferences(const ossimFilename& pathname) { static const char MODULE[] = "ossimPreferences::savePreferences()"; if (traceExec()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG: "<< MODULE << ", entering...\n"; } bool success = true; /*! * Save the file to the specified preferences filename: */ theKWL.write(pathname); thePrefFilename = pathname; theInstanceIsModified = false; if (traceExec()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG: " << MODULE << ", returning...\n"; } return success; } void ossimPreferences::addPreference(const char* key, const char* value) { theKWL.add(key, value, true); theInstanceIsModified = true; } void ossimPreferences::addPreferences(const ossimKeywordlist& kwl, const char* prefix, bool stripPrefix) { theKWL.add(kwl, prefix, stripPrefix); theInstanceIsModified = true; } ossimFilename ossimPreferences::getPreferencesFilename() const { return thePrefFilename; } <commit_msg>Removed dead code.<commit_after>//******************************************************************* // // License: See top level LICENSE.txt file. // // DESCRIPTION: // Contains implementation of class ossimPreferences. This class provides // a static keywordlist for global preferences. Objects needing access to // application-wide global parameters shall do so through this class. // // SOFTWARE HISTORY: //> // 23Apr2001 Oscar Kramer (okramer@imagelinks.com) // Initial coding. //< //***************************************************************************** #include <cstdlib> /* for getenv() */ #include <ossim/base/ossimPreferences.h> #include <ossim/base/ossimNotify.h> //RTTI_DEF1(ossimPreferences, "ossimPreferences" , ossimObject) //*** // Define Trace flags for use within this file: //*** #include <ossim/base/ossimTrace.h> static ossimTrace traceExec ("ossimPreferences:exec"); static ossimTrace traceDebug ("ossimPreferences:debug"); static const char* PREF_FILE_ENV_VAR_NAME = "OSSIM_PREFS_FILE"; ossimPreferences* ossimPreferences::theInstance = NULL; ossimPreferences::ossimPreferences() { /*! * If $(env_var_name) is found in the preferences file, * expand it in place. */ theKWL.setExpandEnvVarsFlag( true ); loadPreferences(); } ossimPreferences::~ossimPreferences() { theInstance = NULL; } /*!**************************************************************************** * METHOD: ossimPreferences::instance() * * This is the method by which run-time objects access this singleton instance * *****************************************************************************/ ossimPreferences* ossimPreferences::instance() { /*! * Simply return the instance if already created: */ if (theInstance) return theInstance; /*! * Create the static instance of this class: */ theInstance = new ossimPreferences(); return theInstance; } /*!**************************************************************************** * METHOD: loadPreferences() * * Loads the preferences file specified in the runtime environment. * *****************************************************************************/ bool ossimPreferences::loadPreferences() { static const char MODULE[] = "ossimPreferences::loadPreferences()"; if (traceExec()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG: " << MODULE << " entering...\n"; } bool parsed_ok = false; /*! * Fetch preferences file name from environment: */ char* pref_filename = getenv(PREF_FILE_ENV_VAR_NAME); //std::cout << "ossimPreferences::loadPreferences() ======== " << ossimString(pref_filename) << "\n"; if (pref_filename) { /*! * Load the preferences file into the static keywordlist object: */ thePrefFilename = pref_filename; parsed_ok = theKWL.addFile(pref_filename); /*! * Check for error opening KWL: */ if (!parsed_ok) { ossimNotify(ossimNotifyLevel_WARN) << "WARNING: " << MODULE << ", an error was encountered loading the prefererences " << "file at \"" << thePrefFilename << "\" as specified by the " << "environment variable \"" << PREF_FILE_ENV_VAR_NAME << "\"." << "Preferences were not loaded.\n"; } } if (traceExec()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG: " << MODULE << "returning...\n"; } return parsed_ok; } /*!**************************************************************************** * METHOD: loadPreferences(filename) * * Loads the preferences file specified in the arg. * *****************************************************************************/ bool ossimPreferences::loadPreferences(const ossimFilename& pathname) { static const char MODULE[] = "ossimPreferences::loadPreferences(filename)"; if (traceExec()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG: " << MODULE << ", entering...\n"; } bool parsed_ok; /*! * First clear the existing KWL: */ theKWL.clear(); theInstanceIsModified = true; /*! * Load the preferences file into the static keywordlist object: */ thePrefFilename = pathname; parsed_ok = theKWL.addFile(pathname); /*! * Check for error opening KWL: */ if (!parsed_ok) { ossimNotify(ossimNotifyLevel_WARN) << "WARNING: " << MODULE << ", an error was encountered loading the prefererences " << "file at \"" << pathname << "\". Preferences were not " << "loaded.\n"; } if (traceExec()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG: " << MODULE<< ", returning...\n"; } return parsed_ok; } /*!**************************************************************************** * METHOD: ossimPreferences::savePreferences() * * Saves KWL to the current filename. * *****************************************************************************/ bool ossimPreferences::savePreferences() const { static const char MODULE[] = "ossimPreferences::savePreferences()"; if (traceExec()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG: " << MODULE << ", entering...\n"; } bool success = true; /*! * Save the file to current preferences filename: */ if (theInstanceIsModified) { theKWL.write(thePrefFilename); theInstanceIsModified = false; } if (traceExec()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG:" << MODULE << ", returning...\n"; } return success; } /*!**************************************************************************** * METHOD: ossimPreferences::savePreferences(filename) * * Saves KWL to the specified filename. * *****************************************************************************/ bool ossimPreferences::savePreferences(const ossimFilename& pathname) { static const char MODULE[] = "ossimPreferences::savePreferences()"; if (traceExec()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG: "<< MODULE << ", entering...\n"; } bool success = true; /*! * Save the file to the specified preferences filename: */ theKWL.write(pathname); thePrefFilename = pathname; theInstanceIsModified = false; if (traceExec()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG: " << MODULE << ", returning...\n"; } return success; } void ossimPreferences::addPreference(const char* key, const char* value) { theKWL.add(key, value, true); theInstanceIsModified = true; } void ossimPreferences::addPreferences(const ossimKeywordlist& kwl, const char* prefix, bool stripPrefix) { theKWL.add(kwl, prefix, stripPrefix); theInstanceIsModified = true; } ossimFilename ossimPreferences::getPreferencesFilename() const { return thePrefFilename; } <|endoftext|>
<commit_before>#include "../../include/carregador/carregador.h" Carregador::Carregador(int argc, char* argv[]) { this->setFileNames(argv); this->loadInstructions(); this->openIOFiles(); this->processObjectFile(); } Carregador::~Carregador() { // Sem preocupações com o close fileObject.close(); fileOutput.close(); } void Carregador::openIOFiles() { this->fileObject.open(objFileName); this->fileOutput.open(outputFileName); } void Carregador::processObjectFile() { std::string word; int expected_args = 0; bool foundStop = false; while (this->fileObject >> word) { int value = std::stoi(word); // get index for instruction, -1 for not instruction int idx = this->identifyInstruction(value); if(idx == -1 | expected_args > 0 | foundStop) { std::cout << value << " " << "Data" <<'\n'; // If a variable was expected subtract one from expected_args, keeps in 0, otherwise expected_args = expected_args <= 0? 0 : expected_args-1; } else { std::cout << value << " " << this->instructionList[idx].nome <<'\n'; expected_args = this->instructionList[idx].noperands; if(this->instructionList[idx].nome == "stop") foundStop = true; } } } int Carregador::identifyInstruction(int value) { for(int idx = 0; idx < this->instructionList.size(); idx++) { if(value == this->instructionList[idx].opcode) return idx; } return -1; } void Carregador::setFileNames(char* argv[]) { this->objFileName = std::string(argv[1]); this->outputFileName = string_ops::setOutputExtension(this->objFileName, ".im"); std::cout << this->outputFileName << '\n'; } void Carregador::loadInstructions(std::string tablePath) { /* Open and closes instruction table file */ std::ifstream instructionTable(tablePath); //string de suporte para capturar os elementos std::string aux; while (getline(instructionTable, aux)){ std::stringstream lineStream (aux); Mnemonic instruction; /* Fill mnemonic with data from this line */ std::string word; lineStream >> word; /* Set name */ instruction.setName(word); lineStream >> word; /* Set noperands */ instruction.setNOperands(atoi(word.c_str())); lineStream >> word; /* Set opcode */ instruction.setOpcode(atoi(word.c_str())); lineStream >> word; /* Set size */ instruction.setSize(atoi(word.c_str())); /* Push to instructionList */ this->instructionList.push_back(instruction); } // this->printIntstructions(); } /* Imprime Tokens guardades em tokensList */ void Carregador::printIntstructions() { if(this->instructionList.empty()) { std::cout << "Instructions list empty" << '\n'; return; } for(size_t i = 0; i < instructionList.size(); i++) { std::cout << "Instruction name: " << instructionList[i].nome << " " << "noperands: " << instructionList[i].noperands << " " << "opcode: " << instructionList[i].opcode << " " << "size: " << instructionList[i].size << '\n'; } std::cout << '\n'; } <commit_msg>Refactored processObjectFile to improve clarity and better output<commit_after>#include "../../include/carregador/carregador.h" Carregador::Carregador(int argc, char* argv[]) { this->setFileNames(argv); this->loadInstructions(); this->openIOFiles(); this->processObjectFile(); } Carregador::~Carregador() { // Sem preocupações com o close fileObject.close(); fileOutput.close(); } void Carregador::openIOFiles() { this->fileObject.open(objFileName); this->fileOutput.open(outputFileName); } void Carregador::processObjectFile() { std::string word; int expected_args = 0; bool foundStop = false; while (this->fileObject >> word) { int value = std::stoi(word); // get index for instruction, -1 for not instruction int idx = this->identifyInstruction(value); // If has found the stop instruction, its surely a data declaration if(foundStop) { std::cout << value << "\t" << "Data" <<'\n'; } // If the opcode is not identified, or an argument is expected, is an argument else if (idx == -1 | expected_args > 0) { expected_args = expected_args - 1; std::cout << value << "\t" << "Argument" <<'\n'; } // If neither, must be an instruction else { std::cout << value << "\t" << this->instructionList[idx].nome <<'\n'; expected_args = this->instructionList[idx].noperands; // If instruction is stop, update found stop if(this->instructionList[idx].nome == "stop") foundStop = true; } } } int Carregador::identifyInstruction(int value) { for(int idx = 0; idx < this->instructionList.size(); idx++) { if(value == this->instructionList[idx].opcode) return idx; } return -1; } void Carregador::setFileNames(char* argv[]) { this->objFileName = std::string(argv[1]); this->outputFileName = string_ops::setOutputExtension(this->objFileName, ".im"); std::cout << this->outputFileName << '\n'; } void Carregador::loadInstructions(std::string tablePath) { /* Open and closes instruction table file */ std::ifstream instructionTable(tablePath); //string de suporte para capturar os elementos std::string aux; while (getline(instructionTable, aux)){ std::stringstream lineStream (aux); Mnemonic instruction; /* Fill mnemonic with data from this line */ std::string word; lineStream >> word; /* Set name */ instruction.setName(word); lineStream >> word; /* Set noperands */ instruction.setNOperands(atoi(word.c_str())); lineStream >> word; /* Set opcode */ instruction.setOpcode(atoi(word.c_str())); lineStream >> word; /* Set size */ instruction.setSize(atoi(word.c_str())); /* Push to instructionList */ this->instructionList.push_back(instruction); } // this->printIntstructions(); } /* Imprime Tokens guardades em tokensList */ void Carregador::printIntstructions() { if(this->instructionList.empty()) { std::cout << "Instructions list empty" << '\n'; return; } for(size_t i = 0; i < instructionList.size(); i++) { std::cout << "Instruction name: " << instructionList[i].nome << " " << "noperands: " << instructionList[i].noperands << " " << "opcode: " << instructionList[i].opcode << " " << "size: " << instructionList[i].size << '\n'; } std::cout << '\n'; } <|endoftext|>
<commit_before>/* (c) Copyright 2001-2011 The world wide DirectFB Open Source Community (directfb.org) (c) Copyright 2000-2004 Convergence (integrated media) GmbH All rights reserved. Written by Denis Oliver Kropp <dok@directfb.org>, Andreas Hundt <andi@fischlustig.de>, Sven Neumann <neo@directfb.org>, Ville Syrjälä <syrjala@sci.fi> and Claudio Ciccani <klan@users.sf.net>. 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 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. */ #include <config.h> #include "CoreSurface.h" extern "C" { #include <directfb_util.h> #include <direct/debug.h> #include <direct/mem.h> #include <direct/messages.h> #include <core/core.h> #include <core/surface.h> #include <core/surface_pool.h> } D_DEBUG_DOMAIN( DirectFB_CoreSurface, "DirectFB/CoreSurface", "DirectFB CoreSurface" ); /*********************************************************************************************************************/ namespace DirectFB { DFBResult ISurface_Real::SetConfig( const CoreSurfaceConfig *config ) { D_DEBUG_AT( DirectFB_CoreSurface, "ISurface_Real::%s()\n", __FUNCTION__ ); D_ASSERT( config != NULL ); return dfb_surface_reconfig( obj, config ); } DFBResult ISurface_Real::Flip( bool swap ) { DFBResult ret; D_DEBUG_AT( DirectFB_CoreSurface, "ISurface_Real::%s()\n", __FUNCTION__ ); dfb_surface_lock( obj ); ret = dfb_surface_flip( obj, swap ); dfb_surface_unlock( obj ); return ret; } DFBResult ISurface_Real::GetPalette( CorePalette **ret_palette ) { DFBResult ret; D_DEBUG_AT( DirectFB_CoreSurface, "ISurface_Real::%s()\n", __FUNCTION__ ); D_ASSERT( ret_palette != NULL ); if (!obj->palette) return DFB_UNSUPPORTED; ret = (DFBResult) dfb_palette_ref( obj->palette ); if (ret) return ret; *ret_palette = obj->palette; return DFB_OK; } DFBResult ISurface_Real::SetPalette( CorePalette *palette ) { D_DEBUG_AT( DirectFB_CoreSurface, "ISurface_Real::%s()\n", __FUNCTION__ ); D_ASSERT( palette != NULL ); return dfb_surface_set_palette( obj, palette ); } DFBResult ISurface_Real::SetAlphaRamp( u8 a0, u8 a1, u8 a2, u8 a3 ) { D_DEBUG_AT( DirectFB_CoreSurface, "ISurface_Real::%s()\n", __FUNCTION__ ); return dfb_surface_set_alpha_ramp( obj, a0, a1, a2, a3 ); } DFBResult ISurface_Real::SetField( s32 field ) { D_DEBUG_AT( DirectFB_CoreSurface, "ISurface_Real::%s()\n", __FUNCTION__ ); return dfb_surface_set_field( obj, field ); } static void manage_interlocks( CoreSurfaceAllocation *allocation, CoreSurfaceAccessorID accessor, CoreSurfaceAccessFlags access ) { int locks; locks = dfb_surface_allocation_locks( allocation ); #if 1 /* * Manage access interlocks. * * SOON FIXME: Clearing flags only when not locked yet. Otherwise nested GPU/CPU locks are a problem. */ /* Software read/write access... */ if (accessor == CSAID_CPU) { /* If hardware has written or is writing... */ if (allocation->accessed[CSAID_GPU] & CSAF_WRITE) { /* ...wait for the operation to finish. */ dfb_gfxcard_sync(); /* TODO: wait for serial instead */ /* Software read access after hardware write requires flush of the (bus) read cache. */ dfb_gfxcard_flush_read_cache(); if (!locks) { /* ...clear hardware write access. */ allocation->accessed[CSAID_GPU] = (CoreSurfaceAccessFlags)(allocation->accessed[CSAID_GPU] & ~CSAF_WRITE); /* ...clear hardware read access (to avoid syncing twice). */ allocation->accessed[CSAID_GPU] = (CoreSurfaceAccessFlags)(allocation->accessed[CSAID_GPU] & ~CSAF_READ); } } /* Software write access... */ if (access & CSAF_WRITE) { /* ...if hardware has (to) read... */ if (allocation->accessed[CSAID_GPU] & CSAF_READ) { /* ...wait for the operation to finish. */ dfb_gfxcard_sync(); /* TODO: wait for serial instead */ /* ...clear hardware read access. */ if (!locks) allocation->accessed[CSAID_GPU] = (CoreSurfaceAccessFlags)(allocation->accessed[CSAID_GPU] & ~CSAF_READ); } } } /* Hardware read access... */ if (accessor == CSAID_GPU && access & CSAF_READ) { /* ...if software has written before... */ if (allocation->accessed[CSAID_CPU] & CSAF_WRITE) { /* ...flush texture cache. */ dfb_gfxcard_flush_texture_cache(); /* ...clear software write access. */ if (!locks) allocation->accessed[CSAID_CPU] = (CoreSurfaceAccessFlags)(allocation->accessed[CSAID_CPU] & ~CSAF_WRITE); } } if (! D_FLAGS_ARE_SET( allocation->accessed[accessor], access )) { /* FIXME: surface_enter */ } #endif /* Collect... */ allocation->accessed[accessor] = (CoreSurfaceAccessFlags)(allocation->accessed[accessor] | access); } DFBResult ISurface_Real::PreLockBuffer( CoreSurfaceBuffer *buffer, CoreSurfaceAccessorID accessor, CoreSurfaceAccessFlags access, CoreSurfaceAllocation **ret_allocation ) { DFBResult ret; CoreSurfaceAllocation *allocation; CoreSurface *surface = obj; bool allocated = false; D_DEBUG_AT( DirectFB_CoreSurface, "ISurface_Real::%s()\n", __FUNCTION__ ); D_MAGIC_ASSERT( buffer, CoreSurfaceBuffer ); dfb_surface_lock( surface ); if (!buffer->surface) { dfb_surface_unlock( surface ); return DFB_BUFFEREMPTY; } /* Look for allocation with proper access. */ allocation = dfb_surface_buffer_find_allocation( buffer, accessor, access, true ); if (!allocation) { /* If no allocation exists, create one. */ ret = dfb_surface_pools_allocate( buffer, accessor, access, &allocation ); if (ret) { if (ret != DFB_NOVIDEOMEMORY && ret != DFB_UNSUPPORTED) D_DERROR( ret, "Core/SurfBuffer: Buffer allocation failed!\n" ); goto out; } allocated = true; } CORE_SURFACE_ALLOCATION_ASSERT( allocation ); /* Synchronize with other allocations. */ ret = dfb_surface_allocation_update( allocation, access ); if (ret) { /* Destroy if newly created. */ if (allocated) dfb_surface_allocation_decouple( allocation ); goto out; } ret = dfb_surface_pool_prelock( allocation->pool, allocation, accessor, access ); if (ret) { /* Destroy if newly created. */ if (allocated) dfb_surface_allocation_decouple( allocation ); goto out; } manage_interlocks( allocation, accessor, access ); dfb_surface_allocation_ref( allocation ); *ret_allocation = allocation; out: dfb_surface_unlock( surface ); return ret; } DFBResult ISurface_Real::PreLockBuffer2( CoreSurfaceBufferRole role, DFBSurfaceStereoEye eye, CoreSurfaceAccessorID accessor, CoreSurfaceAccessFlags access, bool lock, CoreSurfaceAllocation **ret_allocation ) { DFBResult ret; CoreSurfaceBuffer *buffer; CoreSurfaceAllocation *allocation; CoreSurface *surface = obj; bool allocated = false; D_DEBUG_AT( DirectFB_CoreSurface, "ISurface_Real::%s()\n", __FUNCTION__ ); ret = (DFBResult) dfb_surface_lock( surface ); if (ret) return ret; if (surface->num_buffers < 1) { dfb_surface_unlock( surface ); return DFB_BUFFEREMPTY; } buffer = dfb_surface_get_buffer2( surface, role, eye ); D_MAGIC_ASSERT( buffer, CoreSurfaceBuffer ); if (!lock && access & CSAF_READ) { if (fusion_vector_is_empty( &buffer->allocs )) { dfb_surface_unlock( surface ); return DFB_NOALLOCATION; } } /* Look for allocation with proper access. */ allocation = dfb_surface_buffer_find_allocation( buffer, accessor, access, lock ); if (!allocation) { /* If no allocation exists, create one. */ ret = dfb_surface_pools_allocate( buffer, accessor, access, &allocation ); if (ret) { if (ret != DFB_NOVIDEOMEMORY && ret != DFB_UNSUPPORTED) D_DERROR( ret, "Core/SurfBuffer: Buffer allocation failed!\n" ); goto out; } allocated = true; } CORE_SURFACE_ALLOCATION_ASSERT( allocation ); /* Synchronize with other allocations. */ ret = dfb_surface_allocation_update( allocation, access ); if (ret) { /* Destroy if newly created. */ if (allocated) dfb_surface_allocation_decouple( allocation ); goto out; } if (!lock) { if (access & CSAF_WRITE) { if (!(allocation->pool->desc.caps & CSPCAPS_WRITE)) lock = true; } else if (access & CSAF_READ) { if (!(allocation->pool->desc.caps & CSPCAPS_READ)) lock = true; } } if (lock) { ret = dfb_surface_pool_prelock( allocation->pool, allocation, accessor, access ); if (ret) { /* Destroy if newly created. */ if (allocated) dfb_surface_allocation_decouple( allocation ); goto out; } manage_interlocks( allocation, accessor, access ); } dfb_surface_allocation_ref( allocation ); *ret_allocation = allocation; out: dfb_surface_unlock( surface ); return ret; } DFBResult ISurface_Real::PreReadBuffer( CoreSurfaceBuffer *buffer, const DFBRectangle *rect, CoreSurfaceAllocation **ret_allocation ) { DFBResult ret; CoreSurfaceAllocation *allocation; CoreSurface *surface = obj; bool allocated = false; D_DEBUG_AT( DirectFB_CoreSurface, "ISurface_Real::%s()\n", __FUNCTION__ ); D_MAGIC_ASSERT( buffer, CoreSurfaceBuffer ); dfb_surface_lock( surface ); if (!buffer->surface) { dfb_surface_unlock( surface ); return DFB_BUFFEREMPTY; } /* Use last written allocation if it's up to date... */ if (buffer->written && direct_serial_check( &buffer->written->serial, &buffer->serial )) allocation = buffer->written; else { /* ...otherwise look for allocation with CPU access. */ allocation = dfb_surface_buffer_find_allocation( buffer, CSAID_CPU, CSAF_READ, false ); if (!allocation) { /* If no allocation exists, create one. */ ret = dfb_surface_pools_allocate( buffer, CSAID_CPU, CSAF_READ, &allocation ); if (ret) { D_DERROR( ret, "Core/SurfBuffer: Buffer allocation failed!\n" ); goto out; } allocated = true; } } CORE_SURFACE_ALLOCATION_ASSERT( allocation ); /* Synchronize with other allocations. */ ret = dfb_surface_allocation_update( allocation, CSAF_READ ); if (ret) { /* Destroy if newly created. */ if (allocated) dfb_surface_allocation_decouple( allocation ); goto out; } if (!(allocation->pool->desc.caps & CSPCAPS_READ)) { ret = dfb_surface_pool_prelock( allocation->pool, allocation, CSAID_CPU, CSAF_READ ); if (ret) { /* Destroy if newly created. */ if (allocated) dfb_surface_allocation_decouple( allocation ); goto out; } manage_interlocks( allocation, CSAID_CPU, CSAF_READ ); } dfb_surface_allocation_ref( allocation ); *ret_allocation = allocation; out: dfb_surface_unlock( surface ); return ret; } DFBResult ISurface_Real::PreWriteBuffer( CoreSurfaceBuffer *buffer, const DFBRectangle *rect, CoreSurfaceAllocation **ret_allocation ) { DFBResult ret; CoreSurfaceAllocation *allocation; CoreSurface *surface = obj; bool allocated = false; D_DEBUG_AT( DirectFB_CoreSurface, "ISurface_Real::%s()\n", __FUNCTION__ ); D_MAGIC_ASSERT( buffer, CoreSurfaceBuffer ); dfb_surface_lock( surface ); if (!buffer->surface) { dfb_surface_unlock( surface ); return DFB_BUFFEREMPTY; } /* Use last read allocation if it's up to date... */ if (buffer->read && direct_serial_check( &buffer->read->serial, &buffer->serial )) allocation = buffer->read; else { /* ...otherwise look for allocation with CPU access. */ allocation = dfb_surface_buffer_find_allocation( buffer, CSAID_CPU, CSAF_WRITE, false ); if (!allocation) { /* If no allocation exists, create one. */ ret = dfb_surface_pools_allocate( buffer, CSAID_CPU, CSAF_WRITE, &allocation ); if (ret) { D_DERROR( ret, "Core/SurfBuffer: Buffer allocation failed!\n" ); goto out; } allocated = true; } } CORE_SURFACE_ALLOCATION_ASSERT( allocation ); /* Synchronize with other allocations. */ ret = dfb_surface_allocation_update( allocation, CSAF_WRITE ); if (ret) { /* Destroy if newly created. */ if (allocated) dfb_surface_allocation_decouple( allocation ); goto out; } if (!(allocation->pool->desc.caps & CSPCAPS_WRITE)) { ret = dfb_surface_pool_prelock( allocation->pool, allocation, CSAID_CPU, CSAF_WRITE ); if (ret) { /* Destroy if newly created. */ if (allocated) dfb_surface_allocation_decouple( allocation ); goto out; } manage_interlocks( allocation, CSAID_CPU, CSAF_WRITE ); } dfb_surface_allocation_ref( allocation ); *ret_allocation = allocation; out: dfb_surface_unlock( surface ); return ret; } } <commit_msg>CoreSurface_real: Add some more debug to PreLockBuffer2().<commit_after>/* (c) Copyright 2001-2011 The world wide DirectFB Open Source Community (directfb.org) (c) Copyright 2000-2004 Convergence (integrated media) GmbH All rights reserved. Written by Denis Oliver Kropp <dok@directfb.org>, Andreas Hundt <andi@fischlustig.de>, Sven Neumann <neo@directfb.org>, Ville Syrjälä <syrjala@sci.fi> and Claudio Ciccani <klan@users.sf.net>. 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 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. */ #include <config.h> #include "CoreSurface.h" extern "C" { #include <directfb_util.h> #include <direct/debug.h> #include <direct/mem.h> #include <direct/messages.h> #include <core/core.h> #include <core/surface.h> #include <core/surface_pool.h> } D_DEBUG_DOMAIN( DirectFB_CoreSurface, "DirectFB/CoreSurface", "DirectFB CoreSurface" ); /*********************************************************************************************************************/ namespace DirectFB { DFBResult ISurface_Real::SetConfig( const CoreSurfaceConfig *config ) { D_DEBUG_AT( DirectFB_CoreSurface, "ISurface_Real::%s()\n", __FUNCTION__ ); D_ASSERT( config != NULL ); return dfb_surface_reconfig( obj, config ); } DFBResult ISurface_Real::Flip( bool swap ) { DFBResult ret; D_DEBUG_AT( DirectFB_CoreSurface, "ISurface_Real::%s()\n", __FUNCTION__ ); dfb_surface_lock( obj ); ret = dfb_surface_flip( obj, swap ); dfb_surface_unlock( obj ); return ret; } DFBResult ISurface_Real::GetPalette( CorePalette **ret_palette ) { DFBResult ret; D_DEBUG_AT( DirectFB_CoreSurface, "ISurface_Real::%s()\n", __FUNCTION__ ); D_ASSERT( ret_palette != NULL ); if (!obj->palette) return DFB_UNSUPPORTED; ret = (DFBResult) dfb_palette_ref( obj->palette ); if (ret) return ret; *ret_palette = obj->palette; return DFB_OK; } DFBResult ISurface_Real::SetPalette( CorePalette *palette ) { D_DEBUG_AT( DirectFB_CoreSurface, "ISurface_Real::%s()\n", __FUNCTION__ ); D_ASSERT( palette != NULL ); return dfb_surface_set_palette( obj, palette ); } DFBResult ISurface_Real::SetAlphaRamp( u8 a0, u8 a1, u8 a2, u8 a3 ) { D_DEBUG_AT( DirectFB_CoreSurface, "ISurface_Real::%s()\n", __FUNCTION__ ); return dfb_surface_set_alpha_ramp( obj, a0, a1, a2, a3 ); } DFBResult ISurface_Real::SetField( s32 field ) { D_DEBUG_AT( DirectFB_CoreSurface, "ISurface_Real::%s()\n", __FUNCTION__ ); return dfb_surface_set_field( obj, field ); } static void manage_interlocks( CoreSurfaceAllocation *allocation, CoreSurfaceAccessorID accessor, CoreSurfaceAccessFlags access ) { int locks; locks = dfb_surface_allocation_locks( allocation ); #if 1 /* * Manage access interlocks. * * SOON FIXME: Clearing flags only when not locked yet. Otherwise nested GPU/CPU locks are a problem. */ /* Software read/write access... */ if (accessor == CSAID_CPU) { /* If hardware has written or is writing... */ if (allocation->accessed[CSAID_GPU] & CSAF_WRITE) { /* ...wait for the operation to finish. */ dfb_gfxcard_sync(); /* TODO: wait for serial instead */ /* Software read access after hardware write requires flush of the (bus) read cache. */ dfb_gfxcard_flush_read_cache(); if (!locks) { /* ...clear hardware write access. */ allocation->accessed[CSAID_GPU] = (CoreSurfaceAccessFlags)(allocation->accessed[CSAID_GPU] & ~CSAF_WRITE); /* ...clear hardware read access (to avoid syncing twice). */ allocation->accessed[CSAID_GPU] = (CoreSurfaceAccessFlags)(allocation->accessed[CSAID_GPU] & ~CSAF_READ); } } /* Software write access... */ if (access & CSAF_WRITE) { /* ...if hardware has (to) read... */ if (allocation->accessed[CSAID_GPU] & CSAF_READ) { /* ...wait for the operation to finish. */ dfb_gfxcard_sync(); /* TODO: wait for serial instead */ /* ...clear hardware read access. */ if (!locks) allocation->accessed[CSAID_GPU] = (CoreSurfaceAccessFlags)(allocation->accessed[CSAID_GPU] & ~CSAF_READ); } } } /* Hardware read access... */ if (accessor == CSAID_GPU && access & CSAF_READ) { /* ...if software has written before... */ if (allocation->accessed[CSAID_CPU] & CSAF_WRITE) { /* ...flush texture cache. */ dfb_gfxcard_flush_texture_cache(); /* ...clear software write access. */ if (!locks) allocation->accessed[CSAID_CPU] = (CoreSurfaceAccessFlags)(allocation->accessed[CSAID_CPU] & ~CSAF_WRITE); } } if (! D_FLAGS_ARE_SET( allocation->accessed[accessor], access )) { /* FIXME: surface_enter */ } #endif /* Collect... */ allocation->accessed[accessor] = (CoreSurfaceAccessFlags)(allocation->accessed[accessor] | access); } DFBResult ISurface_Real::PreLockBuffer( CoreSurfaceBuffer *buffer, CoreSurfaceAccessorID accessor, CoreSurfaceAccessFlags access, CoreSurfaceAllocation **ret_allocation ) { DFBResult ret; CoreSurfaceAllocation *allocation; CoreSurface *surface = obj; bool allocated = false; D_DEBUG_AT( DirectFB_CoreSurface, "ISurface_Real::%s()\n", __FUNCTION__ ); D_MAGIC_ASSERT( buffer, CoreSurfaceBuffer ); dfb_surface_lock( surface ); if (!buffer->surface) { dfb_surface_unlock( surface ); return DFB_BUFFEREMPTY; } /* Look for allocation with proper access. */ allocation = dfb_surface_buffer_find_allocation( buffer, accessor, access, true ); if (!allocation) { /* If no allocation exists, create one. */ ret = dfb_surface_pools_allocate( buffer, accessor, access, &allocation ); if (ret) { if (ret != DFB_NOVIDEOMEMORY && ret != DFB_UNSUPPORTED) D_DERROR( ret, "Core/SurfBuffer: Buffer allocation failed!\n" ); goto out; } allocated = true; } CORE_SURFACE_ALLOCATION_ASSERT( allocation ); /* Synchronize with other allocations. */ ret = dfb_surface_allocation_update( allocation, access ); if (ret) { /* Destroy if newly created. */ if (allocated) dfb_surface_allocation_decouple( allocation ); goto out; } ret = dfb_surface_pool_prelock( allocation->pool, allocation, accessor, access ); if (ret) { /* Destroy if newly created. */ if (allocated) dfb_surface_allocation_decouple( allocation ); goto out; } manage_interlocks( allocation, accessor, access ); dfb_surface_allocation_ref( allocation ); *ret_allocation = allocation; out: dfb_surface_unlock( surface ); return ret; } DFBResult ISurface_Real::PreLockBuffer2( CoreSurfaceBufferRole role, DFBSurfaceStereoEye eye, CoreSurfaceAccessorID accessor, CoreSurfaceAccessFlags access, bool lock, CoreSurfaceAllocation **ret_allocation ) { DFBResult ret; CoreSurfaceBuffer *buffer; CoreSurfaceAllocation *allocation; CoreSurface *surface = obj; bool allocated = false; D_DEBUG_AT( DirectFB_CoreSurface, "ISurface_Real::%s( surface %p, role %d, eye %d, accessor 0x%02x, access 0x%02x, %slock )\n", __FUNCTION__, surface, role, eye, accessor, access, lock ? "" : "no " ); ret = (DFBResult) dfb_surface_lock( surface ); if (ret) return ret; if (surface->num_buffers < 1) { dfb_surface_unlock( surface ); return DFB_BUFFEREMPTY; } buffer = dfb_surface_get_buffer2( surface, role, eye ); D_MAGIC_ASSERT( buffer, CoreSurfaceBuffer ); D_DEBUG_AT( DirectFB_CoreSurface, " -> buffer %p\n", buffer ); if (!lock && access & CSAF_READ) { if (fusion_vector_is_empty( &buffer->allocs )) { dfb_surface_unlock( surface ); return DFB_NOALLOCATION; } } /* Look for allocation with proper access. */ allocation = dfb_surface_buffer_find_allocation( buffer, accessor, access, lock ); if (!allocation) { /* If no allocation exists, create one. */ ret = dfb_surface_pools_allocate( buffer, accessor, access, &allocation ); if (ret) { if (ret != DFB_NOVIDEOMEMORY && ret != DFB_UNSUPPORTED) D_DERROR( ret, "Core/SurfBuffer: Buffer allocation failed!\n" ); goto out; } allocated = true; } CORE_SURFACE_ALLOCATION_ASSERT( allocation ); /* Synchronize with other allocations. */ ret = dfb_surface_allocation_update( allocation, access ); if (ret) { /* Destroy if newly created. */ if (allocated) dfb_surface_allocation_decouple( allocation ); goto out; } if (!lock) { if (access & CSAF_WRITE) { if (!(allocation->pool->desc.caps & CSPCAPS_WRITE)) lock = true; } else if (access & CSAF_READ) { if (!(allocation->pool->desc.caps & CSPCAPS_READ)) lock = true; } } if (lock) { ret = dfb_surface_pool_prelock( allocation->pool, allocation, accessor, access ); if (ret) { /* Destroy if newly created. */ if (allocated) dfb_surface_allocation_decouple( allocation ); goto out; } manage_interlocks( allocation, accessor, access ); } dfb_surface_allocation_ref( allocation ); *ret_allocation = allocation; out: dfb_surface_unlock( surface ); return ret; } DFBResult ISurface_Real::PreReadBuffer( CoreSurfaceBuffer *buffer, const DFBRectangle *rect, CoreSurfaceAllocation **ret_allocation ) { DFBResult ret; CoreSurfaceAllocation *allocation; CoreSurface *surface = obj; bool allocated = false; D_DEBUG_AT( DirectFB_CoreSurface, "ISurface_Real::%s()\n", __FUNCTION__ ); D_MAGIC_ASSERT( buffer, CoreSurfaceBuffer ); dfb_surface_lock( surface ); if (!buffer->surface) { dfb_surface_unlock( surface ); return DFB_BUFFEREMPTY; } /* Use last written allocation if it's up to date... */ if (buffer->written && direct_serial_check( &buffer->written->serial, &buffer->serial )) allocation = buffer->written; else { /* ...otherwise look for allocation with CPU access. */ allocation = dfb_surface_buffer_find_allocation( buffer, CSAID_CPU, CSAF_READ, false ); if (!allocation) { /* If no allocation exists, create one. */ ret = dfb_surface_pools_allocate( buffer, CSAID_CPU, CSAF_READ, &allocation ); if (ret) { D_DERROR( ret, "Core/SurfBuffer: Buffer allocation failed!\n" ); goto out; } allocated = true; } } CORE_SURFACE_ALLOCATION_ASSERT( allocation ); /* Synchronize with other allocations. */ ret = dfb_surface_allocation_update( allocation, CSAF_READ ); if (ret) { /* Destroy if newly created. */ if (allocated) dfb_surface_allocation_decouple( allocation ); goto out; } if (!(allocation->pool->desc.caps & CSPCAPS_READ)) { ret = dfb_surface_pool_prelock( allocation->pool, allocation, CSAID_CPU, CSAF_READ ); if (ret) { /* Destroy if newly created. */ if (allocated) dfb_surface_allocation_decouple( allocation ); goto out; } manage_interlocks( allocation, CSAID_CPU, CSAF_READ ); } dfb_surface_allocation_ref( allocation ); *ret_allocation = allocation; out: dfb_surface_unlock( surface ); return ret; } DFBResult ISurface_Real::PreWriteBuffer( CoreSurfaceBuffer *buffer, const DFBRectangle *rect, CoreSurfaceAllocation **ret_allocation ) { DFBResult ret; CoreSurfaceAllocation *allocation; CoreSurface *surface = obj; bool allocated = false; D_DEBUG_AT( DirectFB_CoreSurface, "ISurface_Real::%s()\n", __FUNCTION__ ); D_MAGIC_ASSERT( buffer, CoreSurfaceBuffer ); dfb_surface_lock( surface ); if (!buffer->surface) { dfb_surface_unlock( surface ); return DFB_BUFFEREMPTY; } /* Use last read allocation if it's up to date... */ if (buffer->read && direct_serial_check( &buffer->read->serial, &buffer->serial )) allocation = buffer->read; else { /* ...otherwise look for allocation with CPU access. */ allocation = dfb_surface_buffer_find_allocation( buffer, CSAID_CPU, CSAF_WRITE, false ); if (!allocation) { /* If no allocation exists, create one. */ ret = dfb_surface_pools_allocate( buffer, CSAID_CPU, CSAF_WRITE, &allocation ); if (ret) { D_DERROR( ret, "Core/SurfBuffer: Buffer allocation failed!\n" ); goto out; } allocated = true; } } CORE_SURFACE_ALLOCATION_ASSERT( allocation ); /* Synchronize with other allocations. */ ret = dfb_surface_allocation_update( allocation, CSAF_WRITE ); if (ret) { /* Destroy if newly created. */ if (allocated) dfb_surface_allocation_decouple( allocation ); goto out; } if (!(allocation->pool->desc.caps & CSPCAPS_WRITE)) { ret = dfb_surface_pool_prelock( allocation->pool, allocation, CSAID_CPU, CSAF_WRITE ); if (ret) { /* Destroy if newly created. */ if (allocated) dfb_surface_allocation_decouple( allocation ); goto out; } manage_interlocks( allocation, CSAID_CPU, CSAF_WRITE ); } dfb_surface_allocation_ref( allocation ); *ret_allocation = allocation; out: dfb_surface_unlock( surface ); return ret; } } <|endoftext|>
<commit_before>#ifdef _MSC_VER // to avoid long name warnings #pragma warning(disable:4786) #endif #include <iostream> #include <fstream> #include <stdexcept> #include <utils/compatibility.h> #include <utils/eoParam.h> #include "FileMonitor.h" using namespace std; namespace dim { namespace utils { void FileMonitor::printHeader(std::ostream& os) { iterator it = vec.begin(); os << (*it)->longName(); ++it; for (; it != vec.end(); ++it) { // use the longName of the eoParam for the header os << delim.c_str() << (*it)->longName(); } os << std::endl; } void FileMonitor::printHeader() { // create file ofstream os(filename.c_str()); if (!os) { string str = "FileMonitor could not open: " + filename; throw runtime_error(str); } printHeader(os); } Monitor& FileMonitor::operator()(void) { if (stepTimer) { #if __cplusplus > 199711L AUTO(typename BOOST_IDENTITY_TYPE((std_or_boost::chrono::time_point<std_or_boost::chrono::system_clock>))) now = std_or_boost::chrono::system_clock::now(); #else AUTO(BOOST_IDENTITY_TYPE((std_or_boost::chrono::time_point<std_or_boost::chrono::system_clock>))) now = std_or_boost::chrono::system_clock::now(); #endif AUTO(unsigned) elapsed = std_or_boost::chrono::duration_cast<std_or_boost::chrono::milliseconds>(now-start).count(); elapsed /= stepTimer; if ( elapsed <= lastElapsedTime ) { return *this; } lastElapsedTime = elapsed; } else { if (counter % frequency) { counter++; return *this; } counter++; } ofstream os(filename.c_str(), overwrite ? ios_base::out|ios_base::trunc // truncate : ios_base::out|ios_base::app // append ); if (!os) { string str = "FileMonitor could not write to: " + filename; throw runtime_error(str); } if ( header // we want to write headers && firstcall // we do not want to write headers twice && !keep // if we append to an existing file, headers are useless && !overwrite // we do not want to write headers if the file is to be overwriten ) { printHeader(); firstcall = false; } return operator()(os); } Monitor& FileMonitor::operator()(std::ostream& os) { iterator it = vec.begin(); os << (*it)->getValue(); for(++it; it != vec.end(); ++it) { os << delim.c_str() << (*it)->getValue(); } os << std::endl; return *this; } } // !utils } // !dim <commit_msg>* ../src/dim/utils/FileMonitor.cpp: simplified<commit_after>#ifdef _MSC_VER // to avoid long name warnings #pragma warning(disable:4786) #endif #include <iostream> #include <fstream> #include <stdexcept> #include <utils/compatibility.h> #include <utils/eoParam.h> #include "FileMonitor.h" using namespace std; namespace dim { namespace utils { void FileMonitor::printHeader(std::ostream& os) { iterator it = vec.begin(); os << (*it)->longName(); ++it; for (; it != vec.end(); ++it) { // use the longName of the eoParam for the header os << delim.c_str() << (*it)->longName(); } os << std::endl; } void FileMonitor::printHeader() { // create file ofstream os(filename.c_str()); if (!os) { string str = "FileMonitor could not open: " + filename; throw runtime_error(str); } printHeader(os); } Monitor& FileMonitor::operator()(void) { if (stepTimer) { #if __cplusplus > 199711L AUTO(typename BOOST_IDENTITY_TYPE((std_or_boost::chrono::time_point<std_or_boost::chrono::system_clock>))) now = std_or_boost::chrono::system_clock::now(); #else AUTO(BOOST_IDENTITY_TYPE((std_or_boost::chrono::time_point<std_or_boost::chrono::system_clock>))) now = std_or_boost::chrono::system_clock::now(); #endif AUTO(unsigned) elapsed = std_or_boost::chrono::duration_cast<std_or_boost::chrono::milliseconds>(now-start).count(); elapsed /= stepTimer; if ( !elapsed ) { return *this; } start = now; } else { if (counter % frequency) { counter++; return *this; } counter++; } ofstream os(filename.c_str(), overwrite ? ios_base::out|ios_base::trunc // truncate : ios_base::out|ios_base::app // append ); if (!os) { string str = "FileMonitor could not write to: " + filename; throw runtime_error(str); } if ( header // we want to write headers && firstcall // we do not want to write headers twice && !keep // if we append to an existing file, headers are useless && !overwrite // we do not want to write headers if the file is to be overwriten ) { printHeader(); firstcall = false; } return operator()(os); } Monitor& FileMonitor::operator()(std::ostream& os) { iterator it = vec.begin(); os << (*it)->getValue(); for(++it; it != vec.end(); ++it) { os << delim.c_str() << (*it)->getValue(); } os << std::endl; // os.flush(); return *this; } } // !utils } // !dim <|endoftext|>
<commit_before>#include "catalog_queries.h" #include <cstdlib> #include "catalog.h" #include "logging.h" using namespace std; namespace catalog { SqlStatement::SqlStatement(const sqlite3 *database, const std::string &statement) { Init(database, statement); } SqlStatement::~SqlStatement() { last_error_code_ = sqlite3_finalize(statement_); if (not Successful()) { LogCvmfs(kLogSql, kLogDebug, "FAILED to finalize statement - error code: %d", last_error_code_); } LogCvmfs(kLogSql, kLogDebug, "successfully finalized statement"); } bool SqlStatement::Init(const sqlite3 *database, const std::string &statement) { last_error_code_ = sqlite3_prepare_v2((sqlite3*)database, statement.c_str(), -1, // parse until null termination &statement_, NULL); if (not Successful()) { LogCvmfs(kLogSql, kLogDebug, "FAILED to prepare statement '%s' - error code: %d", statement.c_str(), GetLastError()); LogCvmfs(kLogSql, kLogDebug, "Error message: '%s'", sqlite3_errmsg((sqlite3*)database)); return false; } LogCvmfs(kLogSql, kLogDebug, "successfully prepared statement '%s'", statement.c_str()); return true; } // // ########################################################################### // ### ### ### ### ### ### ### ### ### ### ### ### ### // ########################################################################### // unsigned int DirectoryEntrySqlStatement::CreateDatabaseFlags(const DirectoryEntry &entry) const { unsigned int database_flags = 0; if (entry.IsNestedCatalogRoot()) { database_flags |= kFlagDirNestedRoot; } if (entry.IsNestedCatalogMountpoint()) { database_flags |= kFlagDirNestedMountpoint; } if (entry.IsDirectory()) { database_flags |= kFlagDir; } else if (entry.IsLink()) { database_flags |= kFlagFile | kFlagLink; } else { database_flags |= kFlagFile; } database_flags = SetLinkcountInFlags(database_flags, entry.linkcount()); return database_flags; } std::string DirectoryEntrySqlStatement::ExpandSymlink(const std::string raw_symlink) const { string result = ""; for (string::size_type i = 0; i < raw_symlink.length(); i++) { string::size_type lpar; string::size_type rpar; if ((raw_symlink[i] == '$') && ((lpar = raw_symlink.find('(', i+1)) != string::npos) && ((rpar = raw_symlink.find(')', i+2)) != string::npos) && (rpar > lpar)) { string var = raw_symlink.substr(lpar + 1, rpar-lpar-1); char *var_exp = getenv(var.c_str()); /* Don't free! Nothing is allocated here */ if (var_exp) { result += var_exp; } i = rpar; } else { result += raw_symlink[i]; } } return result; } // // ########################################################################### // ### ### ### ### ### ### ### ### ### ### ### ### ### // ########################################################################### // bool ManipulateDirectoryEntrySqlStatement::BindDirectoryEntryFields(const int hash_field, const int inode_field, const int size_field, const int mode_field, const int mtime_field, const int flags_field, const int name_field, const int symlink_field, const DirectoryEntry &entry) { return ( BindSha1Hash( hash_field, entry.checksum_) && BindInt64( inode_field, entry.hardlink_group_id_) && // quirky database layout here ( legacy ;-) ) BindInt64( size_field, entry.size_) && BindInt( mode_field, entry.mode_) && BindInt64( mtime_field, entry.mtime_) && BindInt( flags_field, CreateDatabaseFlags(entry)) && BindText( name_field, entry.name_) && BindText( symlink_field, entry.symlink_) ); } // // ########################################################################### // ### ### ### ### ### ### ### ### ### ### ### ### ### // ########################################################################### // std::string LookupSqlStatement::GetFieldsToSelect() const { return "hash, inode, size, mode, mtime, flags, name, symlink, md5path_1, md5path_2, parent_1, parent_2, rowid"; // 0 1 2 3 4 5 6 7 8 9 10 11 12 } hash::Md5 LookupSqlStatement::GetPathHash() const { return RetrieveMd5Hash(8, 9); } hash::Md5 LookupSqlStatement::GetParentPathHash() const { return RetrieveMd5Hash(10, 11); } DirectoryEntry LookupSqlStatement::GetDirectoryEntry(const Catalog *catalog) const { // fill the directory entry // (this method is a friend of DirectoryEntry ;-) ) DirectoryEntry result; // read administrative stuff from the result int database_flags = RetrieveInt(5); result.catalog_ = (Catalog*)catalog; result.is_nested_catalog_root_ = (database_flags & kFlagDirNestedRoot); result.is_nested_catalog_mountpoint_ = (database_flags & kFlagDirNestedMountpoint); result.hardlink_group_id_ = RetrieveInt64(1); // quirky database layout here ( legacy ;-) ) // read the usual file information result.inode_ = ((Catalog*)catalog)->GetMangledInode(RetrieveInt64(12), RetrieveInt64(1)); result.parent_inode_ = DirectoryEntry::kInvalidInode; // must be set later by a second catalog lookup result.linkcount_ = GetLinkcountFromFlags(database_flags); result.mode_ = RetrieveInt(3); result.size_ = RetrieveInt64(2); result.mtime_ = RetrieveInt64(4); result.checksum_ = RetrieveSha1HashFromBlob(0); result.name_ = string((char *)RetrieveText(6)); result.symlink_ = ExpandSymlink((char *)RetrieveText(7)); return result; } // // ########################################################################### // ### ### ### ### ### ### ### ### ### ### ### ### ### // ########################################################################### // ListingLookupSqlStatement::ListingLookupSqlStatement(const sqlite3 *database) { std::ostringstream statement; statement << "SELECT " << GetFieldsToSelect() << " FROM catalog " "WHERE (parent_1 = :p_1) AND (parent_2 = :p_2);"; Init(database, statement.str()); } bool ListingLookupSqlStatement::BindPathHash(const struct hash::Md5 &hash) { return BindMd5Hash(1, 2, hash); } // // ########################################################################### // ### ### ### ### ### ### ### ### ### ### ### ### ### // ########################################################################### // PathHashLookupSqlStatement::PathHashLookupSqlStatement(const sqlite3 *database) { std::ostringstream statement; statement << "SELECT " << GetFieldsToSelect() << " FROM catalog " "WHERE (md5path_1 = :md5_1) AND (md5path_2 = :md5_2);"; Init(database, statement.str()); } bool PathHashLookupSqlStatement::BindPathHash(const struct hash::Md5 &hash) { return BindMd5Hash(1, 2, hash); } // // ########################################################################### // ### ### ### ### ### ### ### ### ### ### ### ### ### // ########################################################################### // InodeLookupSqlStatement::InodeLookupSqlStatement(const sqlite3 *database) { std::ostringstream statement; statement << "SELECT " << GetFieldsToSelect() << " FROM catalog " "WHERE rowid = :rowid;"; Init(database, statement.str()); } bool InodeLookupSqlStatement::BindRowId(const uint64_t inode) { return BindInt64(1, inode); } // // ########################################################################### // ### ### ### ### ### ### ### ### ### ### ### ### ### // ########################################################################### // FindNestedCatalogSqlStatement::FindNestedCatalogSqlStatement(const sqlite3 *database) { Init(database, "SELECT sha1 FROM nested_catalogs WHERE path=:path;"); } bool FindNestedCatalogSqlStatement::BindSearchPath(const std::string &path) { return BindText(1, &path[0], path.length(), SQLITE_STATIC); } hash::Any FindNestedCatalogSqlStatement::GetContentHash() const { const std::string sha1_str = std::string((char *)RetrieveText(0)); return hash::Any(hash::kSha1, hash::HexPtr(sha1_str)); } // // ########################################################################### // ### ### ### ### ### ### ### ### ### ### ### ### ### // ########################################################################### // ListNestedCatalogsSqlStatement::ListNestedCatalogsSqlStatement(const sqlite3 *database) { Init(database, "SELECT path, sha1 FROM nested_catalogs;"); } string ListNestedCatalogsSqlStatement::GetMountpoint() const { return string((char*)RetrieveText(0)); } hash::Any ListNestedCatalogsSqlStatement::GetContentHash() const { const std::string sha1_str = std::string((char *)RetrieveText(1)); return hash::Any(hash::kSha1, hash::HexPtr(sha1_str)); } // // ########################################################################### // ### ### ### ### ### ### ### ### ### ### ### ### ### // ########################################################################### // InsertDirectoryEntrySqlStatement::InsertDirectoryEntrySqlStatement(const sqlite3 *database) { Init(database, "INSERT INTO catalog " // 1 2 3 4 5 6 7 8 9 10 11 12 "(md5path_1, md5path_2, parent_1, parent_2, hash, inode, size, mode, mtime, flags, name, symlink) " "VALUES (:md5_1, :md5_2, :p_1, :p_2, :hash, :ino, :size, :mode, :mtime, :flags, :name, :symlink);"); } bool InsertDirectoryEntrySqlStatement::BindPathHash(const hash::Md5 &hash) { return BindMd5Hash(1, 2, hash); } bool InsertDirectoryEntrySqlStatement::BindParentPathHash(const hash::Md5 &hash) { return BindMd5Hash(3, 4, hash); } bool InsertDirectoryEntrySqlStatement::BindDirectoryEntry(const DirectoryEntry &entry) { return BindDirectoryEntryFields(5,6,7,8,9,10,11,12, entry); } // // ########################################################################### // ### ### ### ### ### ### ### ### ### ### ### ### ### // ########################################################################### // UpdateDirectoryEntrySqlStatement::UpdateDirectoryEntrySqlStatement(const sqlite3 *database) { Init(database, "UPDATE catalog " // 1 2 3 4 "SET hash = :hash, size = :size, mode = :mode, mtime = :mtime, " // 5 6 7 8 "flags = :flags, name = :name, symlink = :symlink, inode = :inode " // 9 10 "WHERE (md5path_1 = :md5_1) AND (md5path_2 = :md5_2);"); } bool UpdateDirectoryEntrySqlStatement::BindPathHash(const hash::Md5 &hash) { return BindMd5Hash(9, 10, hash); } bool UpdateDirectoryEntrySqlStatement::BindDirectoryEntry(const DirectoryEntry &entry) { return BindDirectoryEntryFields(1,8,2,3,4,5,6,7, entry); } // // ########################################################################### // ### ### ### ### ### ### ### ### ### ### ### ### ### // ########################################################################### // TouchSqlStatement::TouchSqlStatement(const sqlite3 *database) { Init(database, "UPDATE catalog SET mtime = :mtime " "WHERE (md5path_1 = :md5_1) AND (md5path_2 = :md5_2);"); } bool TouchSqlStatement::BindPathHash(const hash::Md5 &hash) { return BindMd5Hash(2, 3, hash); } bool TouchSqlStatement::BindTimestamp(const time_t timestamp) { return BindInt64(1, timestamp); } // // ########################################################################### // ### ### ### ### ### ### ### ### ### ### ### ### ### // ########################################################################### // UnlinkSqlStatement::UnlinkSqlStatement(const sqlite3 *database) { Init(database, "DELETE FROM catalog " "WHERE (md5path_1 = :md5_1) AND (md5path_2 = :md5_2);"); } bool UnlinkSqlStatement::BindPathHash(const hash::Md5 &hash) { return BindMd5Hash(1, 2, hash); } // // ########################################################################### // ### ### ### ### ### ### ### ### ### ### ### ### ### // ########################################################################### // GetMaximalHardlinkGroupIdStatement::GetMaximalHardlinkGroupIdStatement(const sqlite3 *database) { Init(database, "SELECT max(inode) FROM catalog;"); } int GetMaximalHardlinkGroupIdStatement::GetMaximalGroupId() const { return RetrieveInt64(0); } } // namespace cvmfs <commit_msg>Bugfix: Newly created Nested Catalogs do not have a valid content hash, yet. hash::Digest(...) failed by assertion<commit_after>#include "catalog_queries.h" #include <cstdlib> #include "catalog.h" #include "logging.h" using namespace std; namespace catalog { SqlStatement::SqlStatement(const sqlite3 *database, const std::string &statement) { Init(database, statement); } SqlStatement::~SqlStatement() { last_error_code_ = sqlite3_finalize(statement_); if (not Successful()) { LogCvmfs(kLogSql, kLogDebug, "FAILED to finalize statement - error code: %d", last_error_code_); } LogCvmfs(kLogSql, kLogDebug, "successfully finalized statement"); } bool SqlStatement::Init(const sqlite3 *database, const std::string &statement) { last_error_code_ = sqlite3_prepare_v2((sqlite3*)database, statement.c_str(), -1, // parse until null termination &statement_, NULL); if (not Successful()) { LogCvmfs(kLogSql, kLogDebug, "FAILED to prepare statement '%s' - error code: %d", statement.c_str(), GetLastError()); LogCvmfs(kLogSql, kLogDebug, "Error message: '%s'", sqlite3_errmsg((sqlite3*)database)); return false; } LogCvmfs(kLogSql, kLogDebug, "successfully prepared statement '%s'", statement.c_str()); return true; } // // ########################################################################### // ### ### ### ### ### ### ### ### ### ### ### ### ### // ########################################################################### // unsigned int DirectoryEntrySqlStatement::CreateDatabaseFlags(const DirectoryEntry &entry) const { unsigned int database_flags = 0; if (entry.IsNestedCatalogRoot()) { database_flags |= kFlagDirNestedRoot; } if (entry.IsNestedCatalogMountpoint()) { database_flags |= kFlagDirNestedMountpoint; } if (entry.IsDirectory()) { database_flags |= kFlagDir; } else if (entry.IsLink()) { database_flags |= kFlagFile | kFlagLink; } else { database_flags |= kFlagFile; } database_flags = SetLinkcountInFlags(database_flags, entry.linkcount()); return database_flags; } std::string DirectoryEntrySqlStatement::ExpandSymlink(const std::string raw_symlink) const { string result = ""; for (string::size_type i = 0; i < raw_symlink.length(); i++) { string::size_type lpar; string::size_type rpar; if ((raw_symlink[i] == '$') && ((lpar = raw_symlink.find('(', i+1)) != string::npos) && ((rpar = raw_symlink.find(')', i+2)) != string::npos) && (rpar > lpar)) { string var = raw_symlink.substr(lpar + 1, rpar-lpar-1); char *var_exp = getenv(var.c_str()); /* Don't free! Nothing is allocated here */ if (var_exp) { result += var_exp; } i = rpar; } else { result += raw_symlink[i]; } } return result; } // // ########################################################################### // ### ### ### ### ### ### ### ### ### ### ### ### ### // ########################################################################### // bool ManipulateDirectoryEntrySqlStatement::BindDirectoryEntryFields(const int hash_field, const int inode_field, const int size_field, const int mode_field, const int mtime_field, const int flags_field, const int name_field, const int symlink_field, const DirectoryEntry &entry) { return ( BindSha1Hash( hash_field, entry.checksum_) && BindInt64( inode_field, entry.hardlink_group_id_) && // quirky database layout here ( legacy ;-) ) BindInt64( size_field, entry.size_) && BindInt( mode_field, entry.mode_) && BindInt64( mtime_field, entry.mtime_) && BindInt( flags_field, CreateDatabaseFlags(entry)) && BindText( name_field, entry.name_) && BindText( symlink_field, entry.symlink_) ); } // // ########################################################################### // ### ### ### ### ### ### ### ### ### ### ### ### ### // ########################################################################### // std::string LookupSqlStatement::GetFieldsToSelect() const { return "hash, inode, size, mode, mtime, flags, name, symlink, md5path_1, md5path_2, parent_1, parent_2, rowid"; // 0 1 2 3 4 5 6 7 8 9 10 11 12 } hash::Md5 LookupSqlStatement::GetPathHash() const { return RetrieveMd5Hash(8, 9); } hash::Md5 LookupSqlStatement::GetParentPathHash() const { return RetrieveMd5Hash(10, 11); } DirectoryEntry LookupSqlStatement::GetDirectoryEntry(const Catalog *catalog) const { // fill the directory entry // (this method is a friend of DirectoryEntry ;-) ) DirectoryEntry result; // read administrative stuff from the result int database_flags = RetrieveInt(5); result.catalog_ = (Catalog*)catalog; result.is_nested_catalog_root_ = (database_flags & kFlagDirNestedRoot); result.is_nested_catalog_mountpoint_ = (database_flags & kFlagDirNestedMountpoint); result.hardlink_group_id_ = RetrieveInt64(1); // quirky database layout here ( legacy ;-) ) // read the usual file information result.inode_ = ((Catalog*)catalog)->GetMangledInode(RetrieveInt64(12), RetrieveInt64(1)); result.parent_inode_ = DirectoryEntry::kInvalidInode; // must be set later by a second catalog lookup result.linkcount_ = GetLinkcountFromFlags(database_flags); result.mode_ = RetrieveInt(3); result.size_ = RetrieveInt64(2); result.mtime_ = RetrieveInt64(4); result.checksum_ = RetrieveSha1HashFromBlob(0); result.name_ = string((char *)RetrieveText(6)); result.symlink_ = ExpandSymlink((char *)RetrieveText(7)); return result; } // // ########################################################################### // ### ### ### ### ### ### ### ### ### ### ### ### ### // ########################################################################### // ListingLookupSqlStatement::ListingLookupSqlStatement(const sqlite3 *database) { std::ostringstream statement; statement << "SELECT " << GetFieldsToSelect() << " FROM catalog " "WHERE (parent_1 = :p_1) AND (parent_2 = :p_2);"; Init(database, statement.str()); } bool ListingLookupSqlStatement::BindPathHash(const struct hash::Md5 &hash) { return BindMd5Hash(1, 2, hash); } // // ########################################################################### // ### ### ### ### ### ### ### ### ### ### ### ### ### // ########################################################################### // PathHashLookupSqlStatement::PathHashLookupSqlStatement(const sqlite3 *database) { std::ostringstream statement; statement << "SELECT " << GetFieldsToSelect() << " FROM catalog " "WHERE (md5path_1 = :md5_1) AND (md5path_2 = :md5_2);"; Init(database, statement.str()); } bool PathHashLookupSqlStatement::BindPathHash(const struct hash::Md5 &hash) { return BindMd5Hash(1, 2, hash); } // // ########################################################################### // ### ### ### ### ### ### ### ### ### ### ### ### ### // ########################################################################### // InodeLookupSqlStatement::InodeLookupSqlStatement(const sqlite3 *database) { std::ostringstream statement; statement << "SELECT " << GetFieldsToSelect() << " FROM catalog " "WHERE rowid = :rowid;"; Init(database, statement.str()); } bool InodeLookupSqlStatement::BindRowId(const uint64_t inode) { return BindInt64(1, inode); } // // ########################################################################### // ### ### ### ### ### ### ### ### ### ### ### ### ### // ########################################################################### // FindNestedCatalogSqlStatement::FindNestedCatalogSqlStatement(const sqlite3 *database) { Init(database, "SELECT sha1 FROM nested_catalogs WHERE path=:path;"); } bool FindNestedCatalogSqlStatement::BindSearchPath(const std::string &path) { return BindText(1, &path[0], path.length(), SQLITE_STATIC); } hash::Any FindNestedCatalogSqlStatement::GetContentHash() const { const std::string sha1_str = std::string((char *)RetrieveText(0)); return (sha1_str.empty()) ? hash::Any(hash::kSha1) : hash::Any(hash::kSha1, hash::HexPtr(sha1_str)); } // // ########################################################################### // ### ### ### ### ### ### ### ### ### ### ### ### ### // ########################################################################### // ListNestedCatalogsSqlStatement::ListNestedCatalogsSqlStatement(const sqlite3 *database) { Init(database, "SELECT path, sha1 FROM nested_catalogs;"); } string ListNestedCatalogsSqlStatement::GetMountpoint() const { return string((char*)RetrieveText(0)); } hash::Any ListNestedCatalogsSqlStatement::GetContentHash() const { const std::string sha1_str = std::string((char *)RetrieveText(1)); return (sha1_str.empty()) ? hash::Any(hash::kSha1) : hash::Any(hash::kSha1, hash::HexPtr(sha1_str)); } // // ########################################################################### // ### ### ### ### ### ### ### ### ### ### ### ### ### // ########################################################################### // InsertDirectoryEntrySqlStatement::InsertDirectoryEntrySqlStatement(const sqlite3 *database) { Init(database, "INSERT INTO catalog " // 1 2 3 4 5 6 7 8 9 10 11 12 "(md5path_1, md5path_2, parent_1, parent_2, hash, inode, size, mode, mtime, flags, name, symlink) " "VALUES (:md5_1, :md5_2, :p_1, :p_2, :hash, :ino, :size, :mode, :mtime, :flags, :name, :symlink);"); } bool InsertDirectoryEntrySqlStatement::BindPathHash(const hash::Md5 &hash) { return BindMd5Hash(1, 2, hash); } bool InsertDirectoryEntrySqlStatement::BindParentPathHash(const hash::Md5 &hash) { return BindMd5Hash(3, 4, hash); } bool InsertDirectoryEntrySqlStatement::BindDirectoryEntry(const DirectoryEntry &entry) { return BindDirectoryEntryFields(5,6,7,8,9,10,11,12, entry); } // // ########################################################################### // ### ### ### ### ### ### ### ### ### ### ### ### ### // ########################################################################### // UpdateDirectoryEntrySqlStatement::UpdateDirectoryEntrySqlStatement(const sqlite3 *database) { Init(database, "UPDATE catalog " // 1 2 3 4 "SET hash = :hash, size = :size, mode = :mode, mtime = :mtime, " // 5 6 7 8 "flags = :flags, name = :name, symlink = :symlink, inode = :inode " // 9 10 "WHERE (md5path_1 = :md5_1) AND (md5path_2 = :md5_2);"); } bool UpdateDirectoryEntrySqlStatement::BindPathHash(const hash::Md5 &hash) { return BindMd5Hash(9, 10, hash); } bool UpdateDirectoryEntrySqlStatement::BindDirectoryEntry(const DirectoryEntry &entry) { return BindDirectoryEntryFields(1,8,2,3,4,5,6,7, entry); } // // ########################################################################### // ### ### ### ### ### ### ### ### ### ### ### ### ### // ########################################################################### // TouchSqlStatement::TouchSqlStatement(const sqlite3 *database) { Init(database, "UPDATE catalog SET mtime = :mtime " "WHERE (md5path_1 = :md5_1) AND (md5path_2 = :md5_2);"); } bool TouchSqlStatement::BindPathHash(const hash::Md5 &hash) { return BindMd5Hash(2, 3, hash); } bool TouchSqlStatement::BindTimestamp(const time_t timestamp) { return BindInt64(1, timestamp); } // // ########################################################################### // ### ### ### ### ### ### ### ### ### ### ### ### ### // ########################################################################### // UnlinkSqlStatement::UnlinkSqlStatement(const sqlite3 *database) { Init(database, "DELETE FROM catalog " "WHERE (md5path_1 = :md5_1) AND (md5path_2 = :md5_2);"); } bool UnlinkSqlStatement::BindPathHash(const hash::Md5 &hash) { return BindMd5Hash(1, 2, hash); } // // ########################################################################### // ### ### ### ### ### ### ### ### ### ### ### ### ### // ########################################################################### // GetMaximalHardlinkGroupIdStatement::GetMaximalHardlinkGroupIdStatement(const sqlite3 *database) { Init(database, "SELECT max(inode) FROM catalog;"); } int GetMaximalHardlinkGroupIdStatement::GetMaximalGroupId() const { return RetrieveInt64(0); } } // namespace cvmfs <|endoftext|>
<commit_before>/* -*-c++-*- * * Copyright (C) 2006-2007 Mathias Froehlich * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. * */ #ifdef HAVE_CONFIG_H # include <simgear_config.h> #endif #include <osgDB/Registry> #include <osgDB/Input> #include <osgDB/Output> #include "SGTranslateTransform.hxx" static inline void set_translation (osg::Matrix &matrix, double position_m, const SGVec3d &axis) { SGVec3d xyz = axis * position_m; matrix.makeIdentity(); matrix(3, 0) = xyz[0]; matrix(3, 1) = xyz[1]; matrix(3, 2) = xyz[2]; } SGTranslateTransform::SGTranslateTransform() : _axis(0, 0, 0), _value(0) { setReferenceFrame(RELATIVE_RF); } SGTranslateTransform::SGTranslateTransform(const SGTranslateTransform& trans, const osg::CopyOp& copyop) : osg::Transform(trans, copyop), _axis(trans._axis), _value(trans._value) { } bool SGTranslateTransform::computeLocalToWorldMatrix(osg::Matrix& matrix, osg::NodeVisitor* nv) const { if (_referenceFrame == RELATIVE_RF) { osg::Matrix tmp; set_translation(tmp, _value, _axis); matrix.preMult(tmp); } else { osg::Matrix tmp; set_translation(tmp, _value, _axis); matrix = tmp; } return true; } bool SGTranslateTransform::computeWorldToLocalMatrix(osg::Matrix& matrix, osg::NodeVisitor* nv) const { if (_referenceFrame == RELATIVE_RF) { osg::Matrix tmp; set_translation(tmp, -_value, _axis); matrix.postMult(tmp); } else { osg::Matrix tmp; set_translation(tmp, -_value, _axis); matrix = tmp; } return true; } osg::BoundingSphere SGTranslateTransform::computeBound() const { osg::BoundingSphere bs = osg::Group::computeBound(); bs._center += _axis.osg()*_value; return bs; } namespace { bool TranslateTransform_readLocalData(osg::Object& obj, osgDB::Input& fr) { SGTranslateTransform& trans = static_cast<SGTranslateTransform&>(obj); if (fr[0].matchWord("axis")) { ++fr; SGVec3d axis; if (fr.readSequence(axis.osg())) fr += 3; else return false; trans.setAxis(axis); } if (fr[0].matchWord("value")) { ++fr; double value; if (fr[0].getFloat(value)) ++fr; else return false; trans.setValue(value); } return true; } bool TranslateTransform_writeLocalData(const osg::Object& obj, osgDB::Output& fw) { const SGTranslateTransform& trans = static_cast<const SGTranslateTransform&>(obj); const SGVec3d& axis = trans.getAxis(); double value = trans.getValue(); fw.indent() << "axis "; for (int i = 0; i < 3; i++) fw << axis(i) << " "; fw << std::endl; fw.indent() << "value " << value << std::endl; return true; } } osgDB::RegisterDotOsgWrapperProxy g_SGTranslateTransformProxy ( new SGTranslateTransform, "SGTranslateTransform", "Object Node Transform SGTranslateTransform Group", &TranslateTransform_readLocalData, &TranslateTransform_writeLocalData ); <commit_msg>Make use of optimized matrix multiplication routines in osg.<commit_after>/* -*-c++-*- * * Copyright (C) 2006-2007 Mathias Froehlich * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. * */ #ifdef HAVE_CONFIG_H # include <simgear_config.h> #endif #include <osgDB/Registry> #include <osgDB/Input> #include <osgDB/Output> #include "SGTranslateTransform.hxx" SGTranslateTransform::SGTranslateTransform() : _axis(0, 0, 0), _value(0) { setReferenceFrame(RELATIVE_RF); } SGTranslateTransform::SGTranslateTransform(const SGTranslateTransform& trans, const osg::CopyOp& copyop) : osg::Transform(trans, copyop), _axis(trans._axis), _value(trans._value) { } bool SGTranslateTransform::computeLocalToWorldMatrix(osg::Matrix& matrix, osg::NodeVisitor* nv) const { if (_referenceFrame == RELATIVE_RF) { matrix.preMultTranslate((_value*_axis).osg()); } else { matrix.setTrans((_value*_axis).osg()); } return true; } bool SGTranslateTransform::computeWorldToLocalMatrix(osg::Matrix& matrix, osg::NodeVisitor* nv) const { if (_referenceFrame == RELATIVE_RF) { matrix.postMultTranslate((-_value*_axis).osg()); } else { matrix.setTrans((-_value*_axis).osg()); } return true; } osg::BoundingSphere SGTranslateTransform::computeBound() const { osg::BoundingSphere bs = osg::Group::computeBound(); bs._center += _axis.osg()*_value; return bs; } namespace { bool TranslateTransform_readLocalData(osg::Object& obj, osgDB::Input& fr) { SGTranslateTransform& trans = static_cast<SGTranslateTransform&>(obj); if (fr[0].matchWord("axis")) { ++fr; SGVec3d axis; if (fr.readSequence(axis.osg())) fr += 3; else return false; trans.setAxis(axis); } if (fr[0].matchWord("value")) { ++fr; double value; if (fr[0].getFloat(value)) ++fr; else return false; trans.setValue(value); } return true; } bool TranslateTransform_writeLocalData(const osg::Object& obj, osgDB::Output& fw) { const SGTranslateTransform& trans = static_cast<const SGTranslateTransform&>(obj); const SGVec3d& axis = trans.getAxis(); double value = trans.getValue(); fw.indent() << "axis "; for (int i = 0; i < 3; i++) fw << axis(i) << " "; fw << std::endl; fw.indent() << "value " << value << std::endl; return true; } } osgDB::RegisterDotOsgWrapperProxy g_SGTranslateTransformProxy ( new SGTranslateTransform, "SGTranslateTransform", "Object Node Transform SGTranslateTransform Group", &TranslateTransform_readLocalData, &TranslateTransform_writeLocalData ); <|endoftext|>
<commit_before>/* File sections: * Service: constructors, destructors * Chain: functions directly related to the building and analysis of chains * Solution: functions directly related to the solution of a (sub)problem * Utility: advanced member access such as searching and counting * List: maintenance of lists or arrays of objects */ #include "NuclearData.h" #include "truncate.h" #include "Calc/VolFlux.h" #include "DataLib/DataLib.h" /*************************** ********* Service ********* **************************/ int NuclearData::nGroups = 0; DataLib* NuclearData::dataLib = NULL; int NuclearData::mode = MODE_FORWARD; /* basic constructor for NuclearData base class */ NuclearData::NuclearData() { nPaths=-1; relations=NULL; emitted=NULL; single=NULL; paths=NULL; P=NULL; D=NULL; for (int dHeat=0;dHeat<3;dHeat++) E[dHeat] = 0; } NuclearData::NuclearData(const NuclearData& n) { int rxnNum,gNum; /* set dimension */ nPaths = n.nPaths; /* initialize all pointers to NULL */ relations=NULL; emitted=NULL; single=NULL; paths=NULL; P=NULL; D=NULL; for (int dHeat=0;dHeat<3;dHeat++) E[dHeat] = 0; if (nPaths < 0) return; /* allocate storage */ /* if there are any paths other than total */ if (nPaths>0) { relations = new int[nPaths]; memCheck(relations,"NuclearData::NuclearData(...) copy constructor: relations"); emitted = new char*[nPaths]; memCheck(emitted,"NuclearData::NuclearData(...) copy constructor: emitted"); } paths = new double*[nPaths+1]; memCheck(paths,"NuclearData::NuclearData(...) copy constructor: paths"); /* copy data */ for (rxnNum=0;rxnNum<nPaths;rxnNum++) { relations[rxnNum] = n.relations[rxnNum]; emitted[rxnNum] = new char[strlen(n.emitted[rxnNum])+1]; memCheck(emitted[rxnNum],"NuclearData::NuclearData(...) copy constructor: emitted[n]"); strcpy(emitted[rxnNum],n.emitted[rxnNum]); paths[rxnNum] = new double[nGroups+1]; memCheck(paths[rxnNum],"NuclearData::NuclearData(...) copy constructor: paths[n]"); for (gNum=0;gNum<=nGroups;gNum++) paths[rxnNum][gNum] = n.paths[rxnNum][gNum]; /* check for pointing of D and P */ if (n.D == n.paths[rxnNum]) { D = paths[rxnNum]; P = single; } if (n.P == n.paths[rxnNum]) { P = paths[rxnNum]; D = single; } } /* allocate storage for total of paths and single xsection */ paths[nPaths] = new double[nGroups+1]; memCheck(paths[rxnNum],"NuclearData::NuclearData(...) copy constructor: paths[n]"); single = new double[nGroups+1]; memCheck(single,"NuclearData::NuclearData(...) copy constructor: single"); for (gNum=0;gNum<=nGroups;gNum++) { paths[rxnNum][gNum] = n.paths[rxnNum][gNum]; single[gNum] = n.single[gNum]; } /* check for pointing of D and P */ if (n.D == n.paths[rxnNum]) { D = paths[rxnNum]; P = single; } if (n.P == n.paths[rxnNum]) { P = paths[rxnNum]; D = single; } E[0] = n.E[0]; E[1] = n.E[1]; E[3] = n.E[2]; } /* basic destructor for NuclearData */ NuclearData::~NuclearData() { cleanUp(); delete single; single = NULL; P = NULL; } NuclearData& NuclearData::operator=(const NuclearData& n) { if (this == &n) return *this; int rxnNum,gNum; cleanUp(); delete single; single = NULL; P = NULL; nPaths = n.nPaths; if (nPaths < 0) return *this; /* only need relations and emitted if nPaths > 0 */ if (nPaths>0) { relations = new int[nPaths]; memCheck(relations,"NuclearData::NuclearData(...) copy constructor: relations"); emitted = new char*[nPaths]; memCheck(emitted,"NuclearData::NuclearData(...) copy constructor: emitted"); } /* always need paths */ paths = new double*[nPaths+1]; memCheck(paths,"NuclearData::NuclearData(...) copy constructor: paths"); /* copy data */ for (rxnNum=0;rxnNum<nPaths;rxnNum++) { relations[rxnNum] = n.relations[rxnNum]; emitted[rxnNum] = new char[strlen(n.emitted[rxnNum])+1]; memCheck(emitted[rxnNum],"NuclearData::NuclearData(...) copy constructor: emitted[n]"); strcpy(emitted[rxnNum],n.emitted[rxnNum]); paths[rxnNum] = new double[nGroups+1]; memCheck(paths[rxnNum],"NuclearData::NuclearData(...) copy constructor: paths[n]"); for (gNum=0;gNum<=nGroups;gNum++) paths[rxnNum][gNum] = n.paths[rxnNum][gNum]; if (n.D == n.paths[rxnNum]) { D = paths[rxnNum]; P = single; } if (n.P == n.paths[rxnNum]) { P = paths[rxnNum]; D = single; } } /* allocate and fill total xsections */ paths[nPaths] = new double[nGroups+1]; memCheck(paths[nPaths],"NuclearData::NuclearData(...) copy constructor: paths[n]"); single = new double[nGroups+1]; memCheck(single,"NuclearData::NuclearData(...) copy constructor: single"); for (gNum=0;gNum<=nGroups;gNum++) { paths[rxnNum][gNum] = n.paths[rxnNum][gNum]; single[gNum] = n.single[gNum]; } if (n.D == n.paths[rxnNum]) { D = paths[rxnNum]; P = single; } if (n.P == n.paths[rxnNum]) { P = paths[rxnNum]; D = single; } E[0] = n.E[0]; E[1] = n.E[1]; E[3] = n.E[2]; return *this; } void NuclearData::cleanUp() { int rxnNum; if (nPaths>=0) { for (rxnNum=0;rxnNum<nPaths;rxnNum++) { delete paths[rxnNum]; delete emitted[rxnNum]; } delete paths[rxnNum]; } delete paths; delete emitted; delete relations; paths = NULL; emitted = NULL; relations = NULL; D = NULL; E[0] = 0; E[1] = 0; E[2] = 0; nPaths = -1; } /*************************** *********** Input ********* ***************************/ void NuclearData::getDataLib(istream& input) { char type[64]; input >> type; verbose(2,"Openning DataLib with type %s",type); dataLib = DataLib::newLib(type,input); nGroups = dataLib->getNumGroups(); VolFlux::setNumGroups(nGroups); } void NuclearData::closeDataLib() { delete dataLib; } /**************************** ********** Chain *********** ***************************/ /* set the nuclear data with arguments passed from dataLib routine */ void NuclearData::setData(int numRxns, float* radE, int* daugKza, char** emissions, float** xSection, float thalf, float *totalXSection) { int gNum, rxnNum; verbose(4,"Setting NuclearData members."); cleanUp(); /* set dimensions */ nPaths = numRxns; if (nPaths < 0) return; /* only need relations and emitted if nPaths > 0 */ if (nPaths > 0) { relations = new int[nPaths]; memCheck(relations,"NuclearData::setData(...) : relations"); emitted = new char*[nPaths]; memCheck(emitted,"NuclearData::setData(...) : emitted"); } paths = new double*[nPaths+1]; memCheck(paths,"NuclearData::setData(...) : paths"); E[0] = radE[0]; E[1] = radE[1]; E[2] = radE[2]; /* initialize total x-sections */ /* total of all paths */ paths[nPaths] = new double[nGroups+1]; memCheck(paths[nPaths],"NuclearData::setData(...) : paths[n]"); for (gNum=0;gNum<nGroups;gNum++) paths[nPaths][gNum] = 0; /* if we are passed a total xsection (we must be in reverse mode) */ if (totalXSection != NULL) { delete single; single = NULL; P = NULL; single = new double[nGroups+1]; D = single; } else D = paths[nPaths]; if (thalf>0) D[nGroups] = log(2.0)/thalf; else D[nGroups] = 0; /* setup each reaction */ for (rxnNum=0;rxnNum<nPaths;rxnNum++) { debug(4,"Copying reaction %d with %d groups.",rxnNum,nGroups+1); relations[rxnNum] = daugKza[rxnNum]; emitted[rxnNum] = new char[strlen(emissions[rxnNum])+1]; memCheck(emitted[rxnNum],"NuclearData::setData(...) : emitted[n]"); strcpy(emitted[rxnNum],emissions[rxnNum]); paths[rxnNum] = new double[nGroups+1]; memCheck(paths[rxnNum],"NuclearData::setData(...) : paths[n]"); for (gNum=0;gNum<nGroups;gNum++) { paths[rxnNum][gNum] = xSection[rxnNum][gNum]*1e-24; if (strcmp(emitted[rxnNum],"x")) paths[nPaths][gNum] += paths[rxnNum][gNum]; } paths[rxnNum][nGroups] = xSection[rxnNum][nGroups]; } } /* strip pure transmutation reactions out of data */ int NuclearData::stripNonDecay() { int rxnNum = 0; int *newDaug = NULL; char **newEmitted = NULL; /* count decay reactions */ int numDecay = 0; for (rxnNum=0;rxnNum<nPaths;rxnNum++) if (paths[rxnNum][nGroups]>0) numDecay++; /* if there are fewer decay reactions than the total number, * copy them to a new array */ if (numDecay < nPaths) { /* only need relations and emitted if we have decay reactions */ if (numDecay > 0) { newDaug = new int[numDecay]; memCheck(newDaug,"NuclearData::stripNonDecay(...): newDaug"); newEmitted = new char*[numDecay]; memCheck(newEmitted,"NuclearData::stripNonDecay(...): newEmitted"); } int decayRxnNum = 0; /* always need at least one path array for the total */ double **newPaths = new double*[numDecay+1]; memCheck(newPaths,"NuclearData::stripNonDecay(...): newPaths"); /* always need to copy the decay paths (could be none) and * delete the non decay paths */ for (rxnNum=0;rxnNum<nPaths;rxnNum++) if (paths[rxnNum][nGroups]>0) { newDaug[decayRxnNum] = relations[rxnNum]; newPaths[decayRxnNum] = paths[rxnNum]; newEmitted[decayRxnNum++] = emitted[rxnNum]; } else { delete paths[rxnNum]; delete emitted[rxnNum]; } /* always must copy total decay rate */ newPaths[decayRxnNum] = paths[rxnNum]; delete relations; delete emitted; delete paths; relations = newDaug; emitted = newEmitted; paths = newPaths; nPaths = numDecay; } if (nPaths == 0) return TRUNCATE; else return TRUNCATE_STABLE; } <commit_msg>Fixed bug: forgot to copy totalXSection in reverse mode.<commit_after>/* File sections: * Service: constructors, destructors * Chain: functions directly related to the building and analysis of chains * Solution: functions directly related to the solution of a (sub)problem * Utility: advanced member access such as searching and counting * List: maintenance of lists or arrays of objects */ #include "NuclearData.h" #include "truncate.h" #include "Calc/VolFlux.h" #include "DataLib/DataLib.h" /*************************** ********* Service ********* **************************/ int NuclearData::nGroups = 0; DataLib* NuclearData::dataLib = NULL; int NuclearData::mode = MODE_FORWARD; /* basic constructor for NuclearData base class */ NuclearData::NuclearData() { nPaths=-1; relations=NULL; emitted=NULL; single=NULL; paths=NULL; P=NULL; D=NULL; for (int dHeat=0;dHeat<3;dHeat++) E[dHeat] = 0; } NuclearData::NuclearData(const NuclearData& n) { int rxnNum,gNum; /* set dimension */ nPaths = n.nPaths; /* initialize all pointers to NULL */ relations=NULL; emitted=NULL; single=NULL; paths=NULL; P=NULL; D=NULL; for (int dHeat=0;dHeat<3;dHeat++) E[dHeat] = 0; if (nPaths < 0) return; /* allocate storage */ /* if there are any paths other than total */ if (nPaths>0) { relations = new int[nPaths]; memCheck(relations,"NuclearData::NuclearData(...) copy constructor: relations"); emitted = new char*[nPaths]; memCheck(emitted,"NuclearData::NuclearData(...) copy constructor: emitted"); } paths = new double*[nPaths+1]; memCheck(paths,"NuclearData::NuclearData(...) copy constructor: paths"); /* copy data */ for (rxnNum=0;rxnNum<nPaths;rxnNum++) { relations[rxnNum] = n.relations[rxnNum]; emitted[rxnNum] = new char[strlen(n.emitted[rxnNum])+1]; memCheck(emitted[rxnNum],"NuclearData::NuclearData(...) copy constructor: emitted[n]"); strcpy(emitted[rxnNum],n.emitted[rxnNum]); paths[rxnNum] = new double[nGroups+1]; memCheck(paths[rxnNum],"NuclearData::NuclearData(...) copy constructor: paths[n]"); for (gNum=0;gNum<=nGroups;gNum++) paths[rxnNum][gNum] = n.paths[rxnNum][gNum]; /* check for pointing of D and P */ if (n.D == n.paths[rxnNum]) { D = paths[rxnNum]; P = single; } if (n.P == n.paths[rxnNum]) { P = paths[rxnNum]; D = single; } } /* allocate storage for total of paths and single xsection */ paths[nPaths] = new double[nGroups+1]; memCheck(paths[rxnNum],"NuclearData::NuclearData(...) copy constructor: paths[n]"); single = new double[nGroups+1]; memCheck(single,"NuclearData::NuclearData(...) copy constructor: single"); for (gNum=0;gNum<=nGroups;gNum++) { paths[rxnNum][gNum] = n.paths[rxnNum][gNum]; single[gNum] = n.single[gNum]; } /* check for pointing of D and P */ if (n.D == n.paths[rxnNum]) { D = paths[rxnNum]; P = single; } if (n.P == n.paths[rxnNum]) { P = paths[rxnNum]; D = single; } E[0] = n.E[0]; E[1] = n.E[1]; E[3] = n.E[2]; } /* basic destructor for NuclearData */ NuclearData::~NuclearData() { cleanUp(); delete single; single = NULL; P = NULL; } NuclearData& NuclearData::operator=(const NuclearData& n) { if (this == &n) return *this; int rxnNum,gNum; cleanUp(); delete single; single = NULL; P = NULL; nPaths = n.nPaths; if (nPaths < 0) return *this; /* only need relations and emitted if nPaths > 0 */ if (nPaths>0) { relations = new int[nPaths]; memCheck(relations,"NuclearData::NuclearData(...) copy constructor: relations"); emitted = new char*[nPaths]; memCheck(emitted,"NuclearData::NuclearData(...) copy constructor: emitted"); } /* always need paths */ paths = new double*[nPaths+1]; memCheck(paths,"NuclearData::NuclearData(...) copy constructor: paths"); /* copy data */ for (rxnNum=0;rxnNum<nPaths;rxnNum++) { relations[rxnNum] = n.relations[rxnNum]; emitted[rxnNum] = new char[strlen(n.emitted[rxnNum])+1]; memCheck(emitted[rxnNum],"NuclearData::NuclearData(...) copy constructor: emitted[n]"); strcpy(emitted[rxnNum],n.emitted[rxnNum]); paths[rxnNum] = new double[nGroups+1]; memCheck(paths[rxnNum],"NuclearData::NuclearData(...) copy constructor: paths[n]"); for (gNum=0;gNum<=nGroups;gNum++) paths[rxnNum][gNum] = n.paths[rxnNum][gNum]; if (n.D == n.paths[rxnNum]) { D = paths[rxnNum]; P = single; } if (n.P == n.paths[rxnNum]) { P = paths[rxnNum]; D = single; } } /* allocate and fill total xsections */ paths[nPaths] = new double[nGroups+1]; memCheck(paths[nPaths],"NuclearData::NuclearData(...) copy constructor: paths[n]"); single = new double[nGroups+1]; memCheck(single,"NuclearData::NuclearData(...) copy constructor: single"); for (gNum=0;gNum<=nGroups;gNum++) { paths[rxnNum][gNum] = n.paths[rxnNum][gNum]; single[gNum] = n.single[gNum]; } if (n.D == n.paths[rxnNum]) { D = paths[rxnNum]; P = single; } if (n.P == n.paths[rxnNum]) { P = paths[rxnNum]; D = single; } E[0] = n.E[0]; E[1] = n.E[1]; E[3] = n.E[2]; return *this; } void NuclearData::cleanUp() { int rxnNum; if (nPaths>=0) { for (rxnNum=0;rxnNum<nPaths;rxnNum++) { delete paths[rxnNum]; delete emitted[rxnNum]; } delete paths[rxnNum]; } delete paths; delete emitted; delete relations; paths = NULL; emitted = NULL; relations = NULL; D = NULL; E[0] = 0; E[1] = 0; E[2] = 0; nPaths = -1; } /*************************** *********** Input ********* ***************************/ void NuclearData::getDataLib(istream& input) { char type[64]; input >> type; verbose(2,"Openning DataLib with type %s",type); dataLib = DataLib::newLib(type,input); nGroups = dataLib->getNumGroups(); VolFlux::setNumGroups(nGroups); } void NuclearData::closeDataLib() { delete dataLib; } /**************************** ********** Chain *********** ***************************/ /* set the nuclear data with arguments passed from dataLib routine */ void NuclearData::setData(int numRxns, float* radE, int* daugKza, char** emissions, float** xSection, float thalf, float *totalXSection) { int gNum, rxnNum; verbose(4,"Setting NuclearData members."); cleanUp(); /* set dimensions */ nPaths = numRxns; if (nPaths < 0) return; /* only need relations and emitted if nPaths > 0 */ if (nPaths > 0) { relations = new int[nPaths]; memCheck(relations,"NuclearData::setData(...) : relations"); emitted = new char*[nPaths]; memCheck(emitted,"NuclearData::setData(...) : emitted"); } paths = new double*[nPaths+1]; memCheck(paths,"NuclearData::setData(...) : paths"); E[0] = radE[0]; E[1] = radE[1]; E[2] = radE[2]; /* initialize total x-sections */ /* total of all paths */ paths[nPaths] = new double[nGroups+1]; memCheck(paths[nPaths],"NuclearData::setData(...) : paths[n]"); for (gNum=0;gNum<nGroups;gNum++) paths[nPaths][gNum] = 0; /* if we are passed a total xsection (we must be in reverse mode) */ if (totalXSection != NULL) { delete single; single = NULL; P = NULL; single = new double[nGroups+1]; for (gNum=0;gNum<nGroups;gNum++) single[gNum] = totalXSection[gNum]*1e-24; D = single; } else D = paths[nPaths]; if (thalf>0) D[nGroups] = log(2.0)/thalf; else D[nGroups] = 0; /* setup each reaction */ for (rxnNum=0;rxnNum<nPaths;rxnNum++) { debug(4,"Copying reaction %d with %d groups.",rxnNum,nGroups+1); relations[rxnNum] = daugKza[rxnNum]; emitted[rxnNum] = new char[strlen(emissions[rxnNum])+1]; memCheck(emitted[rxnNum],"NuclearData::setData(...) : emitted[n]"); strcpy(emitted[rxnNum],emissions[rxnNum]); paths[rxnNum] = new double[nGroups+1]; memCheck(paths[rxnNum],"NuclearData::setData(...) : paths[n]"); for (gNum=0;gNum<nGroups;gNum++) { paths[rxnNum][gNum] = xSection[rxnNum][gNum]*1e-24; if (strcmp(emitted[rxnNum],"x")) paths[nPaths][gNum] += paths[rxnNum][gNum]; } paths[rxnNum][nGroups] = xSection[rxnNum][nGroups]; } } /* strip pure transmutation reactions out of data */ int NuclearData::stripNonDecay() { int rxnNum = 0; int *newDaug = NULL; char **newEmitted = NULL; /* count decay reactions */ int numDecay = 0; for (rxnNum=0;rxnNum<nPaths;rxnNum++) if (paths[rxnNum][nGroups]>0) numDecay++; /* if there are fewer decay reactions than the total number, * copy them to a new array */ if (numDecay < nPaths) { /* only need relations and emitted if we have decay reactions */ if (numDecay > 0) { newDaug = new int[numDecay]; memCheck(newDaug,"NuclearData::stripNonDecay(...): newDaug"); newEmitted = new char*[numDecay]; memCheck(newEmitted,"NuclearData::stripNonDecay(...): newEmitted"); } int decayRxnNum = 0; /* always need at least one path array for the total */ double **newPaths = new double*[numDecay+1]; memCheck(newPaths,"NuclearData::stripNonDecay(...): newPaths"); /* always need to copy the decay paths (could be none) and * delete the non decay paths */ for (rxnNum=0;rxnNum<nPaths;rxnNum++) if (paths[rxnNum][nGroups]>0) { newDaug[decayRxnNum] = relations[rxnNum]; newPaths[decayRxnNum] = paths[rxnNum]; newEmitted[decayRxnNum++] = emitted[rxnNum]; } else { delete paths[rxnNum]; delete emitted[rxnNum]; } /* always must copy total decay rate */ newPaths[decayRxnNum] = paths[rxnNum]; delete relations; delete emitted; delete paths; relations = newDaug; emitted = newEmitted; paths = newPaths; nPaths = numDecay; } if (nPaths == 0) return TRUNCATE; else return TRUNCATE_STABLE; } <|endoftext|>
<commit_before>/// // CrabLlvm -- Abstract Interpretation-based Analyzer for LLVM bitcode /// #include "llvm/LinkAllPasses.h" #include "llvm/IR/LegacyPassManager.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "llvm/IRReader/IRReader.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/Signals.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/ToolOutputFile.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Transforms/IPO.h" #include "llvm/Bitcode/BitcodeWriter.h" #include "llvm/Bitcode/BitcodeWriterPass.h" #include "llvm/IR/Verifier.h" #include "crab_llvm/config.h" #ifdef HAVE_LLVM_SEAHORN #include "llvm_seahorn/Transforms/Scalar.h" #endif #include "crab_llvm/Passes.hh" #include "crab_llvm/CrabLlvm.hh" #include "crab_llvm/Transforms/InsertInvariants.hh" #include "crab/common/debug.hpp" static llvm::cl::opt<std::string> InputFilename(llvm::cl::Positional, llvm::cl::desc("<input LLVM bitcode file>"), llvm::cl::Required, llvm::cl::value_desc("filename")); static llvm::cl::opt<std::string> OutputFilename("o", llvm::cl::desc("Override output filename"), llvm::cl::init(""), llvm::cl::value_desc("filename")); static llvm::cl::opt<bool> OutputAssembly("S", llvm::cl::desc("Write output as LLVM assembly")); static llvm::cl::opt<std::string> AsmOutputFilename("oll", llvm::cl::desc("Output analyzed bitcode"), llvm::cl::init(""), llvm::cl::value_desc("filename")); static llvm::cl::opt<std::string> DefaultDataLayout("default-data-layout", llvm::cl::desc("data layout string to use if not specified by module"), llvm::cl::init(""), llvm::cl::value_desc("layout-string")); static llvm::cl::opt<bool> NoCrab("no-crab", llvm::cl::desc("Output preprocessed bitecode but disabling Crab analysis"), llvm::cl::init(false), llvm::cl::Hidden); static llvm::cl::opt<bool> TurnUndefNondet("crab-turn-undef-nondet", llvm::cl::desc("Turn undefined behaviour into non-determinism"), llvm::cl::init(false), llvm::cl::Hidden); static llvm::cl::opt<bool> LowerUnsignedICmp("crab-lower-unsigned-icmp", llvm::cl::desc("Lower ULT and ULE instructions"), llvm::cl::init(false)); static llvm::cl::opt<bool> LowerCstExpr("crab-lower-constant-expr", llvm::cl::desc("Lower constant expressions to instructions"), llvm::cl::init(true)); static llvm::cl::opt<bool> LowerSelect("crab-lower-select", llvm::cl::desc("Lower all select instructions"), llvm::cl::init(false)); static llvm::cl::opt<bool> PromoteAssume("crab-promote-assume", llvm::cl::desc("Promote verifier.assume to llvm.assume intrinsics"), llvm::cl::init(false)); /* logging and verbosity */ struct LogOpt { void operator=(const std::string &tag) const { crab::CrabEnableLog(tag); } }; LogOpt loc; static llvm::cl::opt<LogOpt, true, llvm::cl::parser<std::string> > LogClOption("log", llvm::cl::desc("Enable specified log level"), llvm::cl::location(loc), llvm::cl::value_desc("string"), llvm::cl::ValueRequired, llvm::cl::ZeroOrMore); struct VerboseOpt { void operator=(unsigned level) const { crab::CrabEnableVerbosity(level); } }; VerboseOpt verbose; static llvm::cl::opt<VerboseOpt, true, llvm::cl::parser<unsigned> > CrabVerbose("crab-verbose", llvm::cl::desc("Enable verbose messages"), llvm::cl::location(verbose), llvm::cl::value_desc("uint")); struct WarningOpt { void operator=(bool val) const { crab::CrabEnableWarningMsg(val); } }; WarningOpt warning; static llvm::cl::opt<WarningOpt, true, llvm::cl::parser<bool> > CrabEnableWarning("crab-enable-warnings", llvm::cl::desc("Enable warning messages"), llvm::cl::location(warning), llvm::cl::value_desc("bool")); struct SanityChecksOpt { void operator=(bool val) const { crab::CrabEnableSanityChecks(val); } }; SanityChecksOpt sanity; static llvm::cl::opt<SanityChecksOpt, true, llvm::cl::parser<bool> > CrabSanityChecks("crab-sanity-checks", llvm::cl::desc("Enable sanity checks"), llvm::cl::location(sanity), llvm::cl::value_desc("bool")); using namespace crab_llvm; // removes extension from filename if there is one std::string getFileName(const std::string &str) { std::string filename = str; size_t lastdot = str.find_last_of("."); if (lastdot != std::string::npos) filename = str.substr(0, lastdot); return filename; } int main(int argc, char **argv) { llvm::llvm_shutdown_obj shutdown; // calls llvm_shutdown() on exit llvm::cl::ParseCommandLineOptions(argc, argv, "CrabLlvm-- Abstract Interpretation-based Analyzer of LLVM bitcode\n"); llvm::sys::PrintStackTraceOnErrorSignal(argv[0]); llvm::PrettyStackTraceProgram PSTP(argc, argv); llvm::EnableDebugBuffering = true; std::error_code error_code; llvm::SMDiagnostic err; static llvm::LLVMContext context; std::unique_ptr<llvm::Module> module; std::unique_ptr<llvm::tool_output_file> output; std::unique_ptr<llvm::tool_output_file> asmOutput; module = llvm::parseIRFile(InputFilename, err, context); if (!module) { if (llvm::errs().has_colors()) llvm::errs().changeColor(llvm::raw_ostream::RED); llvm::errs() << "error: " << "Bitcode was not properly read; " << err.getMessage() << "\n"; if (llvm::errs().has_colors()) llvm::errs().resetColor(); return 3; } if (!AsmOutputFilename.empty()) asmOutput = llvm::make_unique<llvm::tool_output_file>(AsmOutputFilename.c_str(), error_code, llvm::sys::fs::F_Text); if (error_code) { if (llvm::errs().has_colors()) llvm::errs().changeColor(llvm::raw_ostream::RED); llvm::errs() << "error: Could not open " << AsmOutputFilename << ": " << error_code.message() << "\n"; if (llvm::errs().has_colors()) llvm::errs().resetColor(); return 3; } if (!OutputFilename.empty()) output = llvm::make_unique<llvm::tool_output_file> (OutputFilename.c_str(), error_code, llvm::sys::fs::F_None); if (error_code) { if (llvm::errs().has_colors()) llvm::errs().changeColor(llvm::raw_ostream::RED); llvm::errs() << "error: Could not open " << OutputFilename << ": " << error_code.message() << "\n"; if (llvm::errs().has_colors()) llvm::errs().resetColor(); return 3; } /////////////////////////////// // initialise and run passes // /////////////////////////////// llvm::legacy::PassManager pass_manager; llvm::PassRegistry &Registry = *llvm::PassRegistry::getPassRegistry(); llvm::initializeAnalysis(Registry); /// call graph and other IPA passes // llvm::initializeIPA (Registry); // XXX: porting to 3.8 llvm::initializeCallGraphWrapperPassPass(Registry); // XXX: commented while porting to 5.0 //llvm::initializeCallGraphPrinterPass(Registry); llvm::initializeCallGraphViewerPass(Registry); // XXX: not sure if needed anymore llvm::initializeGlobalsAAWrapperPassPass(Registry); // add an appropriate DataLayout instance for the module const llvm::DataLayout *dl = &module->getDataLayout(); if (!dl && !DefaultDataLayout.empty()) { module->setDataLayout(DefaultDataLayout); dl = &module->getDataLayout(); } assert(dl && "Could not find Data Layout for the module"); /** * Here only passes that are strictly necessary to avoid crashes or * useless results. Passes that are only for improving precision * should be run in crabllvm-pp. **/ // kill unused internal global pass_manager.add(llvm::createGlobalDCEPass()); pass_manager.add(crab_llvm::createRemoveUnreachableBlocksPass()); // -- promote alloca's to registers pass_manager.add(llvm::createPromoteMemoryToRegisterPass()); #ifdef HAVE_LLVM_SEAHORN if (TurnUndefNondet) { // -- Turn undef into nondet pass_manager.add(llvm_seahorn::createNondetInitPass()); } #endif // -- lower invoke's pass_manager.add(llvm::createLowerInvokePass()); // cleanup after lowering invoke's pass_manager.add(llvm::createCFGSimplificationPass()); // -- ensure one single exit point per function pass_manager.add(llvm::createUnifyFunctionExitNodesPass()); // -- remove unreachable blocks pass_manager.add(crab_llvm::createRemoveUnreachableBlocksPass()); // -- remove switch constructions pass_manager.add(llvm::createLowerSwitchPass()); // cleanup after lowering switches pass_manager.add(llvm::createCFGSimplificationPass()); // -- lower constant expressions to instructions if (LowerCstExpr) { pass_manager.add(crab_llvm::createLowerCstExprPass()); } // cleanup after lowering constant expressions pass_manager.add(llvm::createDeadCodeEliminationPass()); #ifdef HAVE_LLVM_SEAHORN if (TurnUndefNondet) { pass_manager.add(llvm_seahorn::createDeadNondetElimPass()); } #endif // -- lower ULT and ULE instructions if(LowerUnsignedICmp) { pass_manager.add(crab_llvm::createLowerUnsignedICmpPass()); // cleanup unnecessary and unreachable blocks pass_manager.add(llvm::createCFGSimplificationPass()); pass_manager.add(crab_llvm::createRemoveUnreachableBlocksPass()); } // -- must be the last ones before running crab. if (LowerSelect) { pass_manager.add(crab_llvm::createLowerSelectPass()); } if (!NoCrab) { /// -- run the crab analyzer pass_manager.add(new crab_llvm::CrabLlvmPass()); } if(!AsmOutputFilename.empty()) pass_manager.add(createPrintModulePass(asmOutput->os())); if (!NoCrab) { // -- insert invariants as assume instructions pass_manager.add(new crab_llvm::InsertInvariants()); // -- simplify invariants added in the bytecode. #ifdef HAVE_LLVM_SEAHORN pass_manager.add(llvm_seahorn::createInstructionCombiningPass()); #else pass_manager.add(llvm::createInstructionCombiningPass()); #endif // -- remove verifier.assume(true) and convert // -- verifier.assume(false) into unreachable blocks pass_manager.add(crab_llvm::createSimplifyAssumePass()); if (PromoteAssume) { // -- promote verifier.assume to llvm.assume intrinsics pass_manager.add(crab_llvm::createPromoteAssumePass()); } } if (!OutputFilename.empty()) { if (OutputAssembly) pass_manager.add(createPrintModulePass(output->os())); else pass_manager.add(createBitcodeWriterPass(output->os())); } pass_manager.run(*module.get()); if (!AsmOutputFilename.empty()) asmOutput->keep(); if (!OutputFilename.empty()) output->keep(); return 0; } <commit_msg>More flags to disable lowering of switch and invoke instructions<commit_after>/// // CrabLlvm -- Abstract Interpretation-based Analyzer for LLVM bitcode /// #include "llvm/LinkAllPasses.h" #include "llvm/IR/LegacyPassManager.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "llvm/IRReader/IRReader.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/Signals.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/ToolOutputFile.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Transforms/IPO.h" #include "llvm/Bitcode/BitcodeWriter.h" #include "llvm/Bitcode/BitcodeWriterPass.h" #include "llvm/IR/Verifier.h" #include "crab_llvm/config.h" #ifdef HAVE_LLVM_SEAHORN #include "llvm_seahorn/Transforms/Scalar.h" #endif #include "crab_llvm/Passes.hh" #include "crab_llvm/CrabLlvm.hh" #include "crab_llvm/Transforms/InsertInvariants.hh" #include "crab/common/debug.hpp" static llvm::cl::opt<std::string> InputFilename(llvm::cl::Positional, llvm::cl::desc("<input LLVM bitcode file>"), llvm::cl::Required, llvm::cl::value_desc("filename")); static llvm::cl::opt<std::string> OutputFilename("o", llvm::cl::desc("Override output filename"), llvm::cl::init(""), llvm::cl::value_desc("filename")); static llvm::cl::opt<bool> OutputAssembly("S", llvm::cl::desc("Write output as LLVM assembly")); static llvm::cl::opt<std::string> AsmOutputFilename("oll", llvm::cl::desc("Output analyzed bitcode"), llvm::cl::init(""), llvm::cl::value_desc("filename")); static llvm::cl::opt<std::string> DefaultDataLayout("default-data-layout", llvm::cl::desc("data layout string to use if not specified by module"), llvm::cl::init(""), llvm::cl::value_desc("layout-string")); static llvm::cl::opt<bool> NoCrab("no-crab", llvm::cl::desc("Output preprocessed bitcode but disabling Crab analysis"), llvm::cl::init(false), llvm::cl::Hidden); static llvm::cl::opt<bool> TurnUndefNondet("crab-turn-undef-nondet", llvm::cl::desc("Turn undefined behaviour into non-determinism"), llvm::cl::init(false), llvm::cl::Hidden); static llvm::cl::opt<bool> LowerUnsignedICmp("crab-lower-unsigned-icmp", llvm::cl::desc("Lower ULT and ULE instructions"), llvm::cl::init(false)); static llvm::cl::opt<bool> LowerCstExpr("crab-lower-constant-expr", llvm::cl::desc("Lower constant expressions to instructions"), llvm::cl::init(true)); static llvm::cl::opt<bool> LowerInvoke("crab-lower-invoke", llvm::cl::desc("Lower invoke instructions"), llvm::cl::init(true)); static llvm::cl::opt<bool> LowerSwitch("crab-lower-switch", llvm::cl::desc("Lower switch instructions"), llvm::cl::init(true)); static llvm::cl::opt<bool> LowerSelect("crab-lower-select", llvm::cl::desc("Lower all select instructions"), llvm::cl::init(false)); static llvm::cl::opt<bool> PromoteAssume("crab-promote-assume", llvm::cl::desc("Promote verifier.assume to llvm.assume intrinsics"), llvm::cl::init(false)); /* logging and verbosity */ struct LogOpt { void operator=(const std::string &tag) const { crab::CrabEnableLog(tag); } }; LogOpt loc; static llvm::cl::opt<LogOpt, true, llvm::cl::parser<std::string> > LogClOption("log", llvm::cl::desc("Enable specified log level"), llvm::cl::location(loc), llvm::cl::value_desc("string"), llvm::cl::ValueRequired, llvm::cl::ZeroOrMore); struct VerboseOpt { void operator=(unsigned level) const { crab::CrabEnableVerbosity(level); } }; VerboseOpt verbose; static llvm::cl::opt<VerboseOpt, true, llvm::cl::parser<unsigned> > CrabVerbose("crab-verbose", llvm::cl::desc("Enable verbose messages"), llvm::cl::location(verbose), llvm::cl::value_desc("uint")); struct WarningOpt { void operator=(bool val) const { crab::CrabEnableWarningMsg(val); } }; WarningOpt warning; static llvm::cl::opt<WarningOpt, true, llvm::cl::parser<bool> > CrabEnableWarning("crab-enable-warnings", llvm::cl::desc("Enable warning messages"), llvm::cl::location(warning), llvm::cl::value_desc("bool")); struct SanityChecksOpt { void operator=(bool val) const { crab::CrabEnableSanityChecks(val); } }; SanityChecksOpt sanity; static llvm::cl::opt<SanityChecksOpt, true, llvm::cl::parser<bool> > CrabSanityChecks("crab-sanity-checks", llvm::cl::desc("Enable sanity checks"), llvm::cl::location(sanity), llvm::cl::value_desc("bool")); using namespace crab_llvm; // removes extension from filename if there is one std::string getFileName(const std::string &str) { std::string filename = str; size_t lastdot = str.find_last_of("."); if (lastdot != std::string::npos) filename = str.substr(0, lastdot); return filename; } int main(int argc, char **argv) { llvm::llvm_shutdown_obj shutdown; // calls llvm_shutdown() on exit llvm::cl::ParseCommandLineOptions(argc, argv, "CrabLlvm-- Abstract Interpretation-based Analyzer of LLVM bitcode\n"); llvm::sys::PrintStackTraceOnErrorSignal(argv[0]); llvm::PrettyStackTraceProgram PSTP(argc, argv); llvm::EnableDebugBuffering = true; std::error_code error_code; llvm::SMDiagnostic err; static llvm::LLVMContext context; std::unique_ptr<llvm::Module> module; std::unique_ptr<llvm::tool_output_file> output; std::unique_ptr<llvm::tool_output_file> asmOutput; module = llvm::parseIRFile(InputFilename, err, context); if (!module) { if (llvm::errs().has_colors()) llvm::errs().changeColor(llvm::raw_ostream::RED); llvm::errs() << "error: " << "Bitcode was not properly read; " << err.getMessage() << "\n"; if (llvm::errs().has_colors()) llvm::errs().resetColor(); return 3; } if (!AsmOutputFilename.empty()) asmOutput = llvm::make_unique<llvm::tool_output_file>(AsmOutputFilename.c_str(), error_code, llvm::sys::fs::F_Text); if (error_code) { if (llvm::errs().has_colors()) llvm::errs().changeColor(llvm::raw_ostream::RED); llvm::errs() << "error: Could not open " << AsmOutputFilename << ": " << error_code.message() << "\n"; if (llvm::errs().has_colors()) llvm::errs().resetColor(); return 3; } if (!OutputFilename.empty()) output = llvm::make_unique<llvm::tool_output_file> (OutputFilename.c_str(), error_code, llvm::sys::fs::F_None); if (error_code) { if (llvm::errs().has_colors()) llvm::errs().changeColor(llvm::raw_ostream::RED); llvm::errs() << "error: Could not open " << OutputFilename << ": " << error_code.message() << "\n"; if (llvm::errs().has_colors()) llvm::errs().resetColor(); return 3; } /////////////////////////////// // initialise and run passes // /////////////////////////////// llvm::legacy::PassManager pass_manager; llvm::PassRegistry &Registry = *llvm::PassRegistry::getPassRegistry(); llvm::initializeAnalysis(Registry); /// call graph and other IPA passes // llvm::initializeIPA (Registry); // XXX: porting to 3.8 llvm::initializeCallGraphWrapperPassPass(Registry); // XXX: commented while porting to 5.0 //llvm::initializeCallGraphPrinterPass(Registry); llvm::initializeCallGraphViewerPass(Registry); // XXX: not sure if needed anymore llvm::initializeGlobalsAAWrapperPassPass(Registry); // add an appropriate DataLayout instance for the module const llvm::DataLayout *dl = &module->getDataLayout(); if (!dl && !DefaultDataLayout.empty()) { module->setDataLayout(DefaultDataLayout); dl = &module->getDataLayout(); } assert(dl && "Could not find Data Layout for the module"); /** * Here only passes that are strictly necessary to avoid crashes or * useless results. Passes that are only for improving precision * should be run in crabllvm-pp. **/ // kill unused internal global pass_manager.add(llvm::createGlobalDCEPass()); pass_manager.add(crab_llvm::createRemoveUnreachableBlocksPass()); // -- promote alloca's to registers pass_manager.add(llvm::createPromoteMemoryToRegisterPass()); #ifdef HAVE_LLVM_SEAHORN if (TurnUndefNondet) { // -- Turn undef into nondet pass_manager.add(llvm_seahorn::createNondetInitPass()); } #endif if (LowerInvoke) { // -- lower invoke's pass_manager.add(llvm::createLowerInvokePass()); // cleanup after lowering invoke's pass_manager.add(llvm::createCFGSimplificationPass()); } // -- ensure one single exit point per function pass_manager.add(llvm::createUnifyFunctionExitNodesPass()); // -- remove unreachable blocks pass_manager.add(crab_llvm::createRemoveUnreachableBlocksPass()); if (LowerSwitch) { // -- remove switch constructions pass_manager.add(llvm::createLowerSwitchPass()); // cleanup after lowering switches pass_manager.add(llvm::createCFGSimplificationPass()); } // -- lower constant expressions to instructions if (LowerCstExpr) { pass_manager.add(crab_llvm::createLowerCstExprPass()); // cleanup after lowering constant expressions pass_manager.add(llvm::createDeadCodeEliminationPass()); } #ifdef HAVE_LLVM_SEAHORN if (TurnUndefNondet) { pass_manager.add(llvm_seahorn::createDeadNondetElimPass()); } #endif // -- lower ULT and ULE instructions if(LowerUnsignedICmp) { pass_manager.add(crab_llvm::createLowerUnsignedICmpPass()); // cleanup unnecessary and unreachable blocks pass_manager.add(llvm::createCFGSimplificationPass()); pass_manager.add(crab_llvm::createRemoveUnreachableBlocksPass()); } // -- must be the last ones before running crab. if (LowerSelect) { pass_manager.add(crab_llvm::createLowerSelectPass()); } if (!NoCrab) { /// -- run the crab analyzer pass_manager.add(new crab_llvm::CrabLlvmPass()); } if(!AsmOutputFilename.empty()) pass_manager.add(createPrintModulePass(asmOutput->os())); if (!NoCrab) { // -- insert invariants as assume instructions pass_manager.add(new crab_llvm::InsertInvariants()); // -- simplify invariants added in the bytecode. #ifdef HAVE_LLVM_SEAHORN pass_manager.add(llvm_seahorn::createInstructionCombiningPass()); #else pass_manager.add(llvm::createInstructionCombiningPass()); #endif // -- remove verifier.assume(true) and convert // -- verifier.assume(false) into unreachable blocks pass_manager.add(crab_llvm::createSimplifyAssumePass()); if (PromoteAssume) { // -- promote verifier.assume to llvm.assume intrinsics pass_manager.add(crab_llvm::createPromoteAssumePass()); } } if (!OutputFilename.empty()) { if (OutputAssembly) pass_manager.add(createPrintModulePass(output->os())); else pass_manager.add(createBitcodeWriterPass(output->os())); } pass_manager.run(*module.get()); if (!AsmOutputFilename.empty()) asmOutput->keep(); if (!OutputFilename.empty()) output->keep(); return 0; } <|endoftext|>
<commit_before>//===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This is the llc code generator driver. It provides a convenient // command-line interface for generating native assembly-language code // or C code, given LLVM bytecode. // //===----------------------------------------------------------------------===// #include "llvm/Bytecode/Reader.h" #include "llvm/Target/SubtargetFeature.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetMachineRegistry.h" #include "llvm/Transforms/Scalar.h" #include "llvm/Module.h" #include "llvm/PassManager.h" #include "llvm/Pass.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/PluginLoader.h" #include "llvm/Support/PassNameParser.h" #include "llvm/Analysis/Verifier.h" #include "llvm/System/Signals.h" #include "llvm/Config/config.h" #include <fstream> #include <iostream> #include <memory> using namespace llvm; // General options for llc. Other pass-specific options are specified // within the corresponding llc passes, and target-specific options // and back-end code generation options are specified with the target machine. // static cl::opt<std::string> InputFilename(cl::Positional, cl::desc("<input bytecode>"), cl::init("-")); static cl::opt<std::string> OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename")); static cl::opt<bool> Force("f", cl::desc("Overwrite output files")); static cl::opt<bool> Fast("fast", cl::desc("Generate code quickly, potentially sacrificing code quality")); static cl::opt<std::string> TargetTriple("mtriple", cl::desc("Override target triple for module")); static cl::opt<const TargetMachineRegistry::Entry*, false, TargetNameParser> MArch("march", cl::desc("Architecture to generate code for:")); static cl::opt<std::string> MCPU("mcpu", cl::desc("Target a specific cpu type (-mcpu=help for details)"), cl::value_desc("cpu-name"), cl::init("")); static cl::list<std::string> MAttrs("mattr", cl::CommaSeparated, cl::desc("Target specific attributes (-mattr=help for details)"), cl::value_desc("a1,+a2,-a3,...")); cl::opt<TargetMachine::CodeGenFileType> FileType("filetype", cl::init(TargetMachine::AssemblyFile), cl::desc("Choose a file type (not all types are supported by all targets):"), cl::values( clEnumValN(TargetMachine::AssemblyFile, "asm", " Emit an assembly ('.s') file"), clEnumValN(TargetMachine::ObjectFile, "obj", " Emit a native object ('.o') file [experimental]"), clEnumValN(TargetMachine::DynamicLibrary, "dynlib", " Emit a native dynamic library ('.so') file"), clEnumValEnd)); // The LLCPassList is populated with passes that were registered using // PassInfo::LLC by the FilteredPassNameParser: cl::list<const PassInfo*, bool, FilteredPassNameParser<PassInfo::LLC> > LLCPassList(cl::desc("Passes Available")); cl::opt<bool> NoVerify("disable-verify", cl::Hidden, cl::desc("Do not verify input module")); // GetFileNameRoot - Helper function to get the basename of a filename. static inline std::string GetFileNameRoot(const std::string &InputFilename) { std::string IFN = InputFilename; std::string outputFilename; int Len = IFN.length(); if ((Len > 2) && IFN[Len-3] == '.' && IFN[Len-2] == 'b' && IFN[Len-1] == 'c') { outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/ } else { outputFilename = IFN; } return outputFilename; } // main - Entry point for the llc compiler. // int main(int argc, char **argv) { try { cl::ParseCommandLineOptions(argc, argv, " llvm system compiler\n"); sys::PrintStackTraceOnErrorSignal(); // Load the module to be compiled... std::auto_ptr<Module> M(ParseBytecodeFile(InputFilename)); if (M.get() == 0) { std::cerr << argv[0] << ": bytecode didn't read correctly.\n"; return 1; } Module &mod = *M.get(); // If we are supposed to override the target triple, do so now. if (!TargetTriple.empty()) mod.setTargetTriple(TargetTriple); // Allocate target machine. First, check whether the user has // explicitly specified an architecture to compile for. TargetMachine* (*TargetMachineAllocator)(const Module&, IntrinsicLowering *) = 0; if (MArch == 0) { std::string Err; MArch = TargetMachineRegistry::getClosestStaticTargetForModule(mod, Err); if (MArch == 0) { std::cerr << argv[0] << ": error auto-selecting target for module '" << Err << "'. Please use the -march option to explicitly " << "pick a target.\n"; return 1; } } // Package up features to be passed to target/subtarget std::string FeaturesStr; if (MCPU.size() || MAttrs.size()) { SubtargetFeatures Features; Features.setCPU(MCPU); for (unsigned i = 0; i != MAttrs.size(); ++i) Features.AddFeature(MAttrs[i]); FeaturesStr = Features.getString(); } std::auto_ptr<TargetMachine> target(MArch->CtorFn(mod, 0, FeaturesStr)); assert(target.get() && "Could not allocate target machine!"); TargetMachine &Target = *target.get(); const TargetData &TD = Target.getTargetData(); // Build up all of the passes that we want to do to the module... PassManager Passes; Passes.add(new TargetData(TD)); // Create a new pass for each one specified on the command line for (unsigned i = 0; i < LLCPassList.size(); ++i) { const PassInfo *aPass = LLCPassList[i]; if (aPass->getNormalCtor()) { Pass *P = aPass->getNormalCtor()(); Passes.add(P); } else { std::cerr << argv[0] << ": cannot create pass: " << aPass->getPassName() << "\n"; } } #ifndef NDEBUG if(!NoVerify) Passes.add(createVerifierPass()); #endif // Figure out where we are going to send the output... std::ostream *Out = 0; if (OutputFilename != "") { if (OutputFilename != "-") { // Specified an output filename? if (!Force && std::ifstream(OutputFilename.c_str())) { // If force is not specified, make sure not to overwrite a file! std::cerr << argv[0] << ": error opening '" << OutputFilename << "': file exists!\n" << "Use -f command line argument to force output\n"; return 1; } Out = new std::ofstream(OutputFilename.c_str()); // Make sure that the Out file gets unlinked from the disk if we get a // SIGINT sys::RemoveFileOnSignal(sys::Path(OutputFilename)); } else { Out = &std::cout; } } else { if (InputFilename == "-") { OutputFilename = "-"; Out = &std::cout; } else { OutputFilename = GetFileNameRoot(InputFilename); switch (FileType) { case TargetMachine::AssemblyFile: if (MArch->Name[0] != 'c' || MArch->Name[1] != 0) // not CBE OutputFilename += ".s"; else OutputFilename += ".cbe.c"; break; case TargetMachine::ObjectFile: OutputFilename += ".o"; break; case TargetMachine::DynamicLibrary: OutputFilename += LTDL_SHLIB_EXT; break; } if (!Force && std::ifstream(OutputFilename.c_str())) { // If force is not specified, make sure not to overwrite a file! std::cerr << argv[0] << ": error opening '" << OutputFilename << "': file exists!\n" << "Use -f command line argument to force output\n"; return 1; } Out = new std::ofstream(OutputFilename.c_str()); if (!Out->good()) { std::cerr << argv[0] << ": error opening " << OutputFilename << "!\n"; delete Out; return 1; } // Make sure that the Out file gets unlinked from the disk if we get a // SIGINT sys::RemoveFileOnSignal(sys::Path(OutputFilename)); } } // Ask the target to add backend passes as necessary. if (Target.addPassesToEmitFile(Passes, *Out, FileType, Fast)) { std::cerr << argv[0] << ": target '" << Target.getName() << "' does not support generation of this file type!\n"; if (Out != &std::cout) delete Out; // And the Out file is empty and useless, so remove it now. std::remove(OutputFilename.c_str()); return 1; } else { // Run our queue of passes all at once now, efficiently. Passes.run(*M.get()); } // Delete the ostream if it's not a stdout stream if (Out != &std::cout) delete Out; return 0; } catch (const std::string& msg) { std::cerr << argv[0] << ": " << msg << "\n"; } catch (...) { std::cerr << argv[0] << ": Unexpected unknown exception occurred.\n"; } return 1; } <commit_msg>WAKEY WAKEY<commit_after>//===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This is the llc code generator driver. It provides a convenient // command-line interface for generating native assembly-language code // or C code, given LLVM bytecode. // //===----------------------------------------------------------------------===// #include "llvm/Bytecode/Reader.h" #include "llvm/Target/SubtargetFeature.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetMachineRegistry.h" #include "llvm/Transforms/Scalar.h" #include "llvm/Module.h" #include "llvm/PassManager.h" #include "llvm/Pass.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/PluginLoader.h" #include "llvm/Support/PassNameParser.h" #include "llvm/Analysis/Verifier.h" #include "llvm/System/Signals.h" #include "llvm/Config/config.h" #include <fstream> #include <iostream> #include <memory> using namespace llvm; // General options for llc. Other pass-specific options are specified // within the corresponding llc passes, and target-specific options // and back-end code generation options are specified with the target machine. // static cl::opt<std::string> InputFilename(cl::Positional, cl::desc("<input bytecode>"), cl::init("-")); static cl::opt<std::string> OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename")); static cl::opt<bool> Force("f", cl::desc("Overwrite output files")); static cl::opt<bool> Fast("fast", cl::desc("Generate code quickly, potentially sacrificing code quality")); static cl::opt<std::string> TargetTriple("mtriple", cl::desc("Override target triple for module")); static cl::opt<const TargetMachineRegistry::Entry*, false, TargetNameParser> MArch("march", cl::desc("Architecture to generate code for:")); static cl::opt<std::string> MCPU("mcpu", cl::desc("Target a specific cpu type (-mcpu=help for details)"), cl::value_desc("cpu-name"), cl::init("")); static cl::list<std::string> MAttrs("mattr", cl::CommaSeparated, cl::desc("Target specific attributes (-mattr=help for details)"), cl::value_desc("a1,+a2,-a3,...")); cl::opt<TargetMachine::CodeGenFileType> FileType("filetype", cl::init(TargetMachine::AssemblyFile), cl::desc("Choose a file type (not all types are supported by all targets):"), cl::values( clEnumValN(TargetMachine::AssemblyFile, "asm", " Emit an assembly ('.s') file"), clEnumValN(TargetMachine::ObjectFile, "obj", " Emit a native object ('.o') file [experimental]"), clEnumValN(TargetMachine::DynamicLibrary, "dynlib", " Emit a native dynamic library ('.so') file"), clEnumValEnd)); // The LLCPassList is populated with passes that were registered using // PassInfo::LLC by the FilteredPassNameParser: cl::list<const PassInfo*, bool, FilteredPassNameParser<PassInfo::LLC> > LLCPassList(cl::desc("Passes Available")); cl::opt<bool> NoVerify("disable-verify", cl::Hidden, cl::desc("Do not verify input module")); // GetFileNameRoot - Helper function to get the basename of a filename. static inline std::string GetFileNameRoot(const std::string &InputFilename) { std::string IFN = InputFilename; std::string outputFilename; int Len = IFN.length(); if ((Len > 2) && IFN[Len-3] == '.' && IFN[Len-2] == 'b' && IFN[Len-1] == 'c') { outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/ } else { outputFilename = IFN; } return outputFilename; } // main - Entry point for the llc compiler. // int main(int argc, char **argv) { try { cl::ParseCommandLineOptions(argc, argv, " llvm system compiler\n"); sys::PrintStackTraceOnErrorSignal(); // Load the module to be compiled... std::auto_ptr<Module> M(ParseBytecodeFile(InputFilename)); if (M.get() == 0) { std::cerr << argv[0] << ": bytecode didn't read correctly.\n"; return 1; } Module &mod = *M.get(); // If we are supposed to override the target triple, do so now. if (!TargetTriple.empty()) mod.setTargetTriple(TargetTriple); // Allocate target machine. First, check whether the user has // explicitly specified an architecture to compile for. TargetMachine* (*TargetMachineAllocator)(const Module&, IntrinsicLowering *) = 0; if (MArch == 0) { std::string Err; MArch = TargetMachineRegistry::getClosestStaticTargetForModule(mod, Err); if (MArch == 0) { std::cerr << argv[0] << ": error auto-selecting target for module '" << Err << "'. Please use the -march option to explicitly " << "pick a target.\n"; return 1; } } // Package up features to be passed to target/subtarget std::string FeaturesStr; if (MCPU.size() || MAttrs.size()) { SubtargetFeatures Features; Features.setCPU(MCPU); for (unsigned i = 0; i != MAttrs.size(); ++i) Features.AddFeature(MAttrs[i]); FeaturesStr = Features.getString(); } std::auto_ptr<TargetMachine> target(MArch->CtorFn(mod, 0, FeaturesStr)); assert(target.get() && "Could not allocate target machine!"); TargetMachine &Target = *target.get(); const TargetData &TD = Target.getTargetData(); // Build up all of the passes that we want to do to the module... PassManager Passes; Passes.add(new TargetData(TD)); // Create a new pass for each one specified on the command line for (unsigned i = 0; i < LLCPassList.size(); ++i) { const PassInfo *aPass = LLCPassList[i]; if (aPass->getNormalCtor()) { Pass *P = aPass->getNormalCtor()(); Passes.add(P); } else { std::cerr << argv[0] << ": cannot create pass: " << aPass->getPassName() << "\n"; } } #ifndef NDEBUG if(!NoVerify) Passes.add(createVerifierPass()); #endif // Figure out where we are going to send the output... std::ostream *Out = 0; if (OutputFilename != "") { if (OutputFilename != "-") { // Specified an output filename? if (!Force && std::ifstream(OutputFilename.c_str())) { // If force is not specified, make sure not to overwrite a file! std::cerr << argv[0] << ": error opening '" << OutputFilename << "': file exists!\n" << "Use -f command line argument to force output\n"; return 1; } Out = new std::ofstream(OutputFilename.c_str()); // Make sure that the Out file gets unlinked from the disk if we get a // SIGINT sys::RemoveFileOnSignal(sys::Path(OutputFilename)); } else { Out = &std::cout; } } else { if (InputFilename == "-") { OutputFilename = "-"; Out = &std::cout; } else { OutputFilename = GetFileNameRoot(InputFilename); switch (FileType) { case TargetMachine::AssemblyFile: if (MArch->Name[0] != 'c' || MArch->Name[1] != 0) // not CBE OutputFilename += ".s"; else OutputFilename += ".cbe.c"; break; case TargetMachine::ObjectFile: OutputFilename += ".o"; break; case TargetMachine::DynamicLibrary: OutputFilename += LTDL_SHLIB_EXT; break; } if (!Force && std::ifstream(OutputFilename.c_str())) { // If force is not specified, make sure not to overwrite a file! std::cerr << argv[0] << ": error opening '" << OutputFilename << "': file exists!\n" << "Use -f command line argument to force output\n"; return 1; } Out = new std::ofstream(OutputFilename.c_str()); if (!Out->good()) { std::cerr << argv[0] << ": error opening " << OutputFilename << "!\n"; delete Out; return 1; } // Make sure that the Out file gets unlinked from the disk if we get a // SIGINT sys::RemoveFileOnSignal(sys::Path(OutputFilename)); } } // Ask the target to add backend passes as necessary. if (Target.addPassesToEmitFile(Passes, *Out, FileType, Fast)) { std::cerr << argv[0] << ": target '" << Target.getName() << "' does not support generation of this file type!\n"; if (Out != &std::cout) delete Out; // And the Out file is empty and useless, so remove it now. remove(OutputFilename.c_str()); return 1; } else { // Run our queue of passes all at once now, efficiently. Passes.run(*M.get()); } // Delete the ostream if it's not a stdout stream if (Out != &std::cout) delete Out; return 0; } catch (const std::string& msg) { std::cerr << argv[0] << ": " << msg << "\n"; } catch (...) { std::cerr << argv[0] << ": Unexpected unknown exception occurred.\n"; } return 1; } <|endoftext|>
<commit_before>//===-lto.cpp - LLVM Link Time Optimizer ----------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the Link Time Optimization library. This library is // intended to be used by linker to optimize code at link time. // //===----------------------------------------------------------------------===// #include "llvm-c/lto.h" #include "llvm/CodeGen/CommandFlags.h" #include "llvm/IR/LLVMContext.h" #include "llvm/LTO/LTOCodeGenerator.h" #include "llvm/LTO/LTOModule.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/TargetSelect.h" // extra command-line flags needed for LTOCodeGenerator static cl::opt<bool> DisableOpt("disable-opt", cl::init(false), cl::desc("Do not run any optimization passes")); static cl::opt<bool> DisableInline("disable-inlining", cl::init(false), cl::desc("Do not run the inliner pass")); static cl::opt<bool> DisableGVNLoadPRE("disable-gvn-loadpre", cl::init(false), cl::desc("Do not run the GVN load PRE pass")); static cl::opt<bool> DisableLTOVectorization("disable-lto-vectorization", cl::init(false), cl::desc("Do not run loop or slp vectorization during LTO")); // Holds most recent error string. // *** Not thread safe *** static std::string sLastErrorString; // Holds the initialization state of the LTO module. // *** Not thread safe *** static bool initialized = false; // Holds the command-line option parsing state of the LTO module. static bool parsedOptions = false; // Initialize the configured targets if they have not been initialized. static void lto_initialize() { if (!initialized) { InitializeAllTargetInfos(); InitializeAllTargets(); InitializeAllTargetMCs(); InitializeAllAsmParsers(); InitializeAllAsmPrinters(); InitializeAllDisassemblers(); initialized = true; } } DEFINE_SIMPLE_CONVERSION_FUNCTIONS(LTOCodeGenerator, lto_code_gen_t) DEFINE_SIMPLE_CONVERSION_FUNCTIONS(LTOModule, lto_module_t) // Convert the subtarget features into a string to pass to LTOCodeGenerator. static void lto_add_attrs(lto_code_gen_t cg) { LTOCodeGenerator *CG = unwrap(cg); if (MAttrs.size()) { std::string attrs; for (unsigned i = 0; i < MAttrs.size(); ++i) { if (i > 0) attrs.append(","); attrs.append(MAttrs[i]); } CG->setAttr(attrs.c_str()); } } extern const char* lto_get_version() { return LTOCodeGenerator::getVersionString(); } const char* lto_get_error_message() { return sLastErrorString.c_str(); } bool lto_module_is_object_file(const char* path) { return LTOModule::isBitcodeFile(path); } bool lto_module_is_object_file_for_target(const char* path, const char* target_triplet_prefix) { ErrorOr<std::unique_ptr<MemoryBuffer>> Buffer = MemoryBuffer::getFile(path); if (!Buffer) return false; return LTOModule::isBitcodeForTarget(Buffer->get(), target_triplet_prefix); } bool lto_module_is_object_file_in_memory(const void* mem, size_t length) { return LTOModule::isBitcodeFile(mem, length); } bool lto_module_is_object_file_in_memory_for_target(const void* mem, size_t length, const char* target_triplet_prefix) { std::unique_ptr<MemoryBuffer> buffer(LTOModule::makeBuffer(mem, length)); if (!buffer) return false; return LTOModule::isBitcodeForTarget(buffer.get(), target_triplet_prefix); } lto_module_t lto_module_create(const char* path) { lto_initialize(); llvm::TargetOptions Options = InitTargetOptionsFromCodeGenFlags(); return wrap(LTOModule::createFromFile(path, Options, sLastErrorString)); } lto_module_t lto_module_create_from_fd(int fd, const char *path, size_t size) { lto_initialize(); llvm::TargetOptions Options = InitTargetOptionsFromCodeGenFlags(); return wrap( LTOModule::createFromOpenFile(fd, path, size, Options, sLastErrorString)); } lto_module_t lto_module_create_from_fd_at_offset(int fd, const char *path, size_t file_size, size_t map_size, off_t offset) { lto_initialize(); llvm::TargetOptions Options = InitTargetOptionsFromCodeGenFlags(); return wrap(LTOModule::createFromOpenFileSlice(fd, path, map_size, offset, Options, sLastErrorString)); } lto_module_t lto_module_create_from_memory(const void* mem, size_t length) { lto_initialize(); llvm::TargetOptions Options = InitTargetOptionsFromCodeGenFlags(); return wrap(LTOModule::createFromBuffer(mem, length, Options, sLastErrorString)); } lto_module_t lto_module_create_from_memory_with_path(const void* mem, size_t length, const char *path) { lto_initialize(); llvm::TargetOptions Options = InitTargetOptionsFromCodeGenFlags(); return wrap( LTOModule::createFromBuffer(mem, length, Options, sLastErrorString, path)); } lto_module_t lto_module_create_in_local_context(const void *mem, size_t length, const char *path) { lto_initialize(); llvm::TargetOptions Options = InitTargetOptionsFromCodeGenFlags(); return wrap(LTOModule::createInLocalContext(mem, length, Options, sLastErrorString, path)); } lto_module_t lto_module_create_in_codegen_context(const void *mem, size_t length, const char *path, lto_code_gen_t cg) { lto_initialize(); llvm::TargetOptions Options = InitTargetOptionsFromCodeGenFlags(); return wrap(LTOModule::createInContext(mem, length, Options, sLastErrorString, path, &unwrap(cg)->getContext())); } void lto_module_dispose(lto_module_t mod) { delete unwrap(mod); } const char* lto_module_get_target_triple(lto_module_t mod) { return unwrap(mod)->getTargetTriple().c_str(); } void lto_module_set_target_triple(lto_module_t mod, const char *triple) { return unwrap(mod)->setTargetTriple(triple); } unsigned int lto_module_get_num_symbols(lto_module_t mod) { return unwrap(mod)->getSymbolCount(); } const char* lto_module_get_symbol_name(lto_module_t mod, unsigned int index) { return unwrap(mod)->getSymbolName(index); } lto_symbol_attributes lto_module_get_symbol_attribute(lto_module_t mod, unsigned int index) { return unwrap(mod)->getSymbolAttributes(index); } unsigned int lto_module_get_num_deplibs(lto_module_t mod) { return unwrap(mod)->getDependentLibraryCount(); } const char* lto_module_get_deplib(lto_module_t mod, unsigned int index) { return unwrap(mod)->getDependentLibrary(index); } unsigned int lto_module_get_num_linkeropts(lto_module_t mod) { return unwrap(mod)->getLinkerOptCount(); } const char* lto_module_get_linkeropt(lto_module_t mod, unsigned int index) { return unwrap(mod)->getLinkerOpt(index); } void lto_codegen_set_diagnostic_handler(lto_code_gen_t cg, lto_diagnostic_handler_t diag_handler, void *ctxt) { unwrap(cg)->setDiagnosticHandler(diag_handler, ctxt); } static lto_code_gen_t createCodeGen(bool InLocalContext) { lto_initialize(); TargetOptions Options = InitTargetOptionsFromCodeGenFlags(); LTOCodeGenerator *CodeGen = InLocalContext ? new LTOCodeGenerator(make_unique<LLVMContext>()) : new LTOCodeGenerator(); if (CodeGen) CodeGen->setTargetOptions(Options); return wrap(CodeGen); } lto_code_gen_t lto_codegen_create(void) { return createCodeGen(/* InLocalContext */ false); } lto_code_gen_t lto_codegen_create_in_local_context(void) { return createCodeGen(/* InLocalContext */ true); } void lto_codegen_dispose(lto_code_gen_t cg) { delete unwrap(cg); } bool lto_codegen_add_module(lto_code_gen_t cg, lto_module_t mod) { return !unwrap(cg)->addModule(unwrap(mod)); } bool lto_codegen_set_debug_model(lto_code_gen_t cg, lto_debug_model debug) { unwrap(cg)->setDebugInfo(debug); return false; } bool lto_codegen_set_pic_model(lto_code_gen_t cg, lto_codegen_model model) { unwrap(cg)->setCodePICModel(model); return false; } void lto_codegen_set_cpu(lto_code_gen_t cg, const char *cpu) { return unwrap(cg)->setCpu(cpu); } void lto_codegen_set_assembler_path(lto_code_gen_t cg, const char *path) { // In here only for backwards compatibility. We use MC now. } void lto_codegen_set_assembler_args(lto_code_gen_t cg, const char **args, int nargs) { // In here only for backwards compatibility. We use MC now. } void lto_codegen_add_must_preserve_symbol(lto_code_gen_t cg, const char *symbol) { unwrap(cg)->addMustPreserveSymbol(symbol); } bool lto_codegen_write_merged_modules(lto_code_gen_t cg, const char *path) { if (!parsedOptions) { unwrap(cg)->parseCodeGenDebugOptions(); lto_add_attrs(cg); parsedOptions = true; } return !unwrap(cg)->writeMergedModules(path, sLastErrorString); } const void *lto_codegen_compile(lto_code_gen_t cg, size_t *length) { if (!parsedOptions) { unwrap(cg)->parseCodeGenDebugOptions(); lto_add_attrs(cg); parsedOptions = true; } return unwrap(cg)->compile(length, DisableOpt, DisableInline, DisableGVNLoadPRE, DisableLTOVectorization, sLastErrorString); } bool lto_codegen_compile_to_file(lto_code_gen_t cg, const char **name) { if (!parsedOptions) { unwrap(cg)->parseCodeGenDebugOptions(); lto_add_attrs(cg); parsedOptions = true; } return !unwrap(cg)->compile_to_file( name, DisableOpt, DisableInline, DisableGVNLoadPRE, DisableLTOVectorization, sLastErrorString); } void lto_codegen_debug_options(lto_code_gen_t cg, const char *opt) { unwrap(cg)->setCodeGenDebugOptions(opt); } <commit_msg>[lto] Disable dialog boxes on crash on Windows.<commit_after>//===-lto.cpp - LLVM Link Time Optimizer ----------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the Link Time Optimization library. This library is // intended to be used by linker to optimize code at link time. // //===----------------------------------------------------------------------===// #include "llvm-c/lto.h" #include "llvm/CodeGen/CommandFlags.h" #include "llvm/IR/LLVMContext.h" #include "llvm/LTO/LTOCodeGenerator.h" #include "llvm/LTO/LTOModule.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Signals.h" #include "llvm/Support/TargetSelect.h" // extra command-line flags needed for LTOCodeGenerator static cl::opt<bool> DisableOpt("disable-opt", cl::init(false), cl::desc("Do not run any optimization passes")); static cl::opt<bool> DisableInline("disable-inlining", cl::init(false), cl::desc("Do not run the inliner pass")); static cl::opt<bool> DisableGVNLoadPRE("disable-gvn-loadpre", cl::init(false), cl::desc("Do not run the GVN load PRE pass")); static cl::opt<bool> DisableLTOVectorization("disable-lto-vectorization", cl::init(false), cl::desc("Do not run loop or slp vectorization during LTO")); // Holds most recent error string. // *** Not thread safe *** static std::string sLastErrorString; // Holds the initialization state of the LTO module. // *** Not thread safe *** static bool initialized = false; // Holds the command-line option parsing state of the LTO module. static bool parsedOptions = false; // Initialize the configured targets if they have not been initialized. static void lto_initialize() { if (!initialized) { #ifdef LLVM_ON_WIN32 // Dialog box on crash disabling doesn't work across DLL boundaries, so do // it here. llvm::sys::DisableSystemDialogsOnCrash(); #endif InitializeAllTargetInfos(); InitializeAllTargets(); InitializeAllTargetMCs(); InitializeAllAsmParsers(); InitializeAllAsmPrinters(); InitializeAllDisassemblers(); initialized = true; } } DEFINE_SIMPLE_CONVERSION_FUNCTIONS(LTOCodeGenerator, lto_code_gen_t) DEFINE_SIMPLE_CONVERSION_FUNCTIONS(LTOModule, lto_module_t) // Convert the subtarget features into a string to pass to LTOCodeGenerator. static void lto_add_attrs(lto_code_gen_t cg) { LTOCodeGenerator *CG = unwrap(cg); if (MAttrs.size()) { std::string attrs; for (unsigned i = 0; i < MAttrs.size(); ++i) { if (i > 0) attrs.append(","); attrs.append(MAttrs[i]); } CG->setAttr(attrs.c_str()); } } extern const char* lto_get_version() { return LTOCodeGenerator::getVersionString(); } const char* lto_get_error_message() { return sLastErrorString.c_str(); } bool lto_module_is_object_file(const char* path) { return LTOModule::isBitcodeFile(path); } bool lto_module_is_object_file_for_target(const char* path, const char* target_triplet_prefix) { ErrorOr<std::unique_ptr<MemoryBuffer>> Buffer = MemoryBuffer::getFile(path); if (!Buffer) return false; return LTOModule::isBitcodeForTarget(Buffer->get(), target_triplet_prefix); } bool lto_module_is_object_file_in_memory(const void* mem, size_t length) { return LTOModule::isBitcodeFile(mem, length); } bool lto_module_is_object_file_in_memory_for_target(const void* mem, size_t length, const char* target_triplet_prefix) { std::unique_ptr<MemoryBuffer> buffer(LTOModule::makeBuffer(mem, length)); if (!buffer) return false; return LTOModule::isBitcodeForTarget(buffer.get(), target_triplet_prefix); } lto_module_t lto_module_create(const char* path) { lto_initialize(); llvm::TargetOptions Options = InitTargetOptionsFromCodeGenFlags(); return wrap(LTOModule::createFromFile(path, Options, sLastErrorString)); } lto_module_t lto_module_create_from_fd(int fd, const char *path, size_t size) { lto_initialize(); llvm::TargetOptions Options = InitTargetOptionsFromCodeGenFlags(); return wrap( LTOModule::createFromOpenFile(fd, path, size, Options, sLastErrorString)); } lto_module_t lto_module_create_from_fd_at_offset(int fd, const char *path, size_t file_size, size_t map_size, off_t offset) { lto_initialize(); llvm::TargetOptions Options = InitTargetOptionsFromCodeGenFlags(); return wrap(LTOModule::createFromOpenFileSlice(fd, path, map_size, offset, Options, sLastErrorString)); } lto_module_t lto_module_create_from_memory(const void* mem, size_t length) { lto_initialize(); llvm::TargetOptions Options = InitTargetOptionsFromCodeGenFlags(); return wrap(LTOModule::createFromBuffer(mem, length, Options, sLastErrorString)); } lto_module_t lto_module_create_from_memory_with_path(const void* mem, size_t length, const char *path) { lto_initialize(); llvm::TargetOptions Options = InitTargetOptionsFromCodeGenFlags(); return wrap( LTOModule::createFromBuffer(mem, length, Options, sLastErrorString, path)); } lto_module_t lto_module_create_in_local_context(const void *mem, size_t length, const char *path) { lto_initialize(); llvm::TargetOptions Options = InitTargetOptionsFromCodeGenFlags(); return wrap(LTOModule::createInLocalContext(mem, length, Options, sLastErrorString, path)); } lto_module_t lto_module_create_in_codegen_context(const void *mem, size_t length, const char *path, lto_code_gen_t cg) { lto_initialize(); llvm::TargetOptions Options = InitTargetOptionsFromCodeGenFlags(); return wrap(LTOModule::createInContext(mem, length, Options, sLastErrorString, path, &unwrap(cg)->getContext())); } void lto_module_dispose(lto_module_t mod) { delete unwrap(mod); } const char* lto_module_get_target_triple(lto_module_t mod) { return unwrap(mod)->getTargetTriple().c_str(); } void lto_module_set_target_triple(lto_module_t mod, const char *triple) { return unwrap(mod)->setTargetTriple(triple); } unsigned int lto_module_get_num_symbols(lto_module_t mod) { return unwrap(mod)->getSymbolCount(); } const char* lto_module_get_symbol_name(lto_module_t mod, unsigned int index) { return unwrap(mod)->getSymbolName(index); } lto_symbol_attributes lto_module_get_symbol_attribute(lto_module_t mod, unsigned int index) { return unwrap(mod)->getSymbolAttributes(index); } unsigned int lto_module_get_num_deplibs(lto_module_t mod) { return unwrap(mod)->getDependentLibraryCount(); } const char* lto_module_get_deplib(lto_module_t mod, unsigned int index) { return unwrap(mod)->getDependentLibrary(index); } unsigned int lto_module_get_num_linkeropts(lto_module_t mod) { return unwrap(mod)->getLinkerOptCount(); } const char* lto_module_get_linkeropt(lto_module_t mod, unsigned int index) { return unwrap(mod)->getLinkerOpt(index); } void lto_codegen_set_diagnostic_handler(lto_code_gen_t cg, lto_diagnostic_handler_t diag_handler, void *ctxt) { unwrap(cg)->setDiagnosticHandler(diag_handler, ctxt); } static lto_code_gen_t createCodeGen(bool InLocalContext) { lto_initialize(); TargetOptions Options = InitTargetOptionsFromCodeGenFlags(); LTOCodeGenerator *CodeGen = InLocalContext ? new LTOCodeGenerator(make_unique<LLVMContext>()) : new LTOCodeGenerator(); if (CodeGen) CodeGen->setTargetOptions(Options); return wrap(CodeGen); } lto_code_gen_t lto_codegen_create(void) { return createCodeGen(/* InLocalContext */ false); } lto_code_gen_t lto_codegen_create_in_local_context(void) { return createCodeGen(/* InLocalContext */ true); } void lto_codegen_dispose(lto_code_gen_t cg) { delete unwrap(cg); } bool lto_codegen_add_module(lto_code_gen_t cg, lto_module_t mod) { return !unwrap(cg)->addModule(unwrap(mod)); } bool lto_codegen_set_debug_model(lto_code_gen_t cg, lto_debug_model debug) { unwrap(cg)->setDebugInfo(debug); return false; } bool lto_codegen_set_pic_model(lto_code_gen_t cg, lto_codegen_model model) { unwrap(cg)->setCodePICModel(model); return false; } void lto_codegen_set_cpu(lto_code_gen_t cg, const char *cpu) { return unwrap(cg)->setCpu(cpu); } void lto_codegen_set_assembler_path(lto_code_gen_t cg, const char *path) { // In here only for backwards compatibility. We use MC now. } void lto_codegen_set_assembler_args(lto_code_gen_t cg, const char **args, int nargs) { // In here only for backwards compatibility. We use MC now. } void lto_codegen_add_must_preserve_symbol(lto_code_gen_t cg, const char *symbol) { unwrap(cg)->addMustPreserveSymbol(symbol); } bool lto_codegen_write_merged_modules(lto_code_gen_t cg, const char *path) { if (!parsedOptions) { unwrap(cg)->parseCodeGenDebugOptions(); lto_add_attrs(cg); parsedOptions = true; } return !unwrap(cg)->writeMergedModules(path, sLastErrorString); } const void *lto_codegen_compile(lto_code_gen_t cg, size_t *length) { if (!parsedOptions) { unwrap(cg)->parseCodeGenDebugOptions(); lto_add_attrs(cg); parsedOptions = true; } return unwrap(cg)->compile(length, DisableOpt, DisableInline, DisableGVNLoadPRE, DisableLTOVectorization, sLastErrorString); } bool lto_codegen_compile_to_file(lto_code_gen_t cg, const char **name) { if (!parsedOptions) { unwrap(cg)->parseCodeGenDebugOptions(); lto_add_attrs(cg); parsedOptions = true; } return !unwrap(cg)->compile_to_file( name, DisableOpt, DisableInline, DisableGVNLoadPRE, DisableLTOVectorization, sLastErrorString); } void lto_codegen_debug_options(lto_code_gen_t cg, const char *opt) { unwrap(cg)->setCodeGenDebugOptions(opt); } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "pastebindotcomprotocol.h" #include <coreplugin/icore.h> #include <utils/qtcassert.h> #include <QDebug> #include <QStringList> #include <QTextStream> #include <QXmlStreamReader> #include <QXmlStreamAttributes> #include <QByteArray> #include <QNetworkReply> enum { debug = 0 }; static const char PASTEBIN_BASE[]="http://pastebin.com/"; static const char PASTEBIN_API[]="api/api_post.php"; static const char PASTEBIN_RAW[]="raw.php"; static const char PASTEBIN_ARCHIVE[]="archive"; static const char API_KEY[]="api_dev_key=516686fc461fb7f9341fd7cf2af6f829&"; // user: qtcreator_apikey namespace CodePaster { PasteBinDotComProtocol::PasteBinDotComProtocol(const NetworkAccessManagerProxyPtr &nw) : NetworkProtocol(nw), m_fetchReply(0), m_pasteReply(0), m_listReply(0), m_fetchId(-1), m_postId(-1), m_hostChecked(false) { } QString PasteBinDotComProtocol::protocolName() { return QLatin1String("Pastebin.Com"); } unsigned PasteBinDotComProtocol::capabilities() const { return ListCapability; } static inline QByteArray format(Protocol::ContentType ct) { QByteArray format = "api_paste_format="; switch (ct) { case Protocol::C: format += 'c'; break; case Protocol::Cpp: format += "cpp-qt"; case Protocol::JavaScript: format += "javascript"; break; case Protocol::Diff: format += "diff"; break; case Protocol::Xml: format += "xml"; break; case Protocol::Text: // fallthrough! default: format += "text"; } format += '&'; return format; } void PasteBinDotComProtocol::paste(const QString &text, ContentType ct, const QString &username, const QString &comment, const QString &description) { Q_UNUSED(comment); Q_UNUSED(description); QTC_ASSERT(!m_pasteReply, return); // Format body QByteArray pasteData = API_KEY; pasteData += "api_option=paste&"; pasteData += "api_paste_expire_date=1M&"; pasteData += format(ct); pasteData += "api_paste_name="; pasteData += QUrl::toPercentEncoding(username); pasteData += "&api_paste_code="; pasteData += QUrl::toPercentEncoding(fixNewLines(text)); // fire request m_pasteReply = httpPost(QLatin1String(PASTEBIN_BASE) + QLatin1String(PASTEBIN_API), pasteData); connect(m_pasteReply, SIGNAL(finished()), this, SLOT(pasteFinished())); if (debug) qDebug() << "paste: sending " << m_pasteReply << pasteData; } void PasteBinDotComProtocol::pasteFinished() { if (m_pasteReply->error()) { qWarning("Pastebin.com protocol error: %s", qPrintable(m_pasteReply->errorString())); } else { emit pasteDone(QString::fromAscii(m_pasteReply->readAll())); } m_pasteReply->deleteLater(); m_pasteReply = 0; } void PasteBinDotComProtocol::fetch(const QString &id) { // Did we get a complete URL or just an id. Insert a call to the php-script QString link = QLatin1String(PASTEBIN_BASE) + QLatin1String(PASTEBIN_RAW); link.append(QLatin1String("?i=")); if (id.startsWith(QLatin1String("http://"))) link.append(id.mid(id.lastIndexOf(QLatin1Char('/')) + 1)); else link.append(id); if (debug) qDebug() << "fetch: sending " << link; m_fetchReply = httpGet(link); connect(m_fetchReply, SIGNAL(finished()), this, SLOT(fetchFinished())); m_fetchId = id; } void PasteBinDotComProtocol::fetchFinished() { QString title; QString content; const bool error = m_fetchReply->error(); if (error) { content = m_fetchReply->errorString(); if (debug) qDebug() << "fetchFinished: error" << m_fetchId << content; } else { title = QString::fromLatin1("Pastebin.com: %1").arg(m_fetchId); content = QString::fromAscii(m_fetchReply->readAll()); // Cut out from '<pre>' formatting const int preEnd = content.lastIndexOf(QLatin1String("</pre>")); if (preEnd != -1) content.truncate(preEnd); const int preStart = content.indexOf(QLatin1String("<pre>")); if (preStart != -1) content.remove(0, preStart + 5); // Make applicable as patch. content = Protocol::textFromHtml(content); content += QLatin1Char('\n'); // ------------- if (debug) { QDebug nsp = qDebug().nospace(); nsp << "fetchFinished: " << content.size() << " Bytes"; if (debug > 1) nsp << content; } } m_fetchReply->deleteLater(); m_fetchReply = 0; emit fetchDone(title, content, error); } void PasteBinDotComProtocol::list() { QTC_ASSERT(!m_listReply, return); const QString url = QLatin1String(PASTEBIN_BASE) + QLatin1String(PASTEBIN_ARCHIVE); m_listReply = httpGet(url); connect(m_listReply, SIGNAL(finished()), this, SLOT(listFinished())); if (debug) qDebug() << "list: sending " << url << m_listReply; } static inline void padString(QString *s, int len) { const int missing = len - s->length(); if (missing > 0) s->append(QString(missing, QLatin1Char(' '))); } /* Quick & dirty: Parse out the 'archive' table as of 16.3.2011: \code <table class="maintable" cellspacing="0"> <tr class="top"> <th scope="col" align="left">Name / Title</th> <th scope="col" align="left">Posted</th> <th scope="col" align="right">Syntax</th> </tr> <tr> <td><img src="/i/t.gif" class="i_p0" alt="" border="0" /><a href="/cvWciF4S">Vector 1</a></td> <td>2 sec ago</td> <td align="right"><a href="/archive/cpp">C++</a></td> </tr> ... -\endcode */ enum ParseState { OutSideTable, WithinTable, WithinTableRow, WithinTableHeaderElement, WithinTableElement, WithinTableElementAnchor, ParseError }; QDebug operator<<(QDebug d, const QXmlStreamAttributes &al) { QDebug nospace = d.nospace(); foreach (const QXmlStreamAttribute &a, al) nospace << a.name().toString() << '=' << a.value().toString() << ' '; return d; } static inline ParseState nextOpeningState(ParseState current, const QXmlStreamReader &reader) { const QStringRef &element = reader.name(); switch (current) { case OutSideTable: // Trigger on main table only. if (element == QLatin1String("table") && reader.attributes().value(QLatin1String("class")) == QLatin1String("maintable")) return WithinTable; return OutSideTable; case WithinTable: if (element == QLatin1String("tr")) return WithinTableRow; break; case WithinTableRow: if (element == QLatin1String("td")) return WithinTableElement; if (element == QLatin1String("th")) return WithinTableHeaderElement; break; case WithinTableElement: if (element == QLatin1String("img")) return WithinTableElement; if (element == QLatin1String("a")) return WithinTableElementAnchor; break; case WithinTableHeaderElement: case WithinTableElementAnchor: case ParseError: break; } return ParseError; } static inline ParseState nextClosingState(ParseState current, const QStringRef &element) { switch (current) { case OutSideTable: return OutSideTable; case WithinTable: if (element == QLatin1String("table")) return OutSideTable; break; case WithinTableRow: if (element == QLatin1String("tr")) return WithinTable; break; case WithinTableElement: if (element == QLatin1String("td")) return WithinTableRow; if (element == QLatin1String("img")) return WithinTableElement; break; case WithinTableHeaderElement: if (element == QLatin1String("th")) return WithinTableRow; break; case WithinTableElementAnchor: if (element == QLatin1String("a")) return WithinTableElement; break; case ParseError: break; } return ParseError; } static inline QStringList parseLists(QIODevice *io) { enum { maxEntries = 200 }; // Limit the archive, which can grow quite large. QStringList rc; QXmlStreamReader reader(io); ParseState state = OutSideTable; int tableRow = 0; int tableColumn = 0; const QString hrefAttribute = QLatin1String("href"); QString link; QString title; QString age; while (!reader.atEnd()) { switch(reader.readNext()) { case QXmlStreamReader::StartElement: state = nextOpeningState(state, reader); switch (state) { case WithinTableRow: tableColumn = 0; break; case OutSideTable: case WithinTable: case WithinTableHeaderElement: case WithinTableElement: break; case WithinTableElementAnchor: // 'href="/svb5K8wS"' if (tableColumn == 0) { link = reader.attributes().value(hrefAttribute).toString(); if (link.startsWith(QLatin1Char('/'))) link.remove(0, 1); } break; case ParseError: return rc; } // switch startelement state break; case QXmlStreamReader::EndElement: state = nextClosingState(state, reader.name()); switch (state) { case OutSideTable: if (tableRow) // Seen the table, bye. return rc; break; case WithinTable: // User can occasionally be empty. if (tableRow && !link.isEmpty() && !title.isEmpty() && !age.isEmpty()) { QString entry = link; entry += QLatin1Char(' '); entry += title; entry += QLatin1String(" ("); entry += age; entry += QLatin1Char(')'); rc.push_back(entry); if (rc.size() >= maxEntries) return rc; } tableRow++; age.clear(); link.clear(); title.clear(); break; case WithinTableRow: tableColumn++; break; case WithinTableHeaderElement: case WithinTableElement: case WithinTableElementAnchor: break; case ParseError: return rc; } // switch endelement state break; case QXmlStreamReader::Characters: switch (state) { case WithinTableElement: if (tableColumn == 1) age = reader.text().toString(); break; case WithinTableElementAnchor: if (tableColumn == 0) title = reader.text().toString(); break; default: break; } // switch characters read state break; default: break; } // switch reader state } return rc; } void PasteBinDotComProtocol::listFinished() { const bool error = m_listReply->error(); if (error) { if (debug) qDebug() << "listFinished: error" << m_listReply->errorString(); } else { QStringList list = parseLists(m_listReply); emit listDone(name(), list); if (debug) qDebug() << list; } m_listReply->deleteLater(); m_listReply = 0; } } // namespace CodePaster <commit_msg>Add missing break; So pastebin works otherwise there is an error on api.<commit_after>/**************************************************************************** ** ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "pastebindotcomprotocol.h" #include <coreplugin/icore.h> #include <utils/qtcassert.h> #include <QDebug> #include <QStringList> #include <QTextStream> #include <QXmlStreamReader> #include <QXmlStreamAttributes> #include <QByteArray> #include <QNetworkReply> enum { debug = 0 }; static const char PASTEBIN_BASE[]="http://pastebin.com/"; static const char PASTEBIN_API[]="api/api_post.php"; static const char PASTEBIN_RAW[]="raw.php"; static const char PASTEBIN_ARCHIVE[]="archive"; static const char API_KEY[]="api_dev_key=516686fc461fb7f9341fd7cf2af6f829&"; // user: qtcreator_apikey namespace CodePaster { PasteBinDotComProtocol::PasteBinDotComProtocol(const NetworkAccessManagerProxyPtr &nw) : NetworkProtocol(nw), m_fetchReply(0), m_pasteReply(0), m_listReply(0), m_fetchId(-1), m_postId(-1), m_hostChecked(false) { } QString PasteBinDotComProtocol::protocolName() { return QLatin1String("Pastebin.Com"); } unsigned PasteBinDotComProtocol::capabilities() const { return ListCapability; } static inline QByteArray format(Protocol::ContentType ct) { QByteArray format = "api_paste_format="; switch (ct) { case Protocol::C: format += 'c'; break; case Protocol::Cpp: format += "cpp-qt"; break; case Protocol::JavaScript: format += "javascript"; break; case Protocol::Diff: format += "diff"; break; case Protocol::Xml: format += "xml"; break; case Protocol::Text: // fallthrough! default: format += "text"; } format += '&'; return format; } void PasteBinDotComProtocol::paste(const QString &text, ContentType ct, const QString &username, const QString &comment, const QString &description) { Q_UNUSED(comment); Q_UNUSED(description); QTC_ASSERT(!m_pasteReply, return); // Format body QByteArray pasteData = API_KEY; pasteData += "api_option=paste&"; pasteData += "api_paste_expire_date=1M&"; pasteData += format(ct); pasteData += "api_paste_name="; pasteData += QUrl::toPercentEncoding(username); pasteData += "&api_paste_code="; pasteData += QUrl::toPercentEncoding(fixNewLines(text)); // fire request m_pasteReply = httpPost(QLatin1String(PASTEBIN_BASE) + QLatin1String(PASTEBIN_API), pasteData); connect(m_pasteReply, SIGNAL(finished()), this, SLOT(pasteFinished())); if (debug) qDebug() << "paste: sending " << m_pasteReply << pasteData; } void PasteBinDotComProtocol::pasteFinished() { if (m_pasteReply->error()) { qWarning("Pastebin.com protocol error: %s", qPrintable(m_pasteReply->errorString())); } else { emit pasteDone(QString::fromAscii(m_pasteReply->readAll())); } m_pasteReply->deleteLater(); m_pasteReply = 0; } void PasteBinDotComProtocol::fetch(const QString &id) { // Did we get a complete URL or just an id. Insert a call to the php-script QString link = QLatin1String(PASTEBIN_BASE) + QLatin1String(PASTEBIN_RAW); link.append(QLatin1String("?i=")); if (id.startsWith(QLatin1String("http://"))) link.append(id.mid(id.lastIndexOf(QLatin1Char('/')) + 1)); else link.append(id); if (debug) qDebug() << "fetch: sending " << link; m_fetchReply = httpGet(link); connect(m_fetchReply, SIGNAL(finished()), this, SLOT(fetchFinished())); m_fetchId = id; } void PasteBinDotComProtocol::fetchFinished() { QString title; QString content; const bool error = m_fetchReply->error(); if (error) { content = m_fetchReply->errorString(); if (debug) qDebug() << "fetchFinished: error" << m_fetchId << content; } else { title = QString::fromLatin1("Pastebin.com: %1").arg(m_fetchId); content = QString::fromAscii(m_fetchReply->readAll()); // Cut out from '<pre>' formatting const int preEnd = content.lastIndexOf(QLatin1String("</pre>")); if (preEnd != -1) content.truncate(preEnd); const int preStart = content.indexOf(QLatin1String("<pre>")); if (preStart != -1) content.remove(0, preStart + 5); // Make applicable as patch. content = Protocol::textFromHtml(content); content += QLatin1Char('\n'); // ------------- if (debug) { QDebug nsp = qDebug().nospace(); nsp << "fetchFinished: " << content.size() << " Bytes"; if (debug > 1) nsp << content; } } m_fetchReply->deleteLater(); m_fetchReply = 0; emit fetchDone(title, content, error); } void PasteBinDotComProtocol::list() { QTC_ASSERT(!m_listReply, return); const QString url = QLatin1String(PASTEBIN_BASE) + QLatin1String(PASTEBIN_ARCHIVE); m_listReply = httpGet(url); connect(m_listReply, SIGNAL(finished()), this, SLOT(listFinished())); if (debug) qDebug() << "list: sending " << url << m_listReply; } static inline void padString(QString *s, int len) { const int missing = len - s->length(); if (missing > 0) s->append(QString(missing, QLatin1Char(' '))); } /* Quick & dirty: Parse out the 'archive' table as of 16.3.2011: \code <table class="maintable" cellspacing="0"> <tr class="top"> <th scope="col" align="left">Name / Title</th> <th scope="col" align="left">Posted</th> <th scope="col" align="right">Syntax</th> </tr> <tr> <td><img src="/i/t.gif" class="i_p0" alt="" border="0" /><a href="/cvWciF4S">Vector 1</a></td> <td>2 sec ago</td> <td align="right"><a href="/archive/cpp">C++</a></td> </tr> ... -\endcode */ enum ParseState { OutSideTable, WithinTable, WithinTableRow, WithinTableHeaderElement, WithinTableElement, WithinTableElementAnchor, ParseError }; QDebug operator<<(QDebug d, const QXmlStreamAttributes &al) { QDebug nospace = d.nospace(); foreach (const QXmlStreamAttribute &a, al) nospace << a.name().toString() << '=' << a.value().toString() << ' '; return d; } static inline ParseState nextOpeningState(ParseState current, const QXmlStreamReader &reader) { const QStringRef &element = reader.name(); switch (current) { case OutSideTable: // Trigger on main table only. if (element == QLatin1String("table") && reader.attributes().value(QLatin1String("class")) == QLatin1String("maintable")) return WithinTable; return OutSideTable; case WithinTable: if (element == QLatin1String("tr")) return WithinTableRow; break; case WithinTableRow: if (element == QLatin1String("td")) return WithinTableElement; if (element == QLatin1String("th")) return WithinTableHeaderElement; break; case WithinTableElement: if (element == QLatin1String("img")) return WithinTableElement; if (element == QLatin1String("a")) return WithinTableElementAnchor; break; case WithinTableHeaderElement: case WithinTableElementAnchor: case ParseError: break; } return ParseError; } static inline ParseState nextClosingState(ParseState current, const QStringRef &element) { switch (current) { case OutSideTable: return OutSideTable; case WithinTable: if (element == QLatin1String("table")) return OutSideTable; break; case WithinTableRow: if (element == QLatin1String("tr")) return WithinTable; break; case WithinTableElement: if (element == QLatin1String("td")) return WithinTableRow; if (element == QLatin1String("img")) return WithinTableElement; break; case WithinTableHeaderElement: if (element == QLatin1String("th")) return WithinTableRow; break; case WithinTableElementAnchor: if (element == QLatin1String("a")) return WithinTableElement; break; case ParseError: break; } return ParseError; } static inline QStringList parseLists(QIODevice *io) { enum { maxEntries = 200 }; // Limit the archive, which can grow quite large. QStringList rc; QXmlStreamReader reader(io); ParseState state = OutSideTable; int tableRow = 0; int tableColumn = 0; const QString hrefAttribute = QLatin1String("href"); QString link; QString title; QString age; while (!reader.atEnd()) { switch(reader.readNext()) { case QXmlStreamReader::StartElement: state = nextOpeningState(state, reader); switch (state) { case WithinTableRow: tableColumn = 0; break; case OutSideTable: case WithinTable: case WithinTableHeaderElement: case WithinTableElement: break; case WithinTableElementAnchor: // 'href="/svb5K8wS"' if (tableColumn == 0) { link = reader.attributes().value(hrefAttribute).toString(); if (link.startsWith(QLatin1Char('/'))) link.remove(0, 1); } break; case ParseError: return rc; } // switch startelement state break; case QXmlStreamReader::EndElement: state = nextClosingState(state, reader.name()); switch (state) { case OutSideTable: if (tableRow) // Seen the table, bye. return rc; break; case WithinTable: // User can occasionally be empty. if (tableRow && !link.isEmpty() && !title.isEmpty() && !age.isEmpty()) { QString entry = link; entry += QLatin1Char(' '); entry += title; entry += QLatin1String(" ("); entry += age; entry += QLatin1Char(')'); rc.push_back(entry); if (rc.size() >= maxEntries) return rc; } tableRow++; age.clear(); link.clear(); title.clear(); break; case WithinTableRow: tableColumn++; break; case WithinTableHeaderElement: case WithinTableElement: case WithinTableElementAnchor: break; case ParseError: return rc; } // switch endelement state break; case QXmlStreamReader::Characters: switch (state) { case WithinTableElement: if (tableColumn == 1) age = reader.text().toString(); break; case WithinTableElementAnchor: if (tableColumn == 0) title = reader.text().toString(); break; default: break; } // switch characters read state break; default: break; } // switch reader state } return rc; } void PasteBinDotComProtocol::listFinished() { const bool error = m_listReply->error(); if (error) { if (debug) qDebug() << "listFinished: error" << m_listReply->errorString(); } else { QStringList list = parseLists(m_listReply); emit listDone(name(), list); if (debug) qDebug() << list; } m_listReply->deleteLater(); m_listReply = 0; } } // namespace CodePaster <|endoftext|>
<commit_before>#include <algorithm> #include <fstream> #include <iostream> #include <iterator> #include <string> #include <vector> #include <absl/strings/str_split.h> #include <gflags/gflags.h> #include <prjxray/memory_mapped_file.h> #include <prjxray/xilinx/xc7series/bitstream_reader.h> #include <prjxray/xilinx/xc7series/bitstream_writer.h> #include <prjxray/xilinx/xc7series/configuration.h> #include <prjxray/xilinx/xc7series/part.h> DEFINE_string(part_file, "", "Definition file for target 7-series part"); DEFINE_string(bitstream_file, "", "Initial bitstream to which the deltas are applied."); DEFINE_string( frm_file, "", "File containing a list of frame deltas to be applied to the base " "bitstream. Each line in the file is of the form: " "<frame_address> <word1>,...,<word101>."); DEFINE_string(output_file, "", "Write patched bitsteam to file"); namespace xc7series = prjxray::xilinx::xc7series; int main(int argc, char* argv[]) { gflags::SetUsageMessage(argv[0]); gflags::ParseCommandLineFlags(&argc, &argv, true); auto part = xc7series::Part::FromFile(FLAGS_part_file); if (!part) { std::cerr << "Part file not found or invalid" << std::endl; return 1; } auto bitstream_file = prjxray::MemoryMappedFile::InitWithFile(FLAGS_bitstream_file); if (!bitstream_file) { std::cerr << "Can't open base bitstream file: " << FLAGS_bitstream_file << std::endl; return 1; } auto bitstream_reader = xc7series::BitstreamReader::InitWithBytes( bitstream_file->as_bytes()); if (!bitstream_reader) { std::cout << "Bitstream does not appear to be a 7-series bitstream!" << std::endl; return 1; } auto bitstream_config = xc7series::Configuration::InitWithPackets(*part, *bitstream_reader); if (!bitstream_config) { std::cerr << "Bitstream does not appear to be for this part" << std::endl; return 1; } // Copy the base frames to a mutable collection std::map<xc7series::FrameAddress, std::vector<uint32_t>> frames; for (auto& frame_val : bitstream_config->frames()) { auto& cur_frame = frames[frame_val.first]; std::copy(frame_val.second.begin(), frame_val.second.end(), std::back_inserter(cur_frame)); } // Apply the deltas. std::ifstream frm_file(FLAGS_frm_file); if (!frm_file) { std::cerr << "Unable to open frm file: " << FLAGS_frm_file << std::endl; return 1; } std::string frm_line; while (std::getline(frm_file, frm_line)) { if (frm_line[0] == '#') continue; std::pair<std::string, std::string> frame_delta = absl::StrSplit(frm_line, ' '); uint32_t frame_address = std::stoul(frame_delta.first, nullptr, 16); auto& frame_data = frames[frame_address]; frame_data.resize(101); std::vector<std::string> frame_data_strings = absl::StrSplit(frame_delta.second, ','); if (frame_data_strings.size() != 101) { std::cerr << "Frame " << std::hex << frame_address << ": found " << std::dec << frame_data_strings.size() << "words instead of 101"; continue; }; std::transform(frame_data_strings.begin(), frame_data_strings.end(), frame_data.begin(), [](const std::string& val) -> uint32_t { return std::stoul(val, nullptr, 16); }); uint32_t ecc = 0; for (size_t ii = 0; ii < frame_data.size(); ++ii) { uint32_t word = frame_data[ii]; uint32_t offset = ii * 32; if (ii > 0x25) { offset += 0x1360; } else if (ii > 0x6) { offset += 0x1340; } else { offset += 0x1320; } // Mask out where the ECC should be. if (ii == 0x32) { word &= 0xFFFFE000; } for (int jj = 0; jj < 32; ++jj) { if ((word & 1) == 1) { ecc ^= offset + jj; } word >>= 1; } } uint32_t v = ecc & 0xFFF; v ^= v >> 8; v ^= v >> 4; v ^= v >> 2; v ^= v >> 1; ecc ^= (v & 1) << 12; // Replace the old ECC with the new. frame_data[0x32] &= 0xFFFFE000; frame_data[0x32] |= (ecc & 0x1FFF); } #if 0 for (auto& frame : frames) { std::cout << "0x" << std::hex << static_cast<uint32_t>(frame.first) << " "; for (auto& word : frame.second) { std::cout << "0x" << std::hex << word << ","; } std::cout << std::endl; } #endif std::vector<xc7series::ConfigurationPacket> out_packets; // Generate a single type 2 packet that writes everything at once. std::vector<uint32_t> packet_data; for (auto& frame : frames) { std::copy(frame.second.begin(), frame.second.end(), std::back_inserter(packet_data)); auto next_address = part->GetNextFrameAddress(frame.first); if (next_address && (next_address->block_type() != frame.first.block_type() || next_address->is_bottom_half_rows() != frame.first.is_bottom_half_rows() || next_address->row() != frame.first.row())) { packet_data.insert(packet_data.end(), 202, 0); } } packet_data.insert(packet_data.end(), 202, 0); out_packets.push_back(xc7series::ConfigurationPacket( 1, xc7series::ConfigurationPacket::Opcode::Write, xc7series::ConfigurationRegister::FDRI, {})); out_packets.push_back(xc7series::ConfigurationPacket( 2, xc7series::ConfigurationPacket::Opcode::Write, xc7series::ConfigurationRegister::FDRI, packet_data)); #if 0 for (auto& packet : out_packets) { std::cout << packet << std::endl; } #endif // Write bitstream. xc7series::BitstreamWriter out_bitstream_writer(out_packets); std::ofstream out_file(FLAGS_output_file); if (!out_file) { std::cerr << "Unable to open file for writting: " << FLAGS_output_file << std::endl; return 1; } for (uint32_t word : out_bitstream_writer) { out_file.put((word >> 24) & 0xFF); out_file.put((word >> 16) & 0xFF); out_file.put((word >> 8) & 0xFF); out_file.put((word)&0xFF); } return 0; } <commit_msg>xc7patch: use ECC calculation from lib<commit_after>#include <algorithm> #include <fstream> #include <iostream> #include <iterator> #include <string> #include <vector> #include <absl/strings/str_split.h> #include <gflags/gflags.h> #include <prjxray/memory_mapped_file.h> #include <prjxray/xilinx/xc7series/bitstream_reader.h> #include <prjxray/xilinx/xc7series/bitstream_writer.h> #include <prjxray/xilinx/xc7series/configuration.h> #include <prjxray/xilinx/xc7series/ecc.h> #include <prjxray/xilinx/xc7series/part.h> DEFINE_string(part_file, "", "Definition file for target 7-series part"); DEFINE_string(bitstream_file, "", "Initial bitstream to which the deltas are applied."); DEFINE_string( frm_file, "", "File containing a list of frame deltas to be applied to the base " "bitstream. Each line in the file is of the form: " "<frame_address> <word1>,...,<word101>."); DEFINE_string(output_file, "", "Write patched bitsteam to file"); namespace xc7series = prjxray::xilinx::xc7series; int main(int argc, char* argv[]) { gflags::SetUsageMessage(argv[0]); gflags::ParseCommandLineFlags(&argc, &argv, true); auto part = xc7series::Part::FromFile(FLAGS_part_file); if (!part) { std::cerr << "Part file not found or invalid" << std::endl; return 1; } auto bitstream_file = prjxray::MemoryMappedFile::InitWithFile(FLAGS_bitstream_file); if (!bitstream_file) { std::cerr << "Can't open base bitstream file: " << FLAGS_bitstream_file << std::endl; return 1; } auto bitstream_reader = xc7series::BitstreamReader::InitWithBytes( bitstream_file->as_bytes()); if (!bitstream_reader) { std::cout << "Bitstream does not appear to be a 7-series bitstream!" << std::endl; return 1; } auto bitstream_config = xc7series::Configuration::InitWithPackets(*part, *bitstream_reader); if (!bitstream_config) { std::cerr << "Bitstream does not appear to be for this part" << std::endl; return 1; } // Copy the base frames to a mutable collection std::map<xc7series::FrameAddress, std::vector<uint32_t>> frames; for (auto& frame_val : bitstream_config->frames()) { auto& cur_frame = frames[frame_val.first]; std::copy(frame_val.second.begin(), frame_val.second.end(), std::back_inserter(cur_frame)); } // Apply the deltas. std::ifstream frm_file(FLAGS_frm_file); if (!frm_file) { std::cerr << "Unable to open frm file: " << FLAGS_frm_file << std::endl; return 1; } std::string frm_line; while (std::getline(frm_file, frm_line)) { if (frm_line[0] == '#') continue; std::pair<std::string, std::string> frame_delta = absl::StrSplit(frm_line, ' '); uint32_t frame_address = std::stoul(frame_delta.first, nullptr, 16); auto& frame_data = frames[frame_address]; frame_data.resize(101); std::vector<std::string> frame_data_strings = absl::StrSplit(frame_delta.second, ','); if (frame_data_strings.size() != 101) { std::cerr << "Frame " << std::hex << frame_address << ": found " << std::dec << frame_data_strings.size() << "words instead of 101"; continue; }; std::transform(frame_data_strings.begin(), frame_data_strings.end(), frame_data.begin(), [](const std::string& val) -> uint32_t { return std::stoul(val, nullptr, 16); }); uint32_t ecc = 0; for (size_t ii = 0; ii < frame_data.size(); ++ii) { ecc = xc7series::icap_ecc(ii, frame_data[ii], ecc); } // Replace the old ECC with the new. frame_data[0x32] &= 0xFFFFE000; frame_data[0x32] |= (ecc & 0x1FFF); } #if 0 for (auto& frame : frames) { std::cout << "0x" << std::hex << static_cast<uint32_t>(frame.first) << " "; for (auto& word : frame.second) { std::cout << "0x" << std::hex << word << ","; } std::cout << std::endl; } #endif std::vector<xc7series::ConfigurationPacket> out_packets; // Generate a single type 2 packet that writes everything at once. std::vector<uint32_t> packet_data; for (auto& frame : frames) { std::copy(frame.second.begin(), frame.second.end(), std::back_inserter(packet_data)); auto next_address = part->GetNextFrameAddress(frame.first); if (next_address && (next_address->block_type() != frame.first.block_type() || next_address->is_bottom_half_rows() != frame.first.is_bottom_half_rows() || next_address->row() != frame.first.row())) { packet_data.insert(packet_data.end(), 202, 0); } } packet_data.insert(packet_data.end(), 202, 0); out_packets.push_back(xc7series::ConfigurationPacket( 1, xc7series::ConfigurationPacket::Opcode::Write, xc7series::ConfigurationRegister::FDRI, {})); out_packets.push_back(xc7series::ConfigurationPacket( 2, xc7series::ConfigurationPacket::Opcode::Write, xc7series::ConfigurationRegister::FDRI, packet_data)); #if 0 for (auto& packet : out_packets) { std::cout << packet << std::endl; } #endif // Write bitstream. xc7series::BitstreamWriter out_bitstream_writer(out_packets); std::ofstream out_file(FLAGS_output_file); if (!out_file) { std::cerr << "Unable to open file for writting: " << FLAGS_output_file << std::endl; return 1; } for (uint32_t word : out_bitstream_writer) { out_file.put((word >> 24) & 0xFF); out_file.put((word >> 16) & 0xFF); out_file.put((word >> 8) & 0xFF); out_file.put((word)&0xFF); } return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: accessiblefactory.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: obo $ $Date: 2007-07-18 10:06:14 $ * * 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 TOOLKIT_HELPER_ACCESSIBLE_FACTORY_HXX #define TOOLKIT_HELPER_ACCESSIBLE_FACTORY_HXX #ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX #include <com/sun/star/uno/Reference.hxx> #endif #ifndef _RTL_REF_HXX #include <rtl/ref.hxx> #endif namespace com { namespace sun { namespace star { namespace accessibility { class XAccessible; class XAccessibleContext; } } } } class VCLXButton; class VCLXCheckBox; class VCLXRadioButton; class VCLXListBox; class VCLXFixedText; class VCLXScrollBar; class VCLXEdit; class VCLXComboBox; class VCLXToolBox; class VCLXWindow; class Menu; //........................................................................ namespace toolkit { //........................................................................ /** a function which is able to create a factory for the standard Accessible/Context components needed for standard toolkit controls The returned pointer denotes an instance of the IAccessibleFactory, which has been acquired <em>once</em>. The caller is responsible for holding this reference as long as it needs the factory, and release it afterwards. */ typedef void* (SAL_CALL * GetStandardAccComponentFactory)( ); //================================================================ //= IAccessibleFactory //================================================================ class IAccessibleFactory : public ::rtl::IReference { public: /** creates an accessible context for a button window */ virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > createAccessibleContext( VCLXButton* _pXWindow ) = 0; /** creates an accessible context for a checkbox window */ virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > createAccessibleContext( VCLXCheckBox* _pXWindow ) = 0; /** creates an accessible context for a radio button window */ virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > createAccessibleContext( VCLXRadioButton* _pXWindow ) = 0; /** creates an accessible context for a listbox window */ virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > createAccessibleContext( VCLXListBox* _pXWindow ) = 0; /** creates an accessible context for a fixed text window */ virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > createAccessibleContext( VCLXFixedText* _pXWindow ) = 0; /** creates an accessible context for a scrollbar window */ virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > createAccessibleContext( VCLXScrollBar* _pXWindow ) = 0; /** creates an accessible context for a edit window */ virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > createAccessibleContext( VCLXEdit* _pXWindow ) = 0; /** creates an accessible context for a combo box window */ virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > createAccessibleContext( VCLXComboBox* _pXWindow ) = 0; /** creates an accessible context for a toolbox window */ virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > createAccessibleContext( VCLXToolBox* _pXWindow ) = 0; /** creates an accessible context for a generic window */ virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > createAccessibleContext( VCLXWindow* _pXWindow ) = 0; /** creates an accessible component for the given menu */ virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > createAccessible( Menu* _pMenu, sal_Bool _bIsMenuBar ) = 0; }; //........................................................................ } // namespace toolkit //........................................................................ #endif // TOOLKIT_HELPER_ACCESSIBLE_FACTORY_HXX <commit_msg>INTEGRATION: CWS fwk80_SRC680 (1.3.52); FILE MERGED 2008/01/11 14:39:42 pb 1.3.52.1: fix: #i83756# createAccessibleContext( VCLXFixedHyperlink* )<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: accessiblefactory.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2008-01-29 15:04:18 $ * * 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 TOOLKIT_HELPER_ACCESSIBLE_FACTORY_HXX #define TOOLKIT_HELPER_ACCESSIBLE_FACTORY_HXX #ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX #include <com/sun/star/uno/Reference.hxx> #endif #ifndef _RTL_REF_HXX #include <rtl/ref.hxx> #endif namespace com { namespace sun { namespace star { namespace accessibility { class XAccessible; class XAccessibleContext; } } } } class VCLXButton; class VCLXCheckBox; class VCLXRadioButton; class VCLXListBox; class VCLXFixedHyperlink; class VCLXFixedText; class VCLXScrollBar; class VCLXEdit; class VCLXComboBox; class VCLXToolBox; class VCLXWindow; class Menu; //........................................................................ namespace toolkit { //........................................................................ /** a function which is able to create a factory for the standard Accessible/Context components needed for standard toolkit controls The returned pointer denotes an instance of the IAccessibleFactory, which has been acquired <em>once</em>. The caller is responsible for holding this reference as long as it needs the factory, and release it afterwards. */ typedef void* (SAL_CALL * GetStandardAccComponentFactory)( ); //================================================================ //= IAccessibleFactory //================================================================ class IAccessibleFactory : public ::rtl::IReference { public: /** creates an accessible context for a button window */ virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > createAccessibleContext( VCLXButton* _pXWindow ) = 0; /** creates an accessible context for a checkbox window */ virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > createAccessibleContext( VCLXCheckBox* _pXWindow ) = 0; /** creates an accessible context for a radio button window */ virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > createAccessibleContext( VCLXRadioButton* _pXWindow ) = 0; /** creates an accessible context for a listbox window */ virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > createAccessibleContext( VCLXListBox* _pXWindow ) = 0; /** creates an accessible context for a fixed hyperlink window */ virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > createAccessibleContext( VCLXFixedHyperlink* _pXWindow ) = 0; /** creates an accessible context for a fixed text window */ virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > createAccessibleContext( VCLXFixedText* _pXWindow ) = 0; /** creates an accessible context for a scrollbar window */ virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > createAccessibleContext( VCLXScrollBar* _pXWindow ) = 0; /** creates an accessible context for a edit window */ virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > createAccessibleContext( VCLXEdit* _pXWindow ) = 0; /** creates an accessible context for a combo box window */ virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > createAccessibleContext( VCLXComboBox* _pXWindow ) = 0; /** creates an accessible context for a toolbox window */ virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > createAccessibleContext( VCLXToolBox* _pXWindow ) = 0; /** creates an accessible context for a generic window */ virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > createAccessibleContext( VCLXWindow* _pXWindow ) = 0; /** creates an accessible component for the given menu */ virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > createAccessible( Menu* _pMenu, sal_Bool _bIsMenuBar ) = 0; }; //........................................................................ } // namespace toolkit //........................................................................ #endif // TOOLKIT_HELPER_ACCESSIBLE_FACTORY_HXX <|endoftext|>
<commit_before>/** \file oai_pmh_harvester.cc * \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de) * * \copyright 2017,2018 Universitätsbibliothek Tübingen. All rights reserved. * * 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/>. */ #include <iostream> #include <cctype> #include <kchashdb.h> #include "Compiler.h" #include "Downloader.h" #include "FileUtil.h" #include "HttpHeader.h" #include "MARC.h" #include "StringDataSource.h" #include "StringUtil.h" #include "UrlUtil.h" #include "XMLParser.h" #include "util.h" //https://memory.loc.gov/cgi-bin/oai2_0?verb=ListRecords&metadataPrefix=marc21&set=mussm void Usage() { std::cerr << "Usage: " << ::progname << " [--skip-dups] [--ignore-ssl-certificates] base_url metadata_prefix [harvest_set] control_number_prefix output_filename" << " time_limit_per_request\n" << " If \"--skip-dups\" has been specified, records that we already encountered in the past won't\n" << " included in the output file.\n" << " \"control_number_prefix\" will be used if the received records have no control numbers\n" << " to autogenerate our own control numbers. \"time_limit_per_request\" is in seconds. (Some\n" << " servers are very slow so we recommend at least 20 seconds!)\n\n"; std::exit(EXIT_FAILURE); } std::string ExtractResumptionToken(const std::string &xml_document, std::string * const cursor, std::string * const complete_list_size) { cursor->clear(); complete_list_size->clear(); XMLParser xml_parser(xml_document, XMLParser::XML_STRING); if (not xml_parser.skipTo(XMLParser::XMLPart::OPENING_TAG, "resumptionToken")) return ""; XMLParser::XMLPart xml_part; if (not xml_parser.getNext(&xml_part) or xml_part.type_ == XMLParser::XMLPart::CLOSING_TAG) return ""; if (xml_part.type_ != XMLParser::XMLPart::CHARACTERS) LOG_ERROR("strange resumption token XML structure!"); // Extract the "cursor" attribute: auto name_and_value(xml_part.attributes_.find("cursor")); if (name_and_value != xml_part.attributes_.end()) *cursor = name_and_value->second; // Extract the "completeListSize" attribute: name_and_value = xml_part.attributes_.find("completeListSize"); if (name_and_value != xml_part.attributes_.end()) *complete_list_size = name_and_value->second; return xml_part.data_; } // Helper for ExtractEncapsulatedRecordData. Removes the trailing whitespace and </metadata>. bool StripOffTrailingGarbage(std::string * const extracted_records) { // 1. back skip over the "</metadata>": size_t pos(extracted_records->rfind('<')); if (unlikely(pos == std::string::npos)) return false; // 2. Now remove any trailing whitespace: while (likely(pos > 0) and isspace((*extracted_records)[--pos])) /* Intentionally empty! */; extracted_records->resize(pos + 1); return true; } // Returns the number of extracted records. unsigned ExtractEncapsulatedRecordData(XMLParser * const xml_parser, std::string * const extracted_records) { unsigned record_count(0); while (xml_parser->skipTo(XMLParser::XMLPart::OPENING_TAG, "record")) { ++record_count; if (not xml_parser->skipTo(XMLParser::XMLPart::OPENING_TAG, "metadata")) LOG_ERROR("no <metadata> tag found after a <record> tag!"); XMLParser::XMLPart extracted_records_part; if (not xml_parser->skipTo(XMLParser::XMLPart::CLOSING_TAG, "metadata", &extracted_records_part)) LOG_ERROR("no </metadata> tag found after a <metadata> tag!"); *extracted_records = extracted_records_part.data_; StripOffTrailingGarbage(extracted_records); *extracted_records += '\n'; } return record_count; } bool ListRecords(const std::string &url, const unsigned time_limit_in_seconds_per_request, const bool ignore_ssl_certificates, File * const output, std::string * const resumption_token, std::string * const cursor, std::string * const complete_list_size, unsigned * total_record_count) { const TimeLimit time_limit(time_limit_in_seconds_per_request * 1000); Downloader::Params params(Downloader::DEFAULT_USER_AGENT_STRING, Downloader::DEFAULT_ACCEPTABLE_LANGUAGES, Downloader::DEFAULT_MAX_REDIRECTS, Downloader::DEFAULT_DNS_CACHE_TIMEOUT, false, /*honour_robots_dot_txt*/ Downloader::TRANSPARENT, PerlCompatRegExps(), false, /*debugging*/ true,/*follow_redirects*/ Downloader::DEFAULT_META_REDIRECT_THRESHOLD, ignore_ssl_certificates, /*ignore SSL certificates*/ "", /*proxy_host_and_port*/ {}, /*additional headers*/ "" /*post_data*/); Downloader downloader(url, params, time_limit); if (downloader.anErrorOccurred()) LOG_ERROR("harvest failed: " + downloader.getLastErrorMessage()); const HttpHeader http_header(downloader.getMessageHeader()); const unsigned status_code(http_header.getStatusCode()); if (status_code < 200 or status_code > 299) LOG_ERROR("server returned a status code of " + std::to_string(status_code) + "!"); const std::string message_body(downloader.getMessageBody()); std::string extracted_records; XMLParser xml_parser(message_body, XMLParser::XML_STRING); const unsigned record_count(ExtractEncapsulatedRecordData(&xml_parser, &extracted_records)); if (record_count == 0) { xml_parser.rewind(); XMLParser::XMLPart xml_part; if (not xml_parser.skipTo(XMLParser::XMLPart::OPENING_TAG, "error", &xml_part)) return 0; const auto key_and_value(xml_part.attributes_.find("code")); std::string error_msg; if (key_and_value != xml_part.attributes_.cend()) error_msg += key_and_value->second + ": "; if (xml_parser.getNext(&xml_part) and xml_part.type_ == XMLParser::XMLPart::CHARACTERS) error_msg += xml_part.data_; LOG_ERROR("OAI-PMH server returned an error: " + error_msg + " (We sent \"" + url + "\")"); } else { // record_count > 0 *total_record_count += record_count; if (not output->write(extracted_records)) LOG_ERROR("failed to write to \"" + output->getPath() + "\"! (Disc full?)"); } *resumption_token = ExtractResumptionToken(message_body, cursor, complete_list_size); return not resumption_token->empty(); } std::string MakeRequestURL(const std::string &base_url, const std::string &metadata_prefix, const std::string &harvest_set, const std::string &resumption_token) { std::string request_url; if (not resumption_token.empty()) request_url = base_url + "?verb=ListRecords&resumptionToken=" + UrlUtil::UrlEncode(resumption_token); else if (harvest_set.empty()) request_url = base_url + "?verb=ListRecords&metadataPrefix=" + metadata_prefix; else request_url = base_url + "?verb=ListRecords&metadataPrefix=" + metadata_prefix + "&set=" + harvest_set; LOG_INFO("Request URL = " + request_url); return request_url; } const std::string OAI_DUPS_DB_FILENAME("/usr/local/var/lib/tuelib/oai_dups.db"); std::unique_ptr<kyotocabinet::HashDB> CreateOrOpenKeyValueDB() { std::unique_ptr<kyotocabinet::HashDB> db(new kyotocabinet::HashDB()); if (not (db->open(OAI_DUPS_DB_FILENAME, kyotocabinet::HashDB::OWRITER | kyotocabinet::HashDB::OREADER | kyotocabinet::HashDB::OCREATE))) LOG_ERROR("failed to open or create \"" + OAI_DUPS_DB_FILENAME + "\"!"); return db; } void GenerateValidatedOutput(kyotocabinet::HashDB * const dups_db, MARC::Reader * const marc_reader, const std::string &control_number_prefix, MARC::Writer * const marc_writer) { unsigned counter(0); while (MARC::Record record = marc_reader->read()) { if (not record.hasValidLeader()) continue; if (dups_db != nullptr) { const std::string checksum(MARC::CalcChecksum(record)); if (dups_db->check(checksum) > 0) { LOG_DEBUG("found a dupe w/ checksum \"" + checksum + "\"."); continue; } dups_db->add(checksum, TimeUtil::GetCurrentDateAndTime()); } if (record.getControlNumber().empty()) { const std::string control_number(control_number_prefix + StringUtil::Map(StringUtil::ToString(++counter, 10, 10), ' ', '0')); record.insertField("001", control_number); } marc_writer->write(record); } } int main(int argc, char **argv) { ::progname = argv[0]; std::unique_ptr<kyotocabinet::HashDB> dups_db; if (argc > 1 and std::strcmp(argv[1], "--skip-dups") == 0) { dups_db = CreateOrOpenKeyValueDB(); --argc, ++argv; } bool ignore_ssl_certificates(false); if (argc > 1 and std::strcmp(argv[1], "--ignore-ssl-certificates") == 0) { ignore_ssl_certificates = true; --argc, ++argv; } if (argc != 6 and argc != 7) Usage(); const std::string base_url(argv[1]); const std::string metadata_prefix(argv[2]); const std::string harvest_set(argc == 7 ? argv[3] : ""); const std::string control_number_prefix(argc == 7 ? argv[3] : argv[2]); const std::string output_filename(argc == 7 ? argv[5] : argv[4]); const std::string time_limit_per_request_as_string(argc == 7 ? argv[6] : argv[5]); unsigned time_limit_per_request_in_seconds; if (not StringUtil::ToUnsigned(time_limit_per_request_as_string, &time_limit_per_request_in_seconds)) LOG_ERROR("\"" + time_limit_per_request_as_string + "\" is not a valid time limit!"); try { const std::string TEMP_FILENAME("/tmp/oai_pmh_harvester.temp.xml"); std::unique_ptr<File> temp_output(FileUtil::OpenOutputFileOrDie(TEMP_FILENAME)); const std::string COLLECTION_OPEN( "<collection xmlns=\"http://www.loc.gov/MARC21/slim\" " "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " "xsi:schemaLocation=\"http://www.loc.gov/standards/marcxml/schema/MARC21slim.xsd\">"); temp_output->write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + COLLECTION_OPEN + "\n"); std::string resumption_token, cursor, complete_list_size; unsigned total_record_count(0); while (ListRecords(MakeRequestURL(base_url, metadata_prefix, harvest_set, resumption_token), time_limit_per_request_in_seconds, ignore_ssl_certificates, temp_output.get(), &resumption_token, &cursor, &complete_list_size, &total_record_count)) LOG_INFO("Continuing download, resumption token was: \"" + resumption_token + "\" (cursor=" + cursor + ", completeListSize=" + complete_list_size + ")."); const std::string COLLECTION_CLOSE("</collection>"); temp_output->write(COLLECTION_CLOSE + "\n"); temp_output->close(); LOG_INFO("Downloaded " + std::to_string(total_record_count) + " record(s)."); std::unique_ptr<MARC::Reader> marc_reader(MARC::Reader::Factory(TEMP_FILENAME, MARC::FileType::XML)); std::unique_ptr<MARC::Writer> marc_writer(MARC::Writer::Factory(output_filename)); GenerateValidatedOutput(dups_db.get(), marc_reader.get(), control_number_prefix, marc_writer.get()); ::unlink(TEMP_FILENAME.c_str()); } catch (const std::exception &x) { LOG_ERROR("caught exception: " + std::string(x.what())); } } <commit_msg>removed unneccesary linebreak<commit_after>/** \file oai_pmh_harvester.cc * \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de) * * \copyright 2017,2018 Universitätsbibliothek Tübingen. All rights reserved. * * 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/>. */ #include <iostream> #include <cctype> #include <kchashdb.h> #include "Compiler.h" #include "Downloader.h" #include "FileUtil.h" #include "HttpHeader.h" #include "MARC.h" #include "StringDataSource.h" #include "StringUtil.h" #include "UrlUtil.h" #include "XMLParser.h" #include "util.h" //https://memory.loc.gov/cgi-bin/oai2_0?verb=ListRecords&metadataPrefix=marc21&set=mussm void Usage() { std::cerr << "Usage: " << ::progname << " [--skip-dups] [--ignore-ssl-certificates] base_url metadata_prefix [harvest_set] control_number_prefix output_filename" << " time_limit_per_request\n" << " If \"--skip-dups\" has been specified, records that we already encountered in the past won't\n" << " included in the output file.\n" << " \"control_number_prefix\" will be used if the received records have no control numbers\n" << " to autogenerate our own control numbers. \"time_limit_per_request\" is in seconds. (Some\n" << " servers are very slow so we recommend at least 20 seconds!)\n\n"; std::exit(EXIT_FAILURE); } std::string ExtractResumptionToken(const std::string &xml_document, std::string * const cursor, std::string * const complete_list_size) { cursor->clear(); complete_list_size->clear(); XMLParser xml_parser(xml_document, XMLParser::XML_STRING); if (not xml_parser.skipTo(XMLParser::XMLPart::OPENING_TAG, "resumptionToken")) return ""; XMLParser::XMLPart xml_part; if (not xml_parser.getNext(&xml_part) or xml_part.type_ == XMLParser::XMLPart::CLOSING_TAG) return ""; if (xml_part.type_ != XMLParser::XMLPart::CHARACTERS) LOG_ERROR("strange resumption token XML structure!"); // Extract the "cursor" attribute: auto name_and_value(xml_part.attributes_.find("cursor")); if (name_and_value != xml_part.attributes_.end()) *cursor = name_and_value->second; // Extract the "completeListSize" attribute: name_and_value = xml_part.attributes_.find("completeListSize"); if (name_and_value != xml_part.attributes_.end()) *complete_list_size = name_and_value->second; return xml_part.data_; } // Helper for ExtractEncapsulatedRecordData. Removes the trailing whitespace and </metadata>. bool StripOffTrailingGarbage(std::string * const extracted_records) { // 1. back skip over the "</metadata>": size_t pos(extracted_records->rfind('<')); if (unlikely(pos == std::string::npos)) return false; // 2. Now remove any trailing whitespace: while (likely(pos > 0) and isspace((*extracted_records)[--pos])) /* Intentionally empty! */; extracted_records->resize(pos + 1); return true; } // Returns the number of extracted records. unsigned ExtractEncapsulatedRecordData(XMLParser * const xml_parser, std::string * const extracted_records) { unsigned record_count(0); while (xml_parser->skipTo(XMLParser::XMLPart::OPENING_TAG, "record")) { ++record_count; if (not xml_parser->skipTo(XMLParser::XMLPart::OPENING_TAG, "metadata")) LOG_ERROR("no <metadata> tag found after a <record> tag!"); XMLParser::XMLPart extracted_records_part; if (not xml_parser->skipTo(XMLParser::XMLPart::CLOSING_TAG, "metadata", &extracted_records_part)) LOG_ERROR("no </metadata> tag found after a <metadata> tag!"); *extracted_records = extracted_records_part.data_; StripOffTrailingGarbage(extracted_records); *extracted_records += '\n'; } return record_count; } bool ListRecords(const std::string &url, const unsigned time_limit_in_seconds_per_request, const bool ignore_ssl_certificates, File * const output, std::string * const resumption_token, std::string * const cursor, std::string * const complete_list_size, unsigned * total_record_count) { const TimeLimit time_limit(time_limit_in_seconds_per_request * 1000); Downloader::Params params(Downloader::DEFAULT_USER_AGENT_STRING, Downloader::DEFAULT_ACCEPTABLE_LANGUAGES, Downloader::DEFAULT_MAX_REDIRECTS, Downloader::DEFAULT_DNS_CACHE_TIMEOUT, false, /*honour_robots_dot_txt*/ Downloader::TRANSPARENT, PerlCompatRegExps(), false, /*debugging*/ true,/*follow_redirects*/ Downloader::DEFAULT_META_REDIRECT_THRESHOLD, ignore_ssl_certificates, /*ignore SSL certificates*/ "", /*proxy_host_and_port*/ {}, /*additional headers*/ "" /*post_data*/); Downloader downloader(url, params, time_limit); if (downloader.anErrorOccurred()) LOG_ERROR("harvest failed: " + downloader.getLastErrorMessage()); const HttpHeader http_header(downloader.getMessageHeader()); const unsigned status_code(http_header.getStatusCode()); if (status_code < 200 or status_code > 299) LOG_ERROR("server returned a status code of " + std::to_string(status_code) + "!"); const std::string message_body(downloader.getMessageBody()); std::string extracted_records; XMLParser xml_parser(message_body, XMLParser::XML_STRING); const unsigned record_count(ExtractEncapsulatedRecordData(&xml_parser, &extracted_records)); if (record_count == 0) { xml_parser.rewind(); XMLParser::XMLPart xml_part; if (not xml_parser.skipTo(XMLParser::XMLPart::OPENING_TAG, "error", &xml_part)) return 0; const auto key_and_value(xml_part.attributes_.find("code")); std::string error_msg; if (key_and_value != xml_part.attributes_.cend()) error_msg += key_and_value->second + ": "; if (xml_parser.getNext(&xml_part) and xml_part.type_ == XMLParser::XMLPart::CHARACTERS) error_msg += xml_part.data_; LOG_ERROR("OAI-PMH server returned an error: " + error_msg + " (We sent \"" + url + "\")"); } else { // record_count > 0 *total_record_count += record_count; if (not output->write(extracted_records)) LOG_ERROR("failed to write to \"" + output->getPath() + "\"! (Disc full?)"); } *resumption_token = ExtractResumptionToken(message_body, cursor, complete_list_size); return not resumption_token->empty(); } std::string MakeRequestURL(const std::string &base_url, const std::string &metadata_prefix, const std::string &harvest_set, const std::string &resumption_token) { std::string request_url; if (not resumption_token.empty()) request_url = base_url + "?verb=ListRecords&resumptionToken=" + UrlUtil::UrlEncode(resumption_token); else if (harvest_set.empty()) request_url = base_url + "?verb=ListRecords&metadataPrefix=" + metadata_prefix; else request_url = base_url + "?verb=ListRecords&metadataPrefix=" + metadata_prefix + "&set=" + harvest_set; LOG_INFO("Request URL = " + request_url); return request_url; } const std::string OAI_DUPS_DB_FILENAME("/usr/local/var/lib/tuelib/oai_dups.db"); std::unique_ptr<kyotocabinet::HashDB> CreateOrOpenKeyValueDB() { std::unique_ptr<kyotocabinet::HashDB> db(new kyotocabinet::HashDB()); if (not (db->open(OAI_DUPS_DB_FILENAME, kyotocabinet::HashDB::OWRITER | kyotocabinet::HashDB::OREADER | kyotocabinet::HashDB::OCREATE))) LOG_ERROR("failed to open or create \"" + OAI_DUPS_DB_FILENAME + "\"!"); return db; } void GenerateValidatedOutput(kyotocabinet::HashDB * const dups_db, MARC::Reader * const marc_reader, const std::string &control_number_prefix, MARC::Writer * const marc_writer) { unsigned counter(0); while (MARC::Record record = marc_reader->read()) { if (not record.hasValidLeader()) continue; if (dups_db != nullptr) { const std::string checksum(MARC::CalcChecksum(record)); if (dups_db->check(checksum) > 0) { LOG_DEBUG("found a dupe w/ checksum \"" + checksum + "\"."); continue; } dups_db->add(checksum, TimeUtil::GetCurrentDateAndTime()); } if (record.getControlNumber().empty()) { const std::string control_number(control_number_prefix + StringUtil::Map(StringUtil::ToString(++counter, 10, 10), ' ', '0')); record.insertField("001", control_number); } marc_writer->write(record); } } int main(int argc, char **argv) { ::progname = argv[0]; std::unique_ptr<kyotocabinet::HashDB> dups_db; if (argc > 1 and std::strcmp(argv[1], "--skip-dups") == 0) { dups_db = CreateOrOpenKeyValueDB(); --argc, ++argv; } bool ignore_ssl_certificates(false); if (argc > 1 and std::strcmp(argv[1], "--ignore-ssl-certificates") == 0) { ignore_ssl_certificates = true; --argc, ++argv; } if (argc != 6 and argc != 7) Usage(); const std::string base_url(argv[1]); const std::string metadata_prefix(argv[2]); const std::string harvest_set(argc == 7 ? argv[3] : ""); const std::string control_number_prefix(argc == 7 ? argv[3] : argv[2]); const std::string output_filename(argc == 7 ? argv[5] : argv[4]); const std::string time_limit_per_request_as_string(argc == 7 ? argv[6] : argv[5]); unsigned time_limit_per_request_in_seconds; if (not StringUtil::ToUnsigned(time_limit_per_request_as_string, &time_limit_per_request_in_seconds)) LOG_ERROR("\"" + time_limit_per_request_as_string + "\" is not a valid time limit!"); try { const std::string TEMP_FILENAME("/tmp/oai_pmh_harvester.temp.xml"); std::unique_ptr<File> temp_output(FileUtil::OpenOutputFileOrDie(TEMP_FILENAME)); const std::string COLLECTION_OPEN( "<collection xmlns=\"http://www.loc.gov/MARC21/slim\" " "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " "xsi:schemaLocation=\"http://www.loc.gov/standards/marcxml/schema/MARC21slim.xsd\">"); temp_output->write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + COLLECTION_OPEN + "\n"); std::string resumption_token, cursor, complete_list_size; unsigned total_record_count(0); while (ListRecords(MakeRequestURL(base_url, metadata_prefix, harvest_set, resumption_token), time_limit_per_request_in_seconds, ignore_ssl_certificates, temp_output.get(), &resumption_token, &cursor, &complete_list_size, &total_record_count)) LOG_INFO("Continuing download, resumption token was: \"" + resumption_token + "\" (cursor=" + cursor + ", completeListSize=" + complete_list_size + ")."); const std::string COLLECTION_CLOSE("</collection>"); temp_output->write(COLLECTION_CLOSE + "\n"); temp_output->close(); LOG_INFO("Downloaded " + std::to_string(total_record_count) + " record(s)."); std::unique_ptr<MARC::Reader> marc_reader(MARC::Reader::Factory(TEMP_FILENAME, MARC::FileType::XML)); std::unique_ptr<MARC::Writer> marc_writer(MARC::Writer::Factory(output_filename)); GenerateValidatedOutput(dups_db.get(), marc_reader.get(), control_number_prefix, marc_writer.get()); ::unlink(TEMP_FILENAME.c_str()); } catch (const std::exception &x) { LOG_ERROR("caught exception: " + std::string(x.what())); } } <|endoftext|>
<commit_before>// // media-stream.cpp // libndnrtc // // Copyright 2013 Regents of the University of California // For licensing details see the LICENSE file. // // Author: Peter Gusev // #include "media-stream.h" #include "video-thread.h" #include "audio-thread.h" #include "ndnrtc-namespace.h" using namespace webrtc; using namespace boost; using namespace ndnrtc; using namespace ndnrtc::new_api; //****************************************************************************** MediaStream::MediaStream() { } MediaStream::~MediaStream() { } int MediaStream::init(const MediaStreamSettings& streamSettings) { settings_ = streamSettings; streamName_ = settings_.streamParams_.streamName_; streamPrefix_ = *NdnRtcNamespace::getStreamPrefix(settings_.userPrefix_, streamName_); int res = RESULT_OK; for (int i = 0; i < settings_.streamParams_.mediaThreads_.size() && RESULT_GOOD(res); i++) res = addNewMediaThread(settings_.streamParams_.mediaThreads_[i]); return res; } void MediaStream::release() { ThreadMap::iterator it = threads_.begin(); while (it != threads_.end()) { it->second->stop(); it++; } threads_.clear(); } void MediaStream::addThread(const MediaThreadParams& threadParams) { } void MediaStream::removeThread(const std::string& threadName) { } void MediaStream::removeAllThreads() { } // private void MediaStream::getCommonThreadSettings(MediaThreadSettings* settings) { settings->segmentSize_ = settings_.streamParams_.producerParams_.segmentSize_; settings->dataFreshnessMs_ = settings_.streamParams_.producerParams_.freshnessMs_; settings->streamPrefix_ = streamPrefix_; settings->certificateName_ = *NdnRtcNamespace::certificateNameForUser(settings_.userPrefix_); settings->keyChain_ = settings_.keyChain_; settings->faceProcessor_ = settings_.faceProcessor_; settings->memoryCache_ = settings_.memoryCache_; } void MediaStream::onMediaThreadRegistrationFailed(std::string threadName) { LogWarnC << "failed to register thread " << threadName << std::endl; } //****************************************************************************** VideoStream::VideoStream(): MediaStream(), capturer_(new ExternalCapturer()) { description_ = "video-stream"; capturer_->setFrameConsumer(this); } int VideoStream::init(const MediaStreamSettings& streamSettings) { if (RESULT_GOOD(MediaStream::init(streamSettings))) { capturer_->setLogger(logger_); isProcessing_ = true; return RESULT_OK; } return RESULT_ERR; } MediaStreamParams VideoStream::getStreamParameters() { MediaStreamParams params(settings_.streamParams_); // update average segments numbers for frames for (int i = 0; i < params.mediaThreads_.size(); i++) { VideoThreadParams* threadParams = ((VideoThreadParams*)params.mediaThreads_[i]); std::string threadKey = *NdnRtcNamespace::buildPath(false, &streamPrefix_, &threadParams->threadName_, 0); VideoThreadStatistics stat; shared_ptr<VideoThread> thread = dynamic_pointer_cast<VideoThread>(threads_[threadKey]); thread->getStatistics(stat); threadParams->deltaAvgSegNum_ = stat.deltaAvgSegNum_; threadParams->deltaAvgParitySegNum_ = stat.deltaAvgParitySegNum_; threadParams->keyAvgSegNum_ = stat.keyAvgSegNum_; threadParams->keyAvgParitySegNum_ = stat.keyAvgParitySegNum_; } return params; } bool VideoStream::isStreamStatReady() { bool statReady = true; for (auto it:threads_) statReady &= dynamic_pointer_cast<VideoThread>(it.second)->isThreadStatReady(); return statReady; } void VideoStream::release() { MediaStream::release(); isProcessing_ = false; } int VideoStream::addNewMediaThread(const MediaThreadParams* params) { VideoThreadSettings threadSettings; getCommonThreadSettings(&threadSettings); threadSettings.useFec_ = settings_.useFec_; threadSettings.threadParams_ = params; shared_ptr<VideoThread> videoThread(new VideoThread()); videoThread->registerCallback(this); videoThread->setLogger(logger_); if (RESULT_FAIL(videoThread->init(threadSettings))) { notifyError(-1, "couldn't add new video thread %s", threadSettings.getVideoParams()->threadName_.c_str()); return RESULT_ERR; } else threads_[videoThread->getPrefix()] = videoThread; return RESULT_OK; } void VideoStream::onDeliverFrame(WebRtcVideoFrame &frame, double timestamp) { if (isProcessing_) { if (!frame.IsZeroSize()) { for (ThreadMap::iterator i = threads_.begin(); i != threads_.end(); i++) { VideoThreadSettings set; ((VideoThread*)i->second.get())->getSettings(set); LogTraceC << "delivering frame to " << set.getVideoParams()->threadName_ << std::endl; ((VideoThread*)i->second.get())->onDeliverFrame(frame, timestamp); } } } } //****************************************************************************** AudioStream::AudioStream(): MediaStream(), audioCapturer_(new AudioCapturer()) { description_ = "audio-stream"; audioCapturer_->registerCallback(this); audioCapturer_->setFrameConsumer(this); } AudioStream::~AudioStream() { audioCapturer_->stopCapture(); } int AudioStream::init(const MediaStreamSettings& streamSettings) { if (RESULT_GOOD(MediaStream::init(streamSettings))) { audioCapturer_->setLogger(logger_); audioCapturer_->init(); audioCapturer_->startCapture(); return RESULT_OK; } return RESULT_ERR; } void AudioStream::release() { MediaStream::release(); // audioCapturer_->stopCapture(); } int AudioStream::addNewMediaThread(const MediaThreadParams* params) { AudioThreadSettings threadSettings; getCommonThreadSettings(&threadSettings); threadSettings.threadParams_ = params; shared_ptr<AudioThread> audioThread(new AudioThread()); audioThread->registerCallback(this); audioThread->setLogger(logger_); if (RESULT_FAIL(audioThread->init(threadSettings))) { notifyError(-1, "couldn't add new audio thread %s", threadSettings.threadParams_->threadName_.c_str()); return RESULT_ERR; } else threads_[audioThread->getPrefix()] = audioThread; return RESULT_OK; } // interface conformance - IAudioFrameConsumer void AudioStream::onDeliverRtpFrame(unsigned int len, unsigned char *data) { if (isProcessing_) for (ThreadMap::iterator i = threads_.begin(); i != threads_.end(); i++) ((AudioThread*)i->second.get())->onDeliverRtpFrame(len, data); } void AudioStream::onDeliverRtcpFrame(unsigned int len, unsigned char *data) { if (isProcessing_) for (ThreadMap::iterator i = threads_.begin(); i != threads_.end(); i++) ((AudioThread*)i->second.get())->onDeliverRtcpFrame(len, data); } <commit_msg>[hotfix] audio producer problem<commit_after>// // media-stream.cpp // libndnrtc // // Copyright 2013 Regents of the University of California // For licensing details see the LICENSE file. // // Author: Peter Gusev // #include "media-stream.h" #include "video-thread.h" #include "audio-thread.h" #include "ndnrtc-namespace.h" using namespace webrtc; using namespace boost; using namespace ndnrtc; using namespace ndnrtc::new_api; //****************************************************************************** MediaStream::MediaStream() { } MediaStream::~MediaStream() { } int MediaStream::init(const MediaStreamSettings& streamSettings) { settings_ = streamSettings; streamName_ = settings_.streamParams_.streamName_; streamPrefix_ = *NdnRtcNamespace::getStreamPrefix(settings_.userPrefix_, streamName_); int res = RESULT_OK; for (int i = 0; i < settings_.streamParams_.mediaThreads_.size() && RESULT_GOOD(res); i++) res = addNewMediaThread(settings_.streamParams_.mediaThreads_[i]); return res; } void MediaStream::release() { ThreadMap::iterator it = threads_.begin(); while (it != threads_.end()) { it->second->stop(); it++; } threads_.clear(); } void MediaStream::addThread(const MediaThreadParams& threadParams) { } void MediaStream::removeThread(const std::string& threadName) { } void MediaStream::removeAllThreads() { } // private void MediaStream::getCommonThreadSettings(MediaThreadSettings* settings) { settings->segmentSize_ = settings_.streamParams_.producerParams_.segmentSize_; settings->dataFreshnessMs_ = settings_.streamParams_.producerParams_.freshnessMs_; settings->streamPrefix_ = streamPrefix_; settings->certificateName_ = *NdnRtcNamespace::certificateNameForUser(settings_.userPrefix_); settings->keyChain_ = settings_.keyChain_; settings->faceProcessor_ = settings_.faceProcessor_; settings->memoryCache_ = settings_.memoryCache_; } void MediaStream::onMediaThreadRegistrationFailed(std::string threadName) { LogWarnC << "failed to register thread " << threadName << std::endl; } //****************************************************************************** VideoStream::VideoStream(): MediaStream(), capturer_(new ExternalCapturer()) { description_ = "video-stream"; capturer_->setFrameConsumer(this); } int VideoStream::init(const MediaStreamSettings& streamSettings) { if (RESULT_GOOD(MediaStream::init(streamSettings))) { capturer_->setLogger(logger_); isProcessing_ = true; return RESULT_OK; } return RESULT_ERR; } MediaStreamParams VideoStream::getStreamParameters() { MediaStreamParams params(settings_.streamParams_); // update average segments numbers for frames for (int i = 0; i < params.mediaThreads_.size(); i++) { VideoThreadParams* threadParams = ((VideoThreadParams*)params.mediaThreads_[i]); std::string threadKey = *NdnRtcNamespace::buildPath(false, &streamPrefix_, &threadParams->threadName_, 0); VideoThreadStatistics stat; shared_ptr<VideoThread> thread = dynamic_pointer_cast<VideoThread>(threads_[threadKey]); thread->getStatistics(stat); threadParams->deltaAvgSegNum_ = stat.deltaAvgSegNum_; threadParams->deltaAvgParitySegNum_ = stat.deltaAvgParitySegNum_; threadParams->keyAvgSegNum_ = stat.keyAvgSegNum_; threadParams->keyAvgParitySegNum_ = stat.keyAvgParitySegNum_; } return params; } bool VideoStream::isStreamStatReady() { bool statReady = true; for (auto it:threads_) statReady &= dynamic_pointer_cast<VideoThread>(it.second)->isThreadStatReady(); return statReady; } void VideoStream::release() { MediaStream::release(); isProcessing_ = false; } int VideoStream::addNewMediaThread(const MediaThreadParams* params) { VideoThreadSettings threadSettings; getCommonThreadSettings(&threadSettings); threadSettings.useFec_ = settings_.useFec_; threadSettings.threadParams_ = params; shared_ptr<VideoThread> videoThread(new VideoThread()); videoThread->registerCallback(this); videoThread->setLogger(logger_); if (RESULT_FAIL(videoThread->init(threadSettings))) { notifyError(-1, "couldn't add new video thread %s", threadSettings.getVideoParams()->threadName_.c_str()); return RESULT_ERR; } else threads_[videoThread->getPrefix()] = videoThread; return RESULT_OK; } void VideoStream::onDeliverFrame(WebRtcVideoFrame &frame, double timestamp) { if (isProcessing_) { if (!frame.IsZeroSize()) { for (ThreadMap::iterator i = threads_.begin(); i != threads_.end(); i++) { VideoThreadSettings set; ((VideoThread*)i->second.get())->getSettings(set); LogTraceC << "delivering frame to " << set.getVideoParams()->threadName_ << std::endl; ((VideoThread*)i->second.get())->onDeliverFrame(frame, timestamp); } } } } //****************************************************************************** AudioStream::AudioStream(): MediaStream(), audioCapturer_(new AudioCapturer()) { description_ = "audio-stream"; audioCapturer_->registerCallback(this); audioCapturer_->setFrameConsumer(this); } AudioStream::~AudioStream() { audioCapturer_->stopCapture(); } int AudioStream::init(const MediaStreamSettings& streamSettings) { if (RESULT_GOOD(MediaStream::init(streamSettings))) { isProcessing_ = true; audioCapturer_->setLogger(logger_); audioCapturer_->init(); audioCapturer_->startCapture(); return RESULT_OK; } return RESULT_ERR; } void AudioStream::release() { MediaStream::release(); // audioCapturer_->stopCapture(); isProcessing_ = false; } int AudioStream::addNewMediaThread(const MediaThreadParams* params) { AudioThreadSettings threadSettings; getCommonThreadSettings(&threadSettings); threadSettings.threadParams_ = params; shared_ptr<AudioThread> audioThread(new AudioThread()); audioThread->registerCallback(this); audioThread->setLogger(logger_); if (RESULT_FAIL(audioThread->init(threadSettings))) { notifyError(-1, "couldn't add new audio thread %s", threadSettings.threadParams_->threadName_.c_str()); return RESULT_ERR; } else threads_[audioThread->getPrefix()] = audioThread; return RESULT_OK; } // interface conformance - IAudioFrameConsumer void AudioStream::onDeliverRtpFrame(unsigned int len, unsigned char *data) { if (isProcessing_) for (ThreadMap::iterator i = threads_.begin(); i != threads_.end(); i++) ((AudioThread*)i->second.get())->onDeliverRtpFrame(len, data); } void AudioStream::onDeliverRtcpFrame(unsigned int len, unsigned char *data) { if (isProcessing_) for (ThreadMap::iterator i = threads_.begin(); i != threads_.end(); i++) ((AudioThread*)i->second.get())->onDeliverRtcpFrame(len, data); } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "kitinformation.h" #include "devicesupport/desktopdevice.h" #include "devicesupport/devicemanager.h" #include "projectexplorerconstants.h" #include "kit.h" #include "kitinformationconfigwidget.h" #include "toolchain.h" #include "toolchainmanager.h" #include <extensionsystem/pluginmanager.h> #include <projectexplorer/abi.h> #include <utils/pathchooser.h> #include <utils/qtcassert.h> #include <QComboBox> #include <QHBoxLayout> #include <QLabel> #include <QPushButton> #include <QFileInfo> namespace ProjectExplorer { // -------------------------------------------------------------------------- // SysRootInformation: // -------------------------------------------------------------------------- static const char SYSROOT_INFORMATION[] = "PE.Profile.SysRoot"; SysRootKitInformation::SysRootKitInformation() { setObjectName(QLatin1String("SysRootInformation")); } Core::Id SysRootKitInformation::dataId() const { static const Core::Id id(SYSROOT_INFORMATION); return id; } unsigned int SysRootKitInformation::priority() const { return 31000; } QVariant SysRootKitInformation::defaultValue(Kit *k) const { Q_UNUSED(k) return QString(); } QList<Task> SysRootKitInformation::validate(const Kit *k) const { QList<Task> result; const Utils::FileName dir = SysRootKitInformation::sysRoot(k); if (!dir.toFileInfo().isDir() && SysRootKitInformation::hasSysRoot(k)) { result << Task(Task::Error, tr("Sys Root \"%1\" is not a directory.").arg(dir.toUserOutput()), Utils::FileName(), -1, Core::Id(Constants::TASK_CATEGORY_BUILDSYSTEM)); } return result; } KitConfigWidget *SysRootKitInformation::createConfigWidget(Kit *k) const { return new Internal::SysRootInformationConfigWidget(k); } KitInformation::ItemList SysRootKitInformation::toUserOutput(const Kit *k) const { return ItemList() << qMakePair(tr("Sys Root"), sysRoot(k).toUserOutput()); } bool SysRootKitInformation::hasSysRoot(const Kit *k) { if (k) return !k->value(Core::Id(SYSROOT_INFORMATION)).toString().isEmpty(); return false; } Utils::FileName SysRootKitInformation::sysRoot(const Kit *k) { if (!k) return Utils::FileName(); return Utils::FileName::fromString(k->value(Core::Id(SYSROOT_INFORMATION)).toString()); } void SysRootKitInformation::setSysRoot(Kit *k, const Utils::FileName &v) { k->setValue(Core::Id(SYSROOT_INFORMATION), v.toString()); } // -------------------------------------------------------------------------- // ToolChainInformation: // -------------------------------------------------------------------------- static const char TOOLCHAIN_INFORMATION[] = "PE.Profile.ToolChain"; ToolChainKitInformation::ToolChainKitInformation() { setObjectName(QLatin1String("ToolChainInformation")); connect(KitManager::instance(), SIGNAL(kitsLoaded()), this, SLOT(kitsWereLoaded())); } Core::Id ToolChainKitInformation::dataId() const { static const Core::Id id(TOOLCHAIN_INFORMATION); return id; } unsigned int ToolChainKitInformation::priority() const { return 30000; } QVariant ToolChainKitInformation::defaultValue(Kit *k) const { Q_UNUSED(k); QList<ToolChain *> tcList = ToolChainManager::instance()->toolChains(); if (tcList.isEmpty()) return QString(); ProjectExplorer::Abi abi = ProjectExplorer::Abi::hostAbi(); foreach (ToolChain *tc, tcList) { if (tc->targetAbi() == abi) return tc->id(); } return tcList.at(0)->id(); } QList<Task> ToolChainKitInformation::validate(const Kit *k) const { QList<Task> result; if (!toolChain(k)) { result << Task(Task::Error, ToolChainKitInformation::msgNoToolChainInTarget(), Utils::FileName(), -1, Core::Id(Constants::TASK_CATEGORY_BUILDSYSTEM)); } return result; } void ToolChainKitInformation::fix(Kit *k) { QTC_ASSERT(ToolChainManager::instance()->isLoaded(), return); if (toolChain(k)) return; qWarning("Tool chain is no longer known, removing from kit \"%s\".", qPrintable(k->displayName())); setToolChain(k, 0); // make sure to clear out no longer known tool chains } void ToolChainKitInformation::setup(Kit *k) { QTC_ASSERT(ToolChainManager::instance()->isLoaded(), return); const QString id = k->value(Core::Id(TOOLCHAIN_INFORMATION)).toString(); if (id.isEmpty()) return; ToolChain *tc = ToolChainManager::instance()->findToolChain(id); if (tc) return; // ID is not found: Might be an ABI string... foreach (ToolChain *current, ToolChainManager::instance()->toolChains()) { if (current->targetAbi().toString() == id) return setToolChain(k, current); } } KitConfigWidget *ToolChainKitInformation::createConfigWidget(Kit *k) const { return new Internal::ToolChainInformationConfigWidget(k); } QString ToolChainKitInformation::displayNamePostfix(const Kit *k) const { ToolChain *tc = toolChain(k); return tc ? tc->displayName() : QString(); } KitInformation::ItemList ToolChainKitInformation::toUserOutput(const Kit *k) const { ToolChain *tc = toolChain(k); return ItemList() << qMakePair(tr("Compiler"), tc ? tc->displayName() : tr("None")); } void ToolChainKitInformation::addToEnvironment(const Kit *k, Utils::Environment &env) const { ToolChain *tc = toolChain(k); if (tc) tc->addToEnvironment(env); } IOutputParser *ToolChainKitInformation::createOutputParser(const Kit *k) const { ToolChain *tc = toolChain(k); if (tc) return tc->outputParser(); return 0; } ToolChain *ToolChainKitInformation::toolChain(const Kit *k) { QTC_ASSERT(ToolChainManager::instance()->isLoaded(), return 0); if (!k) return 0; return ToolChainManager::instance() ->findToolChain(k->value(Core::Id(TOOLCHAIN_INFORMATION)).toString()); } void ToolChainKitInformation::setToolChain(Kit *k, ToolChain *tc) { k->setValue(Core::Id(TOOLCHAIN_INFORMATION), tc ? tc->id() : QString()); } QString ToolChainKitInformation::msgNoToolChainInTarget() { return tr("No compiler set in kit."); } void ToolChainKitInformation::kitsWereLoaded() { foreach (Kit *k, KitManager::instance()->kits()) fix(k); connect(ToolChainManager::instance(), SIGNAL(toolChainRemoved(ProjectExplorer::ToolChain*)), this, SLOT(toolChainRemoved(ProjectExplorer::ToolChain*))); connect(ToolChainManager::instance(), SIGNAL(toolChainUpdated(ProjectExplorer::ToolChain*)), this, SLOT(toolChainUpdated(ProjectExplorer::ToolChain*))); } void ToolChainKitInformation::toolChainUpdated(ProjectExplorer::ToolChain *tc) { ToolChainMatcher m(tc); foreach (Kit *k, KitManager::instance()->kits(&m)) notifyAboutUpdate(k); } void ToolChainKitInformation::toolChainRemoved(ProjectExplorer::ToolChain *tc) { Q_UNUSED(tc); foreach (Kit *k, KitManager::instance()->kits()) fix(k); } // -------------------------------------------------------------------------- // DeviceTypeInformation: // -------------------------------------------------------------------------- static const char DEVICETYPE_INFORMATION[] = "PE.Profile.DeviceType"; DeviceTypeKitInformation::DeviceTypeKitInformation() { setObjectName(QLatin1String("DeviceTypeInformation")); } Core::Id DeviceTypeKitInformation::dataId() const { static const Core::Id id(DEVICETYPE_INFORMATION); return id; } unsigned int DeviceTypeKitInformation::priority() const { return 33000; } QVariant DeviceTypeKitInformation::defaultValue(Kit *k) const { Q_UNUSED(k); return QByteArray(Constants::DESKTOP_DEVICE_TYPE); } QList<Task> DeviceTypeKitInformation::validate(const Kit *k) const { Q_UNUSED(k); return QList<Task>(); } KitConfigWidget *DeviceTypeKitInformation::createConfigWidget(Kit *k) const { return new Internal::DeviceTypeInformationConfigWidget(k); } KitInformation::ItemList DeviceTypeKitInformation::toUserOutput(const Kit *k) const { Core::Id type = deviceTypeId(k); QString typeDisplayName = tr("Unknown device type"); if (type.isValid()) { QList<IDeviceFactory *> factories = ExtensionSystem::PluginManager::instance()->getObjects<IDeviceFactory>(); foreach (IDeviceFactory *factory, factories) { if (factory->availableCreationIds().contains(type)) { typeDisplayName = factory->displayNameForId(type); break; } } } return ItemList() << qMakePair(tr("Device type"), typeDisplayName); } const Core::Id DeviceTypeKitInformation::deviceTypeId(const Kit *k) { // FIXME: This should be fromSetting/toSetting instead. if (!k) return Core::Id(); QByteArray value = k->value(DEVICETYPE_INFORMATION).toByteArray(); if (value.isEmpty()) return Core::Id(); return Core::Id::fromName(value); } void DeviceTypeKitInformation::setDeviceTypeId(Kit *k, Core::Id type) { k->setValue(DEVICETYPE_INFORMATION, type.name()); } // -------------------------------------------------------------------------- // DeviceInformation: // -------------------------------------------------------------------------- static const char DEVICE_INFORMATION[] = "PE.Profile.Device"; DeviceKitInformation::DeviceKitInformation() { setObjectName(QLatin1String("DeviceInformation")); connect(KitManager::instance(), SIGNAL(kitsLoaded()), this, SLOT(kitsWereLoaded())); } Core::Id DeviceKitInformation::dataId() const { static const Core::Id id(DEVICE_INFORMATION); return id; } unsigned int DeviceKitInformation::priority() const { return 32000; } QVariant DeviceKitInformation::defaultValue(Kit *k) const { Core::Id type = DeviceTypeKitInformation::deviceTypeId(k); IDevice::ConstPtr dev = DeviceManager::instance()->defaultDevice(type); return dev.isNull() ? QString() : dev->id().toString(); } QList<Task> DeviceKitInformation::validate(const Kit *k) const { IDevice::ConstPtr dev = DeviceKitInformation::device(k); QList<Task> result; if (!dev.isNull() && dev->type() != DeviceTypeKitInformation::deviceTypeId(k)) result.append(Task(Task::Error, tr("Device does not match device type."), Utils::FileName(), -1, Core::Id(Constants::TASK_CATEGORY_BUILDSYSTEM))); if (dev.isNull()) result.append(Task(Task::Warning, tr("No device set."), Utils::FileName(), -1, Core::Id(Constants::TASK_CATEGORY_BUILDSYSTEM))); return result; } void DeviceKitInformation::fix(Kit *k) { IDevice::ConstPtr dev = DeviceKitInformation::device(k); if (!dev.isNull() && dev->type() == DeviceTypeKitInformation::deviceTypeId(k)) return; qWarning("Device is no longer known, removing from kit \"%s\".", qPrintable(k->displayName())); setDeviceId(k, Core::Id()); } void DeviceKitInformation::setup(Kit *k) { QTC_ASSERT(DeviceManager::instance()->isLoaded(), return); IDevice::ConstPtr dev = DeviceKitInformation::device(k); if (!dev.isNull() && dev->type() == DeviceTypeKitInformation::deviceTypeId(k)) return; setDeviceId(k, Core::Id::fromSetting(defaultValue(k))); } KitConfigWidget *DeviceKitInformation::createConfigWidget(Kit *k) const { return new Internal::DeviceInformationConfigWidget(k); } QString DeviceKitInformation::displayNamePostfix(const Kit *k) const { IDevice::ConstPtr dev = device(k); return dev.isNull() ? QString() : dev->displayName(); } KitInformation::ItemList DeviceKitInformation::toUserOutput(const Kit *k) const { IDevice::ConstPtr dev = device(k); return ItemList() << qMakePair(tr("Device"), dev.isNull() ? tr("Unconfigured") : dev->displayName()); } IDevice::ConstPtr DeviceKitInformation::device(const Kit *k) { QTC_ASSERT(DeviceManager::instance()->isLoaded(), return IDevice::ConstPtr()); return DeviceManager::instance()->find(deviceId(k)); } Core::Id DeviceKitInformation::deviceId(const Kit *k) { return k ? Core::Id::fromSetting(k->value(DEVICE_INFORMATION)) : Core::Id(); } void DeviceKitInformation::setDevice(Kit *k, IDevice::ConstPtr dev) { setDeviceId(k, dev ? dev->id() : Core::Id()); } void DeviceKitInformation::setDeviceId(Kit *k, const Core::Id id) { k->setValue(DEVICE_INFORMATION, id.toSetting()); } void DeviceKitInformation::kitsWereLoaded() { foreach (Kit *k, KitManager::instance()->kits()) fix(k); connect(DeviceManager::instance(), SIGNAL(deviceAdded(Core::Id)), this, SLOT(deviceAdded(Core::Id))); connect(DeviceManager::instance(), SIGNAL(deviceRemoved(Core::Id)), this, SLOT(deviceRemoved(Core::Id))); connect(DeviceManager::instance(), SIGNAL(deviceUpdated(Core::Id)), this, SLOT(deviceUpdated(Core::Id))); connect(KitManager::instance(), SIGNAL(kitUpdated(ProjectExplorer::Kit*)), this, SLOT(kitUpdated(ProjectExplorer::Kit*))); connect(KitManager::instance(), SIGNAL(unmanagedKitUpdated(ProjectExplorer::Kit*)), this, SLOT(kitUpdated(ProjectExplorer::Kit*))); } void DeviceKitInformation::deviceUpdated(const Core::Id &id) { foreach (Kit *k, KitManager::instance()->kits()) { if (deviceId(k) == id) notifyAboutUpdate(k); } } void DeviceKitInformation::kitUpdated(Kit *k) { setup(k); // Set default device if necessary } void DeviceKitInformation::deviceAdded(const Core::Id &id) { Q_UNUSED(id); DeviceMatcher m; foreach (Kit *k, KitManager::instance()->kits(&m)) { setup(k); // Set default device if necessary } } void DeviceKitInformation::deviceRemoved(const Core::Id &id) { DeviceMatcher m(id); foreach (Kit *k, KitManager::instance()->kits(&m)) setup(k); // Set default device if necessary } } // namespace ProjectExplorer <commit_msg>Kits: use Id::{from,to}Settings when appropriate<commit_after>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "kitinformation.h" #include "devicesupport/desktopdevice.h" #include "devicesupport/devicemanager.h" #include "projectexplorerconstants.h" #include "kit.h" #include "kitinformationconfigwidget.h" #include "toolchain.h" #include "toolchainmanager.h" #include <extensionsystem/pluginmanager.h> #include <projectexplorer/abi.h> #include <utils/pathchooser.h> #include <utils/qtcassert.h> #include <QComboBox> #include <QHBoxLayout> #include <QLabel> #include <QPushButton> #include <QFileInfo> namespace ProjectExplorer { // -------------------------------------------------------------------------- // SysRootInformation: // -------------------------------------------------------------------------- static const char SYSROOT_INFORMATION[] = "PE.Profile.SysRoot"; SysRootKitInformation::SysRootKitInformation() { setObjectName(QLatin1String("SysRootInformation")); } Core::Id SysRootKitInformation::dataId() const { static const Core::Id id(SYSROOT_INFORMATION); return id; } unsigned int SysRootKitInformation::priority() const { return 31000; } QVariant SysRootKitInformation::defaultValue(Kit *k) const { Q_UNUSED(k) return QString(); } QList<Task> SysRootKitInformation::validate(const Kit *k) const { QList<Task> result; const Utils::FileName dir = SysRootKitInformation::sysRoot(k); if (!dir.toFileInfo().isDir() && SysRootKitInformation::hasSysRoot(k)) { result << Task(Task::Error, tr("Sys Root \"%1\" is not a directory.").arg(dir.toUserOutput()), Utils::FileName(), -1, Core::Id(Constants::TASK_CATEGORY_BUILDSYSTEM)); } return result; } KitConfigWidget *SysRootKitInformation::createConfigWidget(Kit *k) const { return new Internal::SysRootInformationConfigWidget(k); } KitInformation::ItemList SysRootKitInformation::toUserOutput(const Kit *k) const { return ItemList() << qMakePair(tr("Sys Root"), sysRoot(k).toUserOutput()); } bool SysRootKitInformation::hasSysRoot(const Kit *k) { if (k) return !k->value(Core::Id(SYSROOT_INFORMATION)).toString().isEmpty(); return false; } Utils::FileName SysRootKitInformation::sysRoot(const Kit *k) { if (!k) return Utils::FileName(); return Utils::FileName::fromString(k->value(Core::Id(SYSROOT_INFORMATION)).toString()); } void SysRootKitInformation::setSysRoot(Kit *k, const Utils::FileName &v) { k->setValue(Core::Id(SYSROOT_INFORMATION), v.toString()); } // -------------------------------------------------------------------------- // ToolChainInformation: // -------------------------------------------------------------------------- static const char TOOLCHAIN_INFORMATION[] = "PE.Profile.ToolChain"; ToolChainKitInformation::ToolChainKitInformation() { setObjectName(QLatin1String("ToolChainInformation")); connect(KitManager::instance(), SIGNAL(kitsLoaded()), this, SLOT(kitsWereLoaded())); } Core::Id ToolChainKitInformation::dataId() const { static const Core::Id id(TOOLCHAIN_INFORMATION); return id; } unsigned int ToolChainKitInformation::priority() const { return 30000; } QVariant ToolChainKitInformation::defaultValue(Kit *k) const { Q_UNUSED(k); QList<ToolChain *> tcList = ToolChainManager::instance()->toolChains(); if (tcList.isEmpty()) return QString(); ProjectExplorer::Abi abi = ProjectExplorer::Abi::hostAbi(); foreach (ToolChain *tc, tcList) { if (tc->targetAbi() == abi) return tc->id(); } return tcList.at(0)->id(); } QList<Task> ToolChainKitInformation::validate(const Kit *k) const { QList<Task> result; if (!toolChain(k)) { result << Task(Task::Error, ToolChainKitInformation::msgNoToolChainInTarget(), Utils::FileName(), -1, Core::Id(Constants::TASK_CATEGORY_BUILDSYSTEM)); } return result; } void ToolChainKitInformation::fix(Kit *k) { QTC_ASSERT(ToolChainManager::instance()->isLoaded(), return); if (toolChain(k)) return; qWarning("Tool chain is no longer known, removing from kit \"%s\".", qPrintable(k->displayName())); setToolChain(k, 0); // make sure to clear out no longer known tool chains } void ToolChainKitInformation::setup(Kit *k) { QTC_ASSERT(ToolChainManager::instance()->isLoaded(), return); const QString id = k->value(Core::Id(TOOLCHAIN_INFORMATION)).toString(); if (id.isEmpty()) return; ToolChain *tc = ToolChainManager::instance()->findToolChain(id); if (tc) return; // ID is not found: Might be an ABI string... foreach (ToolChain *current, ToolChainManager::instance()->toolChains()) { if (current->targetAbi().toString() == id) return setToolChain(k, current); } } KitConfigWidget *ToolChainKitInformation::createConfigWidget(Kit *k) const { return new Internal::ToolChainInformationConfigWidget(k); } QString ToolChainKitInformation::displayNamePostfix(const Kit *k) const { ToolChain *tc = toolChain(k); return tc ? tc->displayName() : QString(); } KitInformation::ItemList ToolChainKitInformation::toUserOutput(const Kit *k) const { ToolChain *tc = toolChain(k); return ItemList() << qMakePair(tr("Compiler"), tc ? tc->displayName() : tr("None")); } void ToolChainKitInformation::addToEnvironment(const Kit *k, Utils::Environment &env) const { ToolChain *tc = toolChain(k); if (tc) tc->addToEnvironment(env); } IOutputParser *ToolChainKitInformation::createOutputParser(const Kit *k) const { ToolChain *tc = toolChain(k); if (tc) return tc->outputParser(); return 0; } ToolChain *ToolChainKitInformation::toolChain(const Kit *k) { QTC_ASSERT(ToolChainManager::instance()->isLoaded(), return 0); if (!k) return 0; return ToolChainManager::instance() ->findToolChain(k->value(Core::Id(TOOLCHAIN_INFORMATION)).toString()); } void ToolChainKitInformation::setToolChain(Kit *k, ToolChain *tc) { k->setValue(Core::Id(TOOLCHAIN_INFORMATION), tc ? tc->id() : QString()); } QString ToolChainKitInformation::msgNoToolChainInTarget() { return tr("No compiler set in kit."); } void ToolChainKitInformation::kitsWereLoaded() { foreach (Kit *k, KitManager::instance()->kits()) fix(k); connect(ToolChainManager::instance(), SIGNAL(toolChainRemoved(ProjectExplorer::ToolChain*)), this, SLOT(toolChainRemoved(ProjectExplorer::ToolChain*))); connect(ToolChainManager::instance(), SIGNAL(toolChainUpdated(ProjectExplorer::ToolChain*)), this, SLOT(toolChainUpdated(ProjectExplorer::ToolChain*))); } void ToolChainKitInformation::toolChainUpdated(ProjectExplorer::ToolChain *tc) { ToolChainMatcher m(tc); foreach (Kit *k, KitManager::instance()->kits(&m)) notifyAboutUpdate(k); } void ToolChainKitInformation::toolChainRemoved(ProjectExplorer::ToolChain *tc) { Q_UNUSED(tc); foreach (Kit *k, KitManager::instance()->kits()) fix(k); } // -------------------------------------------------------------------------- // DeviceTypeInformation: // -------------------------------------------------------------------------- static const char DEVICETYPE_INFORMATION[] = "PE.Profile.DeviceType"; DeviceTypeKitInformation::DeviceTypeKitInformation() { setObjectName(QLatin1String("DeviceTypeInformation")); } Core::Id DeviceTypeKitInformation::dataId() const { static const Core::Id id(DEVICETYPE_INFORMATION); return id; } unsigned int DeviceTypeKitInformation::priority() const { return 33000; } QVariant DeviceTypeKitInformation::defaultValue(Kit *k) const { Q_UNUSED(k); return QByteArray(Constants::DESKTOP_DEVICE_TYPE); } QList<Task> DeviceTypeKitInformation::validate(const Kit *k) const { Q_UNUSED(k); return QList<Task>(); } KitConfigWidget *DeviceTypeKitInformation::createConfigWidget(Kit *k) const { return new Internal::DeviceTypeInformationConfigWidget(k); } KitInformation::ItemList DeviceTypeKitInformation::toUserOutput(const Kit *k) const { Core::Id type = deviceTypeId(k); QString typeDisplayName = tr("Unknown device type"); if (type.isValid()) { QList<IDeviceFactory *> factories = ExtensionSystem::PluginManager::instance()->getObjects<IDeviceFactory>(); foreach (IDeviceFactory *factory, factories) { if (factory->availableCreationIds().contains(type)) { typeDisplayName = factory->displayNameForId(type); break; } } } return ItemList() << qMakePair(tr("Device type"), typeDisplayName); } const Core::Id DeviceTypeKitInformation::deviceTypeId(const Kit *k) { return k ? Core::Id::fromSetting(k->value(DEVICETYPE_INFORMATION)) : Core::Id(); } void DeviceTypeKitInformation::setDeviceTypeId(Kit *k, Core::Id type) { k->setValue(DEVICETYPE_INFORMATION, type.toSetting()); } // -------------------------------------------------------------------------- // DeviceInformation: // -------------------------------------------------------------------------- static const char DEVICE_INFORMATION[] = "PE.Profile.Device"; DeviceKitInformation::DeviceKitInformation() { setObjectName(QLatin1String("DeviceInformation")); connect(KitManager::instance(), SIGNAL(kitsLoaded()), this, SLOT(kitsWereLoaded())); } Core::Id DeviceKitInformation::dataId() const { static const Core::Id id(DEVICE_INFORMATION); return id; } unsigned int DeviceKitInformation::priority() const { return 32000; } QVariant DeviceKitInformation::defaultValue(Kit *k) const { Core::Id type = DeviceTypeKitInformation::deviceTypeId(k); IDevice::ConstPtr dev = DeviceManager::instance()->defaultDevice(type); return dev.isNull() ? QString() : dev->id().toString(); } QList<Task> DeviceKitInformation::validate(const Kit *k) const { IDevice::ConstPtr dev = DeviceKitInformation::device(k); QList<Task> result; if (!dev.isNull() && dev->type() != DeviceTypeKitInformation::deviceTypeId(k)) result.append(Task(Task::Error, tr("Device does not match device type."), Utils::FileName(), -1, Core::Id(Constants::TASK_CATEGORY_BUILDSYSTEM))); if (dev.isNull()) result.append(Task(Task::Warning, tr("No device set."), Utils::FileName(), -1, Core::Id(Constants::TASK_CATEGORY_BUILDSYSTEM))); return result; } void DeviceKitInformation::fix(Kit *k) { IDevice::ConstPtr dev = DeviceKitInformation::device(k); if (!dev.isNull() && dev->type() == DeviceTypeKitInformation::deviceTypeId(k)) return; qWarning("Device is no longer known, removing from kit \"%s\".", qPrintable(k->displayName())); setDeviceId(k, Core::Id()); } void DeviceKitInformation::setup(Kit *k) { QTC_ASSERT(DeviceManager::instance()->isLoaded(), return); IDevice::ConstPtr dev = DeviceKitInformation::device(k); if (!dev.isNull() && dev->type() == DeviceTypeKitInformation::deviceTypeId(k)) return; setDeviceId(k, Core::Id::fromSetting(defaultValue(k))); } KitConfigWidget *DeviceKitInformation::createConfigWidget(Kit *k) const { return new Internal::DeviceInformationConfigWidget(k); } QString DeviceKitInformation::displayNamePostfix(const Kit *k) const { IDevice::ConstPtr dev = device(k); return dev.isNull() ? QString() : dev->displayName(); } KitInformation::ItemList DeviceKitInformation::toUserOutput(const Kit *k) const { IDevice::ConstPtr dev = device(k); return ItemList() << qMakePair(tr("Device"), dev.isNull() ? tr("Unconfigured") : dev->displayName()); } IDevice::ConstPtr DeviceKitInformation::device(const Kit *k) { QTC_ASSERT(DeviceManager::instance()->isLoaded(), return IDevice::ConstPtr()); return DeviceManager::instance()->find(deviceId(k)); } Core::Id DeviceKitInformation::deviceId(const Kit *k) { return k ? Core::Id::fromSetting(k->value(DEVICE_INFORMATION)) : Core::Id(); } void DeviceKitInformation::setDevice(Kit *k, IDevice::ConstPtr dev) { setDeviceId(k, dev ? dev->id() : Core::Id()); } void DeviceKitInformation::setDeviceId(Kit *k, const Core::Id id) { k->setValue(DEVICE_INFORMATION, id.toSetting()); } void DeviceKitInformation::kitsWereLoaded() { foreach (Kit *k, KitManager::instance()->kits()) fix(k); connect(DeviceManager::instance(), SIGNAL(deviceAdded(Core::Id)), this, SLOT(deviceAdded(Core::Id))); connect(DeviceManager::instance(), SIGNAL(deviceRemoved(Core::Id)), this, SLOT(deviceRemoved(Core::Id))); connect(DeviceManager::instance(), SIGNAL(deviceUpdated(Core::Id)), this, SLOT(deviceUpdated(Core::Id))); connect(KitManager::instance(), SIGNAL(kitUpdated(ProjectExplorer::Kit*)), this, SLOT(kitUpdated(ProjectExplorer::Kit*))); connect(KitManager::instance(), SIGNAL(unmanagedKitUpdated(ProjectExplorer::Kit*)), this, SLOT(kitUpdated(ProjectExplorer::Kit*))); } void DeviceKitInformation::deviceUpdated(const Core::Id &id) { foreach (Kit *k, KitManager::instance()->kits()) { if (deviceId(k) == id) notifyAboutUpdate(k); } } void DeviceKitInformation::kitUpdated(Kit *k) { setup(k); // Set default device if necessary } void DeviceKitInformation::deviceAdded(const Core::Id &id) { Q_UNUSED(id); DeviceMatcher m; foreach (Kit *k, KitManager::instance()->kits(&m)) { setup(k); // Set default device if necessary } } void DeviceKitInformation::deviceRemoved(const Core::Id &id) { DeviceMatcher m(id); foreach (Kit *k, KitManager::instance()->kits(&m)) setup(k); // Set default device if necessary } } // namespace ProjectExplorer <|endoftext|>
<commit_before>#include <assert.h> #include <cppdom/cppdom.h> #include <testHelpers.h> /** * Test application to test creating a document from scratch */ int main() { // Create the basic context and document to work on // - All nodes need to have an associated context // we will just define one here at the beginning and use it // the entire way through cppdom::ContextPtr ctx( new cppdom::Context ); cppdom::Document doc("Document Root", ctx ); // What it should look like // - Root // - Element1: attrib1:1, attrib2:two // cdata: This is element1 // - Element2: // - Element3: attrib1:attrib1 cppdom::NodePtr element1(new cppdom::Node("Element1", ctx)); cppdom::NodePtr element2(new cppdom::Node("Element2", ctx)); cppdom::NodePtr element3(new cppdom::Node("Element3", ctx)); cppdom::NodePtr element1_cdata(new cppdom::Node("Element1-cdata", ctx)); // Now add element 1 // - Also set it's attributes doc.addChild(element1); element1->setAttribute("attrib1", 1); element1->setAttribute("attrib2", "two"); //element1->addChild(element1_cdata); // Cdata must have it's type set // then set the actual contents of the cdata element1_cdata->setType(cppdom::xml_nt_cdata); element1_cdata->setCdata("This is element1"); // Add a couple of nested nodes and set the attributes doc.addChild(element2); element2->addChild(element3); element3->setAttribute("attrib1", "attrib1"); // Dump the tree to the screen testHelpers::dump_node(doc); // Write the document out to a file doc.save(std::cout); std::string filename = "maketree.xml"; doc.saveFile(filename); } <commit_msg>Fix bugs in test application.<commit_after>#include <assert.h> #include <cppdom/cppdom.h> #include <testHelpers.h> /** * Test application to test creating a document from scratch */ int main() { // Create the basic context and document to work on // - All nodes need to have an associated context // we will just define one here at the beginning and use it // the entire way through cppdom::ContextPtr ctx( new cppdom::Context ); cppdom::Document doc("Document", ctx ); // What it should look like // - Root // - Element1: attrib1:1, attrib2:two // cdata: This is element1 // - Element2: // - Element3: attrib1:attrib1 cppdom::NodePtr root(new cppdom::Node("root", ctx)); cppdom::NodePtr element1(new cppdom::Node("Element1", ctx)); cppdom::NodePtr element2(new cppdom::Node("Element2", ctx)); cppdom::NodePtr element3(new cppdom::Node("Element3", ctx)); cppdom::NodePtr element1_cdata(new cppdom::Node("Element1-cdata", ctx)); // Document can only have one element as child (to be valid xml) // Set this to the root element doc.addChild(root); // Now add element 1 // - Also set it's attributes root->addChild(element1); element1->setAttribute("attrib1", 1); element1->setAttribute("attrib2", "two"); element1->addChild(element1_cdata); // Cdata must have it's type set // then set the actual contents of the cdata element1_cdata->setType(cppdom::xml_nt_cdata); element1_cdata->setCdata("This is element1"); // Add a couple of nested nodes and set the attributes root->addChild(element2); element2->addChild(element3); element3->setAttribute("attrib1", "attrib1"); // Dump the tree to the screen testHelpers::dump_node(doc); // Write the document out to a file doc.save(std::cout); std::string filename("maketree.xml"); doc.saveFile(filename); } <|endoftext|>
<commit_before>// // This file is part of the Marble Desktop Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2008-2009 Patrick Spendrin <ps_ml@gmx.de> // #include "GeoRendererView.h" // Marble #include "GeoDataContainer.h" #include "GeoDataCoordinates.h" #include "GeoDataDocument.h" #include "GeoDataFeature.h" #include "GeoDataFolder.h" #include "GeoDataLineStyle.h" #include "GeoDataObject.h" #include "GeoDataPlacemark.h" #include "GeoDataPolygon.h" #include "GeoDataPolyStyle.h" #include "GeoDataStyle.h" #include "GeoDataStyleMap.h" #include "GeoPainter.h" // Qt #include <QtCore/QDebug> #include <QtGui/QPaintEvent> using namespace Marble; GeoRendererView::GeoRendererView( QWidget * parent ) : QAbstractItemView( parent ) { } void GeoRendererView::setGeoPainter( GeoPainter* painter ) { m_painter = painter; /* the paintEvent function has to called by hand as the view is not * connected to a widget (where you normally would get the event from) */ if( model() ) paintEvent( 0 ); } QRect GeoRendererView::visualRect( const QModelIndex &index ) const { Q_UNUSED( index ) return QRect(); } void GeoRendererView::scrollTo( const QModelIndex &index, ScrollHint hint ) { Q_UNUSED( index ) Q_UNUSED( hint ) } QModelIndex GeoRendererView::indexAt( const QPoint &point ) const { Q_UNUSED( point ) return QModelIndex(); } QModelIndex GeoRendererView::moveCursor( QAbstractItemView::CursorAction cursorAction, Qt::KeyboardModifiers modifiers ) { Q_UNUSED( cursorAction ) Q_UNUSED( modifiers ) return QModelIndex(); } bool GeoRendererView::isIndexHidden( const QModelIndex &index ) const { Q_UNUSED( index ) return false; } void GeoRendererView::setSelection( const QRect&, QItemSelectionModel::SelectionFlags command ) { Q_UNUSED( command ) } void GeoRendererView::paintEvent( QPaintEvent *event ) { Q_UNUSED( event ) QModelIndex index = rootIndex(); renderIndex( index ); } void GeoRendererView::renderIndex( QModelIndex &index ) { /* * "render" a specific index - this means going through all children and if * one can be rendered (if it is a Geometry object which is not a container) * then call the real render function. For the rest iterate through the * children and recurse. */ GeoDataObject* indexObject = model()->data( rootIndex(), Qt::UserRole + 11 ).value<Marble::GeoDataObject*>(); if( !( dynamic_cast<GeoDataFeature*>( indexObject ) && dynamic_cast<GeoDataFeature*>( indexObject )->isVisible() ) ) return; int rowCount = model()->rowCount( index ); for ( int row = 0; row < rowCount; ++row ) { QModelIndex childIndex = model()->index( row, 0, index ); QString output = model()->data( childIndex ).toString(); GeoDataObject* object = model()->data( childIndex, Qt::UserRole + 11 ).value<Marble::GeoDataObject*>(); if( dynamic_cast<GeoDataGeometry*>( object ) ) { if( static_cast<GeoDataGeometry*>( object )->geometryId() != GeoDataMultiGeometryId ) { renderGeoDataGeometry( reinterpret_cast<GeoDataGeometry*>( object ), styleUrl ); } else { if( childIndex.isValid() && model()->rowCount( childIndex ) > 0 ) { renderIndex( childIndex ); } } } else if( dynamic_cast<GeoDataFeature*>( object ) ) { if( dynamic_cast<GeoDataFeature*>( object )->featureId() == GeoDataPlacemarkId ) { GeoDataPlacemark placemark( *static_cast<GeoDataFeature*>( object ) ); styleUrl = placemark.styleUrl(); } if( childIndex.isValid() && model()->rowCount( childIndex ) > 0 ) { renderIndex( childIndex ); } } } } QRegion GeoRendererView::visualRegionForSelection( const QItemSelection &selection ) const { Q_UNUSED( selection ) return QRegion(); } void GeoRendererView::setBrushStyle( QString mapped ) { /* this part has to be reworked: * Currently the style has to be accessible from the root object of the * model. This might not be wanted. On the other hand - is a copy of the * style within every Placemark wanted and how should this be called here? */ if( m_currentBrush.color() != m_root->style( mapped ).polyStyle().color() ) { /* qDebug() << "BrushColor:" << m_root->style( mapped ).polyStyle()->color() << m_currentBrush.color();*/ m_currentBrush.setColor( m_root->style( mapped ).polyStyle().color() ); m_painter->setBrush( m_currentBrush.color() ); } } void GeoRendererView::setPenStyle( QString mapped ) { /* * see the note in the setBrushStyle function */ if( m_currentPen.color() != m_root->style( mapped ).lineStyle().color() || m_currentPen.widthF() != m_root->style( mapped ).lineStyle().width() ) { /* qDebug() << "PenColor:" << m_root->style( mapped ).lineStyle().color() << m_currentPen.color(); qDebug() << "PenWidth:" << m_root->style( mapped ).lineStyle().width() << m_currentPen.widthF();*/ m_currentPen.setColor( m_root->style( mapped ).lineStyle().color() ); m_currentPen.setWidthF( m_root->style( mapped ).lineStyle().width() ); } if ( m_painter->mapQuality() != Marble::High && m_painter->mapQuality() != Marble::Print ) { // m_currentPen.setWidth( 0 ); QColor penColor = m_currentPen.color(); penColor.setAlpha( 255 ); m_currentPen.setColor( penColor ); } m_painter->setPen( m_currentPen ); } bool GeoRendererView::renderGeoDataGeometry( GeoDataGeometry *object, QString styleUrl ) { m_painter->save(); m_painter->autoMapQuality(); m_root = dynamic_cast<GeoDataDocument*>( model()->data( rootIndex(), Qt::UserRole + 11 ).value<Marble::GeoDataObject*>() ); if( !m_root ) { qWarning() << "root seems to be 0!!!"; return false; } /// hard coded to use only the "normal" style QString mapped = styleUrl; const GeoDataStyleMap& styleMap = m_root->styleMap( styleUrl.remove( '#' ) ); mapped = styleMap.value( QString( "normal" ) ); mapped.remove( '#' ); if( object->geometryId() == GeoDataPolygonId ) { setBrushStyle( mapped ); setPenStyle( mapped ); m_painter->drawPolygon( *static_cast<GeoDataPolygon*>( object ) ); } if( object->geometryId() == GeoDataLinearRingId ) { m_painter->setBrush( QColor( 0, 0, 0, 0 ) ); setPenStyle( mapped ); m_painter->drawPolygon( *static_cast<GeoDataLinearRing*>( object ) ); } if( object->geometryId() == GeoDataLineStringId ) { setPenStyle( mapped ); m_painter->drawPolyline( *static_cast<GeoDataLineString*>( object ) ); } /* Note: GeoDataMultiGeometry is handled within the model */ m_painter->restore(); return true; } <commit_msg>instead of checking a member variable, check the painter itself. Since this worked before, the painter seems to forget its brush, so maybe we can find that too, to reduce the number of setBrush-calls<commit_after>// // This file is part of the Marble Desktop Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2008-2009 Patrick Spendrin <ps_ml@gmx.de> // #include "GeoRendererView.h" // Marble #include "GeoDataContainer.h" #include "GeoDataCoordinates.h" #include "GeoDataDocument.h" #include "GeoDataFeature.h" #include "GeoDataFolder.h" #include "GeoDataLineStyle.h" #include "GeoDataObject.h" #include "GeoDataPlacemark.h" #include "GeoDataPolygon.h" #include "GeoDataPolyStyle.h" #include "GeoDataStyle.h" #include "GeoDataStyleMap.h" #include "GeoPainter.h" // Qt #include <QtCore/QDebug> #include <QtGui/QPaintEvent> using namespace Marble; GeoRendererView::GeoRendererView( QWidget * parent ) : QAbstractItemView( parent ) { } void GeoRendererView::setGeoPainter( GeoPainter* painter ) { m_painter = painter; /* the paintEvent function has to called by hand as the view is not * connected to a widget (where you normally would get the event from) */ if( model() ) paintEvent( 0 ); } QRect GeoRendererView::visualRect( const QModelIndex &index ) const { Q_UNUSED( index ) return QRect(); } void GeoRendererView::scrollTo( const QModelIndex &index, ScrollHint hint ) { Q_UNUSED( index ) Q_UNUSED( hint ) } QModelIndex GeoRendererView::indexAt( const QPoint &point ) const { Q_UNUSED( point ) return QModelIndex(); } QModelIndex GeoRendererView::moveCursor( QAbstractItemView::CursorAction cursorAction, Qt::KeyboardModifiers modifiers ) { Q_UNUSED( cursorAction ) Q_UNUSED( modifiers ) return QModelIndex(); } bool GeoRendererView::isIndexHidden( const QModelIndex &index ) const { Q_UNUSED( index ) return false; } void GeoRendererView::setSelection( const QRect&, QItemSelectionModel::SelectionFlags command ) { Q_UNUSED( command ) } void GeoRendererView::paintEvent( QPaintEvent *event ) { Q_UNUSED( event ) QModelIndex index = rootIndex(); renderIndex( index ); } void GeoRendererView::renderIndex( QModelIndex &index ) { /* * "render" a specific index - this means going through all children and if * one can be rendered (if it is a Geometry object which is not a container) * then call the real render function. For the rest iterate through the * children and recurse. */ GeoDataObject* indexObject = model()->data( rootIndex(), Qt::UserRole + 11 ).value<Marble::GeoDataObject*>(); if( !( dynamic_cast<GeoDataFeature*>( indexObject ) && dynamic_cast<GeoDataFeature*>( indexObject )->isVisible() ) ) return; int rowCount = model()->rowCount( index ); for ( int row = 0; row < rowCount; ++row ) { QModelIndex childIndex = model()->index( row, 0, index ); QString output = model()->data( childIndex ).toString(); GeoDataObject* object = model()->data( childIndex, Qt::UserRole + 11 ).value<Marble::GeoDataObject*>(); if( dynamic_cast<GeoDataGeometry*>( object ) ) { if( static_cast<GeoDataGeometry*>( object )->geometryId() != GeoDataMultiGeometryId ) { renderGeoDataGeometry( reinterpret_cast<GeoDataGeometry*>( object ), styleUrl ); } else { if( childIndex.isValid() && model()->rowCount( childIndex ) > 0 ) { renderIndex( childIndex ); } } } else if( dynamic_cast<GeoDataFeature*>( object ) ) { if( dynamic_cast<GeoDataFeature*>( object )->featureId() == GeoDataPlacemarkId ) { GeoDataPlacemark placemark( *static_cast<GeoDataFeature*>( object ) ); styleUrl = placemark.styleUrl(); } if( childIndex.isValid() && model()->rowCount( childIndex ) > 0 ) { renderIndex( childIndex ); } } } } QRegion GeoRendererView::visualRegionForSelection( const QItemSelection &selection ) const { Q_UNUSED( selection ) return QRegion(); } void GeoRendererView::setBrushStyle( QString mapped ) { /* this part has to be reworked: * Currently the style has to be accessible from the root object of the * model. This might not be wanted. On the other hand - is a copy of the * style within every Placemark wanted and how should this be called here? */ if( m_painter->brush().color() != m_root->style( mapped ).polyStyle().color() ) { /* qDebug() << "BrushColor:" << m_root->style( mapped ).polyStyle().color() << m_painter->brush().color();*/ m_painter->setBrush( m_currentBrush.color() ); } } void GeoRendererView::setPenStyle( QString mapped ) { /* * see the note in the setBrushStyle function */ if( m_currentPen.color() != m_root->style( mapped ).lineStyle().color() || m_currentPen.widthF() != m_root->style( mapped ).lineStyle().width() ) { /* qDebug() << "PenColor:" << m_root->style( mapped ).lineStyle().color() << m_currentPen.color(); qDebug() << "PenWidth:" << m_root->style( mapped ).lineStyle().width() << m_currentPen.widthF();*/ m_currentPen.setColor( m_root->style( mapped ).lineStyle().color() ); m_currentPen.setWidthF( m_root->style( mapped ).lineStyle().width() ); } if ( m_painter->mapQuality() != Marble::High && m_painter->mapQuality() != Marble::Print ) { // m_currentPen.setWidth( 0 ); QColor penColor = m_currentPen.color(); penColor.setAlpha( 255 ); m_currentPen.setColor( penColor ); } m_painter->setPen( m_currentPen ); } bool GeoRendererView::renderGeoDataGeometry( GeoDataGeometry *object, QString styleUrl ) { m_painter->save(); m_painter->autoMapQuality(); m_root = dynamic_cast<GeoDataDocument*>( model()->data( rootIndex(), Qt::UserRole + 11 ).value<Marble::GeoDataObject*>() ); if( !m_root ) { qWarning() << "root seems to be 0!!!"; return false; } /// hard coded to use only the "normal" style QString mapped = styleUrl; const GeoDataStyleMap& styleMap = m_root->styleMap( styleUrl.remove( '#' ) ); mapped = styleMap.value( QString( "normal" ) ); mapped.remove( '#' ); if( object->geometryId() == GeoDataPolygonId ) { setBrushStyle( mapped ); setPenStyle( mapped ); m_painter->drawPolygon( *static_cast<GeoDataPolygon*>( object ) ); } if( object->geometryId() == GeoDataLinearRingId ) { m_painter->setBrush( QColor( 0, 0, 0, 0 ) ); setPenStyle( mapped ); m_painter->drawPolygon( *static_cast<GeoDataLinearRing*>( object ) ); } if( object->geometryId() == GeoDataLineStringId ) { setPenStyle( mapped ); m_painter->drawPolyline( *static_cast<GeoDataLineString*>( object ) ); } /* Note: GeoDataMultiGeometry is handled within the model */ m_painter->restore(); return true; } <|endoftext|>
<commit_before>#include <stdio.h> #include <stdlib.h> #include <android/log.h> #include <jni.h> #include <tango-api/application-interface.h> #include <tango-api/vio-interface.h> #ifdef __cplusplus extern "C" { #endif application_handle_t *app_handler; #define LOG_TAG "JJ" #define LOG(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__) static float vioStatusArray[6] = {}; JNIEXPORT void JNICALL Java_com_google_tango_hellotangojni_TangoJNINative_initApplication( JNIEnv *env, jobject obj) { app_handler = ApplicationInitialize("[Superframes Small-Peanut]", 1); if(app_handler == NULL) { LOG("Application initialize failed\n"); return; } CAPIErrorCodes ret_error; if((ret_error = VIOInitialize(app_handler, 1, NULL)) != kCAPISuccess) { LOG("VIO initialized failed: %d\n", ret_error); return; } LOG("Application and VIO initialized success"); } JNIEXPORT void JNICALL Java_com_google_tango_hellotangojni_TangoJNINative_updateVIO( JNIEnv * env, jobject obj) { VIOStatus viostatus; CAPIErrorCodes ret_error; if((ret_error = ApplicationDoStep(app_handler)) != kCAPISuccess) { LOG("Application do step failed: %d\n", ret_error); return; } if((ret_error = VIOGetLatestPoseOpenGL(app_handler, &viostatus)) != kCAPISuccess) { LOG("Application do step failed: %d\n", ret_error); return; } vioStatusArray[0]=viostatus.translation[0]; vioStatusArray[1]=viostatus.translation[1]; vioStatusArray[2]=viostatus.translation[2]; vioStatusArray[3]=viostatus.rotation[0]; vioStatusArray[4]=viostatus.rotation[1]; vioStatusArray[5]=viostatus.rotation[2]; } JNIEXPORT void Java_com_google_tango_hellotangojni_TangoJNINative_onGlSurfaceCreated(JNIEnv * env, jclass cls) { } JNIEXPORT void Java_com_google_tango_hellotangojni_TangoJNINative_onGLSurfaceChanged(JNIEnv * env, jclass cls, jint width, jint height) { } JNIEXPORT void Java_com_google_tango_hellotangojni_TangoJNINative_onGLSurfaceDraw(JNIEnv * env, jclass cls) { } #ifdef __cplusplus } #endif <commit_msg>Implementation of simple cube rendering represents VIO position and rotation in GLES version1.<commit_after>#include <stdio.h> #include <stdlib.h> #include <android/log.h> #include <jni.h> #include <tango-api/application-interface.h> #include <tango-api/vio-interface.h> #include <GLES2/gl2.h> #include <GLES/gl.h> #include <math.h> #ifdef __cplusplus extern "C" { #endif application_handle_t *app_handler; #define LOG_TAG "JJ" #define LOG(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__) static float vioStatusArray[6] = {}; JNIEXPORT void JNICALL Java_com_google_tango_hellotangojni_TangoJNINative_initApplication( JNIEnv *env, jobject obj) { app_handler = ApplicationInitialize("[Superframes Small-Peanut]", 1); if(app_handler == NULL) { LOG("Application initialize failed\n"); return; } CAPIErrorCodes ret_error; if((ret_error = VIOInitialize(app_handler, 1, NULL)) != kCAPISuccess) { LOG("VIO initialized failed: %d\n", ret_error); return; } LOG("Application and VIO initialized success"); } JNIEXPORT void JNICALL Java_com_google_tango_hellotangojni_TangoJNINative_updateVIO( JNIEnv * env, jobject obj) { VIOStatus viostatus; CAPIErrorCodes ret_error; if((ret_error = ApplicationDoStep(app_handler)) != kCAPISuccess) { LOG("Application do step failed: %d\n", ret_error); return; } if((ret_error = VIOGetLatestPoseOpenGL(app_handler, &viostatus)) != kCAPISuccess) { LOG("Application do step failed: %d\n", ret_error); return; } vioStatusArray[0]=viostatus.translation[0]; vioStatusArray[1]=viostatus.translation[1]; vioStatusArray[2]=viostatus.translation[2]; vioStatusArray[3]=viostatus.rotation[0]; vioStatusArray[4]=viostatus.rotation[1]; vioStatusArray[5]=viostatus.rotation[2]; } JNIEXPORT void Java_com_google_tango_hellotangojni_TangoJNINative_onGlSurfaceCreated(JNIEnv * env, jclass cls) { glClearColor(0, 0, 0, 1.0f); glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); } JNIEXPORT void Java_com_google_tango_hellotangojni_TangoJNINative_onGLSurfaceChanged(JNIEnv * env, jclass cls, jint width, jint height) { glViewport(0, 0, width, height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glFrustumf(-(GLfloat) width/height, (GLfloat) width/height, -1.0f, 1.0f, 1.0f, 10.0f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } JNIEXPORT void Java_com_google_tango_hellotangojni_TangoJNINative_onGLSurfaceDraw(JNIEnv * env, jclass cls) { static GLfloat vertices[] = { 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 1.0, 1.0, 1.0, 0, 1.0, 1.0, 0, 0, 1.0, 1.0, 0, 1.0, 1.0, 1.0 }; glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef(vioStatusArray[0]*3.0, vioStatusArray[1]*3.0, -3.0f+vioStatusArray[2]*3.0); glRotatef(vioStatusArray[3]*180.0, 1.0, 0.0, 0.0); glRotatef(vioStatusArray[4]*180.0, 0.0, 0.0, -1.0); glRotatef(vioStatusArray[5]*180.0, 0.0, 1.0, 0.0); glTranslatef(-0.5, -0.5, -0.5); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, 0, vertices); static GLbyte frontIndices[] = { 4, 5, 6, 7 }; static GLbyte rightIndices[] = { 1, 2, 6, 5 }; static GLbyte bottomIndices[] = { 0, 1, 5, 4 }; static GLbyte backIndices[] = { 0, 3, 2, 1 }; static GLbyte leftIndices[] = { 0, 4, 7, 3 }; static GLbyte topIndices[] = { 2, 3, 7, 6 }; glColor4f(0.3, 0.2, 0.8, 1.0); glDrawElements(GL_TRIANGLE_FAN, 4, GL_UNSIGNED_BYTE, frontIndices); glColor4f(1.0, 0.3, 0.6, 1.0); glDrawElements(GL_TRIANGLE_FAN, 4, GL_UNSIGNED_BYTE, rightIndices); glColor4f(0.3, 0.7, 0.9, 1.0); glDrawElements(GL_TRIANGLE_FAN, 4, GL_UNSIGNED_BYTE, bottomIndices); glColor4f(0.9, 0.5, 0.2, 1.0); glDrawElements(GL_TRIANGLE_FAN, 4, GL_UNSIGNED_BYTE, backIndices); glColor4f(0.1, 0.7, 0.6, 1.0); glDrawElements(GL_TRIANGLE_FAN, 4, GL_UNSIGNED_BYTE, leftIndices); glColor4f(0.8, 0.8, 0.0, 1.0); glDrawElements(GL_TRIANGLE_FAN, 4, GL_UNSIGNED_BYTE, topIndices); glDisableClientState(GL_VERTEX_ARRAY); glFlush(); } #ifdef __cplusplus } #endif <|endoftext|>
<commit_before>//Copyright (c) 2018 Ultimaker B.V. //CuraEngine is released under the terms of the AGPLv3 or higher. #include "utils/linearAlg2D.h" //Distance from point to line. #include "MergeInfillLines.h" namespace cura { MergeInfillLines::MergeInfillLines(ExtruderPlan& plan) : extruder_plan(plan) { //Just copy the parameters to their fields. } void MergeInfillLines::mergeLinesSharedEndStartPoint(GCodePath& first_path, const Point first_path_start, GCodePath& second_path, const Point second_path_start) const { for (const Point second_path_point : second_path.points) { first_path.points.push_back(second_path_point); //Move the coordinates over to the first path. } } void MergeInfillLines::mergeLinesSideBySide(const bool first_is_already_merged, GCodePath& first_path, const Point first_path_start, GCodePath& second_path, const Point second_path_start) const { //Alternative: Merge adjacent lines by drawing a line through them. coord_t first_path_length_flow = 0; Point average_first_path; Point previous_point = first_path_start; for (const Point point : first_path.points) { first_path_length_flow += vSize(point - previous_point); previous_point = point; } first_path_length_flow *= first_path.flow; //To get the volume we don't need to include the line width since it's the same for both lines. if (first_is_already_merged) { // take second point of path, first_path.points[0] average_first_path = first_path.points[0]; } else { average_first_path += first_path_start; for (const Point point : first_path.points) { average_first_path += point; } average_first_path /= (first_path.points.size() + 1); } coord_t second_path_length_flow = 0; Point previous_point_second = second_path_start; Point average_second_path = second_path_start; for (const Point point : second_path.points) { second_path_length_flow += vSize(point - previous_point_second); average_second_path += point; previous_point_second = point; } second_path_length_flow *= second_path.flow; average_second_path /= (second_path.points.size() + 1); coord_t new_path_length = 0; if (first_is_already_merged) { // check if the new point is a good extension of last part of existing polyline if (LinearAlg2D::getDist2FromLine(average_second_path, first_path.points[first_path.points.size()-2], first_path.points[first_path.points.size()-1]) == 0) { // replace last point with new point if it's an extension first_path.points[first_path.points.size()-1] = average_second_path; } else { first_path.points.push_back(average_second_path); } } else { first_path.points.clear(); first_path.points.push_back(average_first_path); first_path.points.push_back(average_second_path); } previous_point = first_path_start; for (const Point point : first_path.points) { new_path_length += vSize(point - previous_point); previous_point = point; } first_path.flow = static_cast<double>(first_path_length_flow + second_path_length_flow) / new_path_length; } bool MergeInfillLines::tryMerge(const bool first_is_already_merged, GCodePath& first_path, const Point first_path_start, GCodePath& second_path, Point second_path_start) const { if (first_path.config->isTravelPath()) //Don't merge travel moves. { return false; } if (first_path.config != second_path.config) //Only merge lines that have the same type. { return false; } if (first_path.config->type != PrintFeatureType::Infill && first_path.config->type != PrintFeatureType::Skin) //Only merge skin and infill lines. { return false; } if ((!first_is_already_merged && first_path.points.size() > 1) || second_path.points.size() > 1) { // For now we only merge simple lines, not polylines, to keep it simple. // If the first line is already a merged line, then allow it. return false; } const Point first_path_end = first_path.points.back(); Point second_path_end = second_path.points.back(); const Point first_direction = first_path_end - first_path_start; Point second_direction = second_path_end - second_path_start; coord_t dot_product = dot(first_direction, second_direction); const coord_t first_size = vSize(first_direction); const coord_t second_size = vSize(second_direction); // if (dot_product < 0) //Make lines in the same direction by flipping one. // { // second_direction *= -1; // dot_product *= -1; // Point swap = second_path_end; // second_path_end = second_path_start; // second_path_start = swap; // } //Check if lines are connected end-to-end and can be merged that way. const coord_t line_width = first_path.config->getLineWidth(); if (vSize2(first_path_end - second_path_start) < line_width * line_width || vSize2(first_path_start - second_path_end) < line_width * line_width) //Paths are already (practically) connected, end-to-end. { //Only merge if lines are more or less in the same direction. const bool is_straight = dot_product + 400 > first_size * second_size; //400 = 20*20, where 20 micron is the allowed inaccuracy in the dot product, allowing a slight curve. if (is_straight) { // TODO: merge lines in same direction mergeLinesSharedEndStartPoint(first_path, first_path_start, second_path, second_path_start); } return is_straight; } //Lines may be adjacent side-by-side then. Point first_path_middle; coord_t merged_size2; if (first_is_already_merged) { first_path_middle = first_path.points[0]; // the second point here was once the "middle" } else { first_path_middle = (first_path_start + first_path_end) / 2; } const Point second_path_middle = (second_path_start + second_path_end) / 2; const Point merged_direction = second_path_middle - first_path_middle; if (first_is_already_merged) { merged_size2 = vSize2(second_path_middle - first_path.points.back()); // check distance with last point in merged line that is to be replaced } else { merged_size2 = vSize2(merged_direction); } if (merged_size2 > 25 * line_width * line_width) { return false; //Lines are too far away from each other. } if (LinearAlg2D::getDist2FromLine(first_path_start, second_path_middle, second_path_middle + merged_direction) > 4 * line_width * line_width || LinearAlg2D::getDist2FromLine(first_path_end, second_path_middle, second_path_middle + merged_direction) > 4 * line_width * line_width || LinearAlg2D::getDist2FromLine(second_path_start, first_path_middle, first_path_middle + merged_direction) > 4 * line_width * line_width || LinearAlg2D::getDist2FromLine(second_path_end, first_path_middle, first_path_middle + merged_direction) > 4 * line_width * line_width) { return false; //One of the lines is too far from the merged line. Lines would be too wide or too far off. } mergeLinesSideBySide(first_is_already_merged, first_path, first_path_start, second_path, second_path_start); return true; } bool MergeInfillLines::mergeInfillLines(std::vector<GCodePath>& paths, const Point starting_position) const { /* Algorithm overview: 1. Loop over all lines to see if they can be merged. 1a. Check if two adjacent lines can be merged (skipping travel moves in between). 1b. If they can, merge both lines into the first line. 1c. If they are merged, check next that the first line can be merged with the line after the second line. 2. Do a second iteration over all paths to remove the tombstones. */ std::vector<size_t> remove_path_indices; std::set<size_t> is_merged; std::set<size_t> removed; // keep track of what we already removed, so don't remove it again //For each two adjacent lines, see if they can be merged. size_t first_path_index = 0; Point first_path_start = starting_position; size_t second_path_index = 1; for (; second_path_index < paths.size(); second_path_index++) { GCodePath& first_path = paths[first_path_index]; GCodePath& second_path = paths[second_path_index]; Point second_path_start = paths[second_path_index - 1].points.back(); if (second_path.config->isTravelPath()) { continue; //Skip travel paths. } if (tryMerge(is_merged.find(first_path_index) != is_merged.end(), first_path, first_path_start, second_path, second_path_start)) { /* If we combine two lines, the second path is inside the first line, so the iteration after that we need to merge the first line with the line after the second line, so we do NOT update first_path_index. */ for (size_t to_delete_index = first_path_index + 1; to_delete_index <= second_path_index; to_delete_index++) { if (removed.find(to_delete_index) == removed.end()) // if there are line(s) between first and second, then those lines are already marked as to be deleted, only add the new line(s) { remove_path_indices.push_back(to_delete_index); removed.insert(to_delete_index); } } is_merged.insert(first_path_index); } else { /* If we do not combine, the next iteration we must simply merge the second path with the line after it. */ first_path_index = second_path_index; first_path_start = second_path_start; } } //Delete all removed lines in one pass so that we need to move lines less often. if (!remove_path_indices.empty()) { size_t path_index = remove_path_indices[0]; for (size_t removed_position = 1; removed_position < remove_path_indices.size(); removed_position++) { for (; path_index < remove_path_indices[removed_position] - removed_position; path_index++) { paths[path_index] = paths[path_index + removed_position]; //Shift all paths. } } for (; path_index < paths.size() - remove_path_indices.size(); path_index++) //Remaining shifts at the end. { paths[path_index] = paths[path_index + remove_path_indices.size()]; } paths.erase(paths.begin() + path_index, paths.end()); return true; } else { return false; } } }//namespace cura <commit_msg>Now the line merging works on most parts where you expect it. CURA-5535<commit_after>//Copyright (c) 2018 Ultimaker B.V. //CuraEngine is released under the terms of the AGPLv3 or higher. #include "utils/linearAlg2D.h" //Distance from point to line. #include "MergeInfillLines.h" namespace cura { MergeInfillLines::MergeInfillLines(ExtruderPlan& plan) : extruder_plan(plan) { //Just copy the parameters to their fields. } void MergeInfillLines::mergeLinesSharedEndStartPoint(GCodePath& first_path, const Point first_path_start, GCodePath& second_path, const Point second_path_start) const { for (const Point second_path_point : second_path.points) { first_path.points.push_back(second_path_point); //Move the coordinates over to the first path. } } void MergeInfillLines::mergeLinesSideBySide(const bool first_is_already_merged, GCodePath& first_path, const Point first_path_start, GCodePath& second_path, const Point second_path_start) const { //Alternative: Merge adjacent lines by drawing a line through them. coord_t first_path_length_flow = 0; Point average_first_path; Point previous_point = first_path_start; for (const Point point : first_path.points) { first_path_length_flow += vSize(point - previous_point); previous_point = point; } first_path_length_flow *= first_path.flow; //To get the volume we don't need to include the line width since it's the same for both lines. if (first_is_already_merged) { // take second point of path, first_path.points[0] average_first_path = first_path.points[0]; } else { average_first_path += first_path_start; for (const Point point : first_path.points) { average_first_path += point; } average_first_path /= (first_path.points.size() + 1); } coord_t second_path_length_flow = 0; Point previous_point_second = second_path_start; Point average_second_path = second_path_start; for (const Point point : second_path.points) { second_path_length_flow += vSize(point - previous_point_second); average_second_path += point; previous_point_second = point; } second_path_length_flow *= second_path.flow; average_second_path /= (second_path.points.size() + 1); coord_t new_path_length = 0; if (first_is_already_merged) { // check if the new point is a good extension of last part of existing polyline if (LinearAlg2D::getDist2FromLine(average_second_path, first_path.points[first_path.points.size()-2], first_path.points[first_path.points.size()-1]) == 0) { // replace last point with new point if it's an extension first_path.points[first_path.points.size()-1] = average_second_path; } else { first_path.points.push_back(average_second_path); } } else { first_path.points.clear(); first_path.points.push_back(average_first_path); first_path.points.push_back(average_second_path); } previous_point = first_path_start; for (const Point point : first_path.points) { new_path_length += vSize(point - previous_point); previous_point = point; } first_path.flow = static_cast<double>(first_path_length_flow + second_path_length_flow) / new_path_length; } bool MergeInfillLines::tryMerge(const bool first_is_already_merged, GCodePath& first_path, const Point first_path_start, GCodePath& second_path, Point second_path_start) const { if (first_path.config->isTravelPath()) //Don't merge travel moves. { return false; } if (first_path.config != second_path.config) //Only merge lines that have the same type. { return false; } if (first_path.config->type != PrintFeatureType::Infill && first_path.config->type != PrintFeatureType::Skin) //Only merge skin and infill lines. { return false; } if ((!first_is_already_merged && first_path.points.size() > 1) || second_path.points.size() > 1) { // For now we only merge simple lines, not polylines, to keep it simple. // If the first line is already a merged line, then allow it. return false; } const Point first_path_end = first_path.points.back(); Point second_path_end = second_path.points.back(); const Point first_direction = first_path_end - first_path_start; Point second_direction = second_path_end - second_path_start; coord_t dot_product = dot(first_direction, second_direction); const coord_t first_size = vSize(first_direction); const coord_t second_size = vSize(second_direction); // if (dot_product < 0) //Make lines in the same direction by flipping one. // { // second_direction *= -1; // dot_product *= -1; // Point swap = second_path_end; // second_path_end = second_path_start; // second_path_start = swap; // } //Check if lines are connected end-to-end and can be merged that way. const coord_t line_width = first_path.config->getLineWidth(); if (vSize2(first_path_end - second_path_start) < line_width * line_width || vSize2(first_path_start - second_path_end) < line_width * line_width) //Paths are already (practically) connected, end-to-end. { //Only merge if lines are more or less in the same direction. const bool is_straight = dot_product + 400 > first_size * second_size; //400 = 20*20, where 20 micron is the allowed inaccuracy in the dot product, allowing a slight curve. if (is_straight) { mergeLinesSharedEndStartPoint(first_path, first_path_start, second_path, second_path_start); return true; } } //Lines may be adjacent side-by-side then. Point first_path_middle; coord_t merged_size2; if (first_is_already_merged) { first_path_middle = first_path.points[0]; // the second point here was once the "middle" } else { first_path_middle = (first_path_start + first_path_end) / 2; } const Point second_path_middle = (second_path_start + second_path_end) / 2; const Point merged_direction = second_path_middle - first_path_middle; if (first_is_already_merged) { merged_size2 = vSize2(second_path_middle - first_path.points.back()); // check distance with last point in merged line that is to be replaced } else { merged_size2 = vSize2(merged_direction); } if (merged_size2 > 25 * line_width * line_width) { return false; //Lines are too far away from each other. } if (LinearAlg2D::getDist2FromLine(first_path_start, second_path_middle, second_path_middle + merged_direction) > 4 * line_width * line_width || LinearAlg2D::getDist2FromLine(first_path_end, second_path_middle, second_path_middle + merged_direction) > 4 * line_width * line_width || LinearAlg2D::getDist2FromLine(second_path_start, first_path_middle, first_path_middle + merged_direction) > 4 * line_width * line_width || LinearAlg2D::getDist2FromLine(second_path_end, first_path_middle, first_path_middle + merged_direction) > 4 * line_width * line_width) { return false; //One of the lines is too far from the merged line. Lines would be too wide or too far off. } mergeLinesSideBySide(first_is_already_merged, first_path, first_path_start, second_path, second_path_start); return true; } bool MergeInfillLines::mergeInfillLines(std::vector<GCodePath>& paths, const Point starting_position) const { /* Algorithm overview: 1. Loop over all lines to see if they can be merged. 1a. Check if two adjacent lines can be merged (skipping travel moves in between). 1b. If they can, merge both lines into the first line. 1c. If they are merged, check next that the first line can be merged with the line after the second line. 2. Do a second iteration over all paths to remove the tombstones. */ std::vector<size_t> remove_path_indices; std::set<size_t> is_merged; std::set<size_t> removed; // keep track of what we already removed, so don't remove it again //For each two adjacent lines, see if they can be merged. size_t first_path_index = 0; Point first_path_start = starting_position; size_t second_path_index = 1; for (; second_path_index < paths.size(); second_path_index++) { GCodePath& first_path = paths[first_path_index]; GCodePath& second_path = paths[second_path_index]; Point second_path_start = paths[second_path_index - 1].points.back(); if (second_path.config->isTravelPath()) { continue; //Skip travel paths. } if (tryMerge(is_merged.find(first_path_index) != is_merged.end(), first_path, first_path_start, second_path, second_path_start)) { /* If we combine two lines, the second path is inside the first line, so the iteration after that we need to merge the first line with the line after the second line, so we do NOT update first_path_index. */ for (size_t to_delete_index = first_path_index + 1; to_delete_index <= second_path_index; to_delete_index++) { if (removed.find(to_delete_index) == removed.end()) // if there are line(s) between first and second, then those lines are already marked as to be deleted, only add the new line(s) { remove_path_indices.push_back(to_delete_index); removed.insert(to_delete_index); } } is_merged.insert(first_path_index); } else { /* If we do not combine, the next iteration we must simply merge the second path with the line after it. */ first_path_index = second_path_index; first_path_start = second_path_start; } } //Delete all removed lines in one pass so that we need to move lines less often. if (!remove_path_indices.empty()) { size_t path_index = remove_path_indices[0]; for (size_t removed_position = 1; removed_position < remove_path_indices.size(); removed_position++) { for (; path_index < remove_path_indices[removed_position] - removed_position; path_index++) { paths[path_index] = paths[path_index + removed_position]; //Shift all paths. } } for (; path_index < paths.size() - remove_path_indices.size(); path_index++) //Remaining shifts at the end. { paths[path_index] = paths[path_index + remove_path_indices.size()]; } paths.erase(paths.begin() + path_index, paths.end()); return true; } else { return false; } } }//namespace cura <|endoftext|>
<commit_before>#include <iostream> #include <map> #include <execinfo.h> #include <stdio.h> #include <stdlib.h> #include <iostream> #include <chrono> #include <thread> #include <cstdlib> #include "fscore.h" using namespace fs; using namespace std; using namespace chrono; // using SdlArena = MemoryArena<Allocator<HeapAllocator, AllocationHeaderU32>, // MultiThread<MutexPrimitive>, // SimpleBoundsChecking, // FullMemoryTracking, // MemoryTagging>; template<class Allocator> void allocator_ManySmallAllocations_InOrder_FreeInReverse(const char* allocatorType, bool doFree = true) { FS_PRINT(allocatorType); const size_t allocationSize = 32; const size_t allocationAlignment = 8; HeapArea area(FS_SIZE_OF_MB * 7); Allocator allocator(area.getStart(), area.getEnd()); auto start = steady_clock::now(); const i32 numAllocations = FS_SIZE_OF_MB * 3 / allocationSize; uptr* allocations = new uptr[numAllocations]; for(i32 i = 0; i < numAllocations; ++i) { allocations[i] = (uptr)allocator.allocate(allocationSize, allocationAlignment, 0); //FS_PRINT("allocated " << i << " @ " << (void*)allocations[i]); } auto end = steady_clock::now(); auto allocatorTime = duration<double, milli>(end - start).count(); double freeTime = 0; if(doFree) { start = steady_clock::now(); for(i32 i = numAllocations - 1; i >= 0; --i) { //FS_PRINT("free " << i << " @ " << (void*)allocations[i]); allocator.free((void*)allocations[i]); } end = steady_clock::now(); freeTime = duration<double, milli>(end - start).count(); } FS_PRINT("allocate = " << allocatorTime); FS_PRINT("free = " << freeTime); FS_PRINT(""); } int main( int, char **) { //Logger::init("content/logger.xml"); #define CURRENT_TEST(Allocator, ...) \ allocator_ManySmallAllocations_InOrder_FreeInReverse<ArgumentType<void(Allocator)>::type> \ (FS_PP_STRINGIZE(Allocator), __VA_ARGS__) FS_PRINT("allocator_ManySmallAllocations_InOrder_FreeInReverse"); CURRENT_TEST(LinearAllocator, false); CURRENT_TEST(StackAllocatorBottom, true); CURRENT_TEST(StackAllocatorTop, true); CURRENT_TEST((PoolAllocatorNonGrowable<32, 8>), true); CURRENT_TEST(HeapAllocator, true); CURRENT_TEST(MallocAllocator, true); #undef CURRENT_TEST //Logger::destroy(); return 0; } <commit_msg>WIP on more allocator benchmarking<commit_after>#include <iostream> #include <map> #include <execinfo.h> #include <stdio.h> #include <stdlib.h> #include <iostream> #include <chrono> #include <thread> #include <cstdlib> #include "fscore.h" using namespace fs; using namespace std; using namespace chrono; // using SdlArena = MemoryArena<Allocator<HeapAllocator, AllocationHeaderU32>, // MultiThread<MutexPrimitive>, // SimpleBoundsChecking, // FullMemoryTracking, // MemoryTagging>; template<class Allocator> void allocator_ManySmallAllocations_InOrder_FreeInReverse(const char* allocatorType, bool doFree = true) { FS_PRINT(allocatorType); const i32 numAllocations = 100000; const size_t allocationSize = 32; const size_t allocationAlignment = 8; HeapArea area(FS_SIZE_OF_MB * 32); Allocator allocator(area.getStart(), area.getEnd()); auto start = steady_clock::now(); uptr* allocations = new uptr[numAllocations]; for(i32 i = 0; i < numAllocations; ++i) { allocations[i] = (uptr)allocator.allocate(allocationSize, allocationAlignment, 0); } auto end = steady_clock::now(); auto allocatorTime = duration<double, milli>(end - start).count(); double freeTime = 0; if(doFree) { start = steady_clock::now(); for(i32 i = numAllocations - 1; i >= 0; --i) { allocator.free((void*)allocations[i]); } end = steady_clock::now(); freeTime = duration<double, milli>(end - start).count(); } FS_PRINT("allocate = " << allocatorTime); FS_PRINT("free = " << freeTime); FS_PRINT(""); } template<class Allocator> void allocator_ManyMixedAllocations_InOrder_FreeInReverse(const char* allocatorType, bool doFree = true) { FS_PRINT(allocatorType); const i32 numAllocations = 100000; const size_t allocationSize = 32; const size_t allocationAlignment = 8; const size_t maxSizeMultiple = 100; srand(1234); HeapArea area(FS_SIZE_OF_MB * 32); Allocator allocator(area.getStart(), area.getEnd()); uptr* allocations = new uptr[numAllocations]; size_t* sizes = new uptr[numAllocations]; size_t approxSize = 0; for(i32 i = 0; i < numAllocations; ++i) { size_t size = (rand() % (maxSizeMultiple - 1) + 1) * allocationSize; sizes[i] = size; approxSize += size; } auto start = steady_clock::now(); for(i32 i = 0; i < numAllocations; ++i) { allocations[i] = (uptr)allocator.allocate(sizes[i], allocationAlignment, 0); //FS_PRINT("allocated " << i << " @ " << (void*)allocations[i]); } auto end = steady_clock::now(); auto allocatorTime = duration<double, milli>(end - start).count(); double freeTime = 0; if(doFree) { start = steady_clock::now(); for(i32 i = numAllocations - 1; i >= 0; --i) { //FS_PRINT("free " << i << " @ " << (void*)allocations[i]); allocator.free((void*)allocations[i]); } end = steady_clock::now(); freeTime = duration<double, milli>(end - start).count(); } FS_PRINT("allocate = " << allocatorTime); FS_PRINT("free = " << freeTime); FS_PRINT(""); } int main( int, char **) { //Logger::init("content/logger.xml"); #define CURRENT_TEST(Allocator, ...) \ allocator_ManySmallAllocations_InOrder_FreeInReverse<ArgumentType<void(Allocator)>::type> \ (FS_PP_STRINGIZE(Allocator), __VA_ARGS__) FS_PRINT("allocator_ManySmallAllocations_InOrder_FreeInReverse"); CURRENT_TEST(LinearAllocator, false); CURRENT_TEST(StackAllocatorBottom, true); CURRENT_TEST(StackAllocatorTop, true); CURRENT_TEST((PoolAllocatorNonGrowable<32, 8>), true); CURRENT_TEST(HeapAllocator, true); CURRENT_TEST(MallocAllocator, true); #undef CURRENT_TEST #define CURRENT_TEST(Allocator, ...) \ allocator_ManyMixedAllocations_InOrder_FreeInReverse<ArgumentType<void(Allocator)>::type> \ (FS_PP_STRINGIZE(Allocator), __VA_ARGS__) FS_PRINT("allocator_ManyMixedAllocations_InOrder_FreeInReverse"); CURRENT_TEST(LinearAllocator, false); CURRENT_TEST(StackAllocatorBottom, true); CURRENT_TEST(StackAllocatorTop, true); CURRENT_TEST(HeapAllocator, true); CURRENT_TEST(MallocAllocator, true); #undef CURRENT_TEST //Logger::destroy(); return 0; } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: TestSQLiteDatabase.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. =========================================================================*/ /*---------------------------------------------------------------------------- Copyright (c) Sandia Corporation See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details. ----------------------------------------------------------------------------*/ // .SECTION Thanks // Thanks to Andrew Wilson from Sandia National Laboratories for implementing // this test. #include "vtkSQLiteDatabase.h" #include "vtkSQLQuery.h" #include "vtkSQLDatabaseSchema.h" #include "vtkRowQueryToTable.h" #include "vtkStdString.h" #include "vtkTable.h" #include "vtkVariant.h" #include "vtkVariantArray.h" #include <vtkstd/vector> int TestSQLiteDatabase( int /*argc*/, char* /*argv*/[]) { vtkSQLiteDatabase* db = vtkSQLiteDatabase::SafeDownCast( vtkSQLDatabase::CreateFromURL( "sqlite://:memory:" ) ); bool status = db->Open(); if ( ! status ) { cerr << "Couldn't open database.\n"; return 1; } vtkSQLQuery* query = db->GetQueryInstance(); vtkStdString createQuery("CREATE TABLE IF NOT EXISTS people (name TEXT, age INTEGER, weight FLOAT)"); cout << createQuery << endl; query->SetQuery( createQuery.c_str()); if (!query->Execute()) { cerr << "Create query failed" << endl; return 1; } for ( int i = 0; i < 40; i++) { char insertQuery[200]; sprintf( insertQuery, "INSERT INTO people VALUES('John Doe %d', %d, %d)", i, i, 10*i ); cout << insertQuery << endl; query->SetQuery( insertQuery ); if (!query->Execute()) { cerr << "Insert query " << i << " failed" << endl; return 1; } } const char *queryText = "SELECT name, age, weight FROM people WHERE age <= 20"; query->SetQuery( queryText ); cerr << endl << "Running query: " << query->GetQuery() << endl; cerr << endl << "Using vtkSQLQuery directly to execute query:" << endl; if (!query->Execute()) { cerr << "Query failed" << endl; return 1; } for ( int col = 0; col < query->GetNumberOfFields(); col++) { if ( col > 0) { cerr << ", "; } cerr << query->GetFieldName( col ); } cerr << endl; while ( query->NextRow()) { for ( int field = 0; field < query->GetNumberOfFields(); field++) { if ( field > 0) { cerr << ", "; } cerr << query->DataValue( field ).ToString().c_str(); } cerr << endl; } cerr << endl << "Using vtkSQLQuery to execute query and retrieve by row:" << endl; if (!query->Execute()) { cerr << "Query failed" << endl; return 1; } for ( int col = 0; col < query->GetNumberOfFields(); col++) { if ( col > 0) { cerr << ", "; } cerr << query->GetFieldName( col ); } cerr << endl; vtkVariantArray* va = vtkVariantArray::New(); while ( query->NextRow( va )) { for ( int field = 0; field < va->GetNumberOfValues(); field++) { if ( field > 0) { cerr << ", "; } cerr << va->GetValue( field ).ToString().c_str(); } cerr << endl; } va->Delete(); cerr << endl << "Using vtkRowQueryToTable to execute query:" << endl; vtkRowQueryToTable* reader = vtkRowQueryToTable::New(); reader->SetQuery( query ); reader->Update(); vtkTable* table = reader->GetOutput(); for ( vtkIdType col = 0; col < table->GetNumberOfColumns(); col++) { table->GetColumn( col )->Print( cerr ); } cerr << endl; for ( vtkIdType row = 0; row < table->GetNumberOfRows(); row++) { for ( vtkIdType col = 0; col < table->GetNumberOfColumns(); col++) { vtkVariant v = table->GetValue( row, col ); cerr << "row " << row << ", col " << col << " - " << v.ToString() << " (" << vtkImageScalarTypeNameMacro( v.GetType()) << ")" << endl; } } reader->Delete(); query->Delete(); db->Delete(); // ---------------------------------------------------------------------- // Testing transformation of a schema into a SQLite database // 1. Create the schema cerr << "@@ Creating a schema..."; vtkSQLDatabaseSchema* schema = vtkSQLDatabaseSchema::New(); schema->SetName( "TestSchema" ); int tblHandle = schema->AddTableMultipleArguments( "StrangeTable", vtkSQLDatabaseSchema::COLUMN_TOKEN, vtkSQLDatabaseSchema::INTEGER, "TableKey", 0, "", vtkSQLDatabaseSchema::COLUMN_TOKEN, vtkSQLDatabaseSchema::VARCHAR, "SomeName", 11, "NOT NULL", vtkSQLDatabaseSchema::COLUMN_TOKEN, vtkSQLDatabaseSchema::BIGINT, "SomeNmbr", 17, "DEFAULT 0", vtkSQLDatabaseSchema::INDEX_TOKEN, vtkSQLDatabaseSchema::PRIMARY_KEY, "BigKey", vtkSQLDatabaseSchema::INDEX_COLUMN_TOKEN, "TableKey", vtkSQLDatabaseSchema::END_INDEX_TOKEN, vtkSQLDatabaseSchema::INDEX_TOKEN, vtkSQLDatabaseSchema::UNIQUE, "ReverseLookup", vtkSQLDatabaseSchema::INDEX_COLUMN_TOKEN, "SomeName", vtkSQLDatabaseSchema::INDEX_COLUMN_TOKEN, "SomeNmbr", vtkSQLDatabaseSchema::END_INDEX_TOKEN, vtkSQLDatabaseSchema::TRIGGER_TOKEN, vtkSQLDatabaseSchema::AFTER_INSERT, "InsertTrigger", "INSERT INTO OtherTable ( Value ) VALUES NEW.SomeNmbr", vtkSQLDatabaseSchema::END_TABLE_TOKEN ); if ( tblHandle < 0 ) { cerr << "Could not create test schema.\n"; return 1; } cerr << " done." << endl; // 2. Convert the schema into a SQLite database cerr << "@@ Converting the schema into a SQLite database..."; vtkSQLiteDatabase* dbSch = vtkSQLiteDatabase::SafeDownCast( vtkSQLDatabase::CreateFromURL( "sqlite://:memory:" ) ); status = dbSch->Open(); if ( ! status ) { cerr << "Couldn't open database.\n"; return 1; } status = dbSch->EffectSchema( schema ); if ( ! status ) { cerr << "Could not effect test schema.\n"; return 1; } cerr << " done." << endl; // 3. Count tables of the newly created database cerr << "@@ Fetching table names of the newly created database:\n"; query = dbSch->GetQueryInstance(); query->SetQuery( "SELECT name FROM sqlite_master WHERE type = \"table\"" ); if ( ! query->Execute() ) { cerr << "QuerySch failed" << endl; return 1; } for ( tblHandle =0; query->NextRow(); ++ tblHandle ) { vtkStdString tblNameSch( schema->GetTableNameFromHandle( tblHandle ) ); vtkStdString tblNameDB( query->DataValue( 0 ).ToString() ); cerr << " " << tblNameDB << "\n"; if ( tblNameDB != tblNameSch ) { cerr << "Fetched an incorrect name: " << tblNameDB << " != " << tblNameSch << endl; return 1; } } if ( tblHandle != schema->GetNumberOfTables() ) { cerr << "Found an incorrect number of tables: " << tblHandle << " != " << schema->GetNumberOfTables() << endl; return 1; } cerr << " " << tblHandle << " found.\n"; // Clean up dbSch->Delete(); schema->Delete(); query->Delete(); return 0; } <commit_msg>STYLE: fixed typo in the output message.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: TestSQLiteDatabase.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. =========================================================================*/ /*---------------------------------------------------------------------------- Copyright (c) Sandia Corporation See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details. ----------------------------------------------------------------------------*/ // .SECTION Thanks // Thanks to Andrew Wilson from Sandia National Laboratories for implementing // this test. #include "vtkSQLiteDatabase.h" #include "vtkSQLQuery.h" #include "vtkSQLDatabaseSchema.h" #include "vtkRowQueryToTable.h" #include "vtkStdString.h" #include "vtkTable.h" #include "vtkVariant.h" #include "vtkVariantArray.h" #include <vtkstd/vector> int TestSQLiteDatabase( int /*argc*/, char* /*argv*/[]) { vtkSQLiteDatabase* db = vtkSQLiteDatabase::SafeDownCast( vtkSQLDatabase::CreateFromURL( "sqlite://:memory:" ) ); bool status = db->Open(); if ( ! status ) { cerr << "Couldn't open database.\n"; return 1; } vtkSQLQuery* query = db->GetQueryInstance(); vtkStdString createQuery("CREATE TABLE IF NOT EXISTS people (name TEXT, age INTEGER, weight FLOAT)"); cout << createQuery << endl; query->SetQuery( createQuery.c_str()); if (!query->Execute()) { cerr << "Create query failed" << endl; return 1; } for ( int i = 0; i < 40; i++) { char insertQuery[200]; sprintf( insertQuery, "INSERT INTO people VALUES('John Doe %d', %d, %d)", i, i, 10*i ); cout << insertQuery << endl; query->SetQuery( insertQuery ); if (!query->Execute()) { cerr << "Insert query " << i << " failed" << endl; return 1; } } const char *queryText = "SELECT name, age, weight FROM people WHERE age <= 20"; query->SetQuery( queryText ); cerr << endl << "Running query: " << query->GetQuery() << endl; cerr << endl << "Using vtkSQLQuery directly to execute query:" << endl; if (!query->Execute()) { cerr << "Query failed" << endl; return 1; } for ( int col = 0; col < query->GetNumberOfFields(); col++) { if ( col > 0) { cerr << ", "; } cerr << query->GetFieldName( col ); } cerr << endl; while ( query->NextRow()) { for ( int field = 0; field < query->GetNumberOfFields(); field++) { if ( field > 0) { cerr << ", "; } cerr << query->DataValue( field ).ToString().c_str(); } cerr << endl; } cerr << endl << "Using vtkSQLQuery to execute query and retrieve by row:" << endl; if (!query->Execute()) { cerr << "Query failed" << endl; return 1; } for ( int col = 0; col < query->GetNumberOfFields(); col++) { if ( col > 0) { cerr << ", "; } cerr << query->GetFieldName( col ); } cerr << endl; vtkVariantArray* va = vtkVariantArray::New(); while ( query->NextRow( va )) { for ( int field = 0; field < va->GetNumberOfValues(); field++) { if ( field > 0) { cerr << ", "; } cerr << va->GetValue( field ).ToString().c_str(); } cerr << endl; } va->Delete(); cerr << endl << "Using vtkRowQueryToTable to execute query:" << endl; vtkRowQueryToTable* reader = vtkRowQueryToTable::New(); reader->SetQuery( query ); reader->Update(); vtkTable* table = reader->GetOutput(); for ( vtkIdType col = 0; col < table->GetNumberOfColumns(); col++) { table->GetColumn( col )->Print( cerr ); } cerr << endl; for ( vtkIdType row = 0; row < table->GetNumberOfRows(); row++) { for ( vtkIdType col = 0; col < table->GetNumberOfColumns(); col++) { vtkVariant v = table->GetValue( row, col ); cerr << "row " << row << ", col " << col << " - " << v.ToString() << " (" << vtkImageScalarTypeNameMacro( v.GetType()) << ")" << endl; } } reader->Delete(); query->Delete(); db->Delete(); // ---------------------------------------------------------------------- // Testing transformation of a schema into a SQLite database // 1. Create the schema cerr << "@@ Creating a schema..."; vtkSQLDatabaseSchema* schema = vtkSQLDatabaseSchema::New(); schema->SetName( "TestSchema" ); int tblHandle = schema->AddTableMultipleArguments( "StrangeTable", vtkSQLDatabaseSchema::COLUMN_TOKEN, vtkSQLDatabaseSchema::INTEGER, "TableKey", 0, "", vtkSQLDatabaseSchema::COLUMN_TOKEN, vtkSQLDatabaseSchema::VARCHAR, "SomeName", 11, "NOT NULL", vtkSQLDatabaseSchema::COLUMN_TOKEN, vtkSQLDatabaseSchema::BIGINT, "SomeNmbr", 17, "DEFAULT 0", vtkSQLDatabaseSchema::INDEX_TOKEN, vtkSQLDatabaseSchema::PRIMARY_KEY, "BigKey", vtkSQLDatabaseSchema::INDEX_COLUMN_TOKEN, "TableKey", vtkSQLDatabaseSchema::END_INDEX_TOKEN, vtkSQLDatabaseSchema::INDEX_TOKEN, vtkSQLDatabaseSchema::UNIQUE, "ReverseLookup", vtkSQLDatabaseSchema::INDEX_COLUMN_TOKEN, "SomeName", vtkSQLDatabaseSchema::INDEX_COLUMN_TOKEN, "SomeNmbr", vtkSQLDatabaseSchema::END_INDEX_TOKEN, vtkSQLDatabaseSchema::TRIGGER_TOKEN, vtkSQLDatabaseSchema::AFTER_INSERT, "InsertTrigger", "INSERT INTO OtherTable ( Value ) VALUES NEW.SomeNmbr", vtkSQLDatabaseSchema::END_TABLE_TOKEN ); if ( tblHandle < 0 ) { cerr << "Could not create test schema.\n"; return 1; } cerr << " done." << endl; // 2. Convert the schema into a SQLite database cerr << "@@ Converting the schema into a SQLite database..."; vtkSQLiteDatabase* dbSch = vtkSQLiteDatabase::SafeDownCast( vtkSQLDatabase::CreateFromURL( "sqlite://:memory:" ) ); status = dbSch->Open(); if ( ! status ) { cerr << "Couldn't open database.\n"; return 1; } status = dbSch->EffectSchema( schema ); if ( ! status ) { cerr << "Could not effect test schema.\n"; return 1; } cerr << " done." << endl; // 3. Count tables of the newly created database cerr << "@@ Fetching table names of the newly created database:\n"; query = dbSch->GetQueryInstance(); query->SetQuery( "SELECT name FROM sqlite_master WHERE type = \"table\"" ); if ( ! query->Execute() ) { cerr << "Query failed" << endl; return 1; } for ( tblHandle =0; query->NextRow(); ++ tblHandle ) { vtkStdString tblNameSch( schema->GetTableNameFromHandle( tblHandle ) ); vtkStdString tblNameDB( query->DataValue( 0 ).ToString() ); cerr << " " << tblNameDB << "\n"; if ( tblNameDB != tblNameSch ) { cerr << "Fetched an incorrect name: " << tblNameDB << " != " << tblNameSch << endl; return 1; } } if ( tblHandle != schema->GetNumberOfTables() ) { cerr << "Found an incorrect number of tables: " << tblHandle << " != " << schema->GetNumberOfTables() << endl; return 1; } cerr << " " << tblHandle << " found.\n"; // Clean up dbSch->Delete(); schema->Delete(); query->Delete(); return 0; } <|endoftext|>
<commit_before>/** The goal of this tutorial is to implement, in Tiramisu, a code that is equivalent to the following for (int i = 0; i < 10; i++) buf0[i] = 3 + 4; Tiramisu is a code generator, therefore the goal of a Tiramisu program is to generate code that is supposed to be called from another program (the user program). A Tiramisu program is structures as follows: - It starts with a call to initialize the Tiramisu compiler. The name of the function to be generated is specified during this initialization. - The user then declares the algorithm: Tiramisu expressions. - The user then specifies how the algorithm should be optimized using scheduling and data mapping commands. - The user then calls the codegen() function which generates code. This call compiles the Tiramisu program and generates an object file. The user can call the function compiled in the object file from any place in his program. How to compile ? You can use the makefile to compile the tutorial or you can do it manually. To compile and run the tutorials using the makefile use: cd build/ make run_developers_tutorial_01 Detailed compilation process (without makefile) are explained below at the end of this tutorial. */ // Every Tiramisu program needs to include the header file tiramisu/tiramisu.h // which defines classes for declaring and compiling Tiramisu expressions. #include <tiramisu/tiramisu.h> using namespace tiramisu; int main(int argc, char **argv) { // Initialize the tiramisu compiler and declare a function called "function0". // A function in tiramisu is the equivalent of a function in C. // It can have input and output arguments (buffers). These arguments // are declared later in the tutorial. tiramisu::init("function0"); // ------------------------------------------------------- // Layer I: provide the algorithm. // ------------------------------------------------------- // Declare an iterator. The range of this iterator is [0, 10[ // i.e., 0<=i<10 var i("i", 0, 10); // Declare a computation that adds 3 and 4. This computation is done // within a loop that has i as iterator. computation S0({i}, 3 + 4); // Since the iterator i is declared to be 0<=i<10 (i.e., the iteration space of S0 is 0<=i<10), // the previous declaration of S0 is equivalent to the following C code // for (i = 0; i < 10; i++) // S0(i) = 3 + 4; // ------------------------------------------------------------ // Layer II: specify how the algorithm is optimized. // ------------------------------------------------------------ // Parallelize the loop level i S0.parallelize(i); // ------------------------------------------------------- // Layer III: allocate buffers and specify how computations // should be stored in these buffers. // ------------------------------------------------------- // Create a buffer called "buf0". buffer buf0("buf0", {10}, p_uint8, a_output); // The second argument to the constructor is a vector that represents the // size of the buffer dimensions. In this example, the vector has only one // element (which is expr(10)), therefore the buffer only has one dimension // of size 10. // The third argument is the type of the buffer elements (uint8). // The fourth argument indicates whether the buffer is in input or an output buffer. // Othr types are a_input (for input buffers) and a_temporary (for temporary buffers // allocated and freed within the function). // For more details about the constructor of buffers please refer to the // documentation https://tiramisu-compiler.github.io/doc/classtiramisu_1_1buffer.html // In general, all the API of Tiramisu is documented in https://tiramisu-compiler.github.io/doc/ // Store the computation S0 to the buffer buf0. // That is, store the computation S0(i) in buf0[i]. S0.store_in(&buf0); // ------------------------------------------------------- // Code Generation // ------------------------------------------------------- // Compile code and store it in an object file. Two arguments need // to be passed to the code generator: // - The arguments (buffers) passed to the generated function. // The buffer buf0 is supposed to be allocated by the user (caller) // and is supposed to be passed to the generated function "function0". // Any buffer of type a_output or a_input are supposed to be allocated // by the user (caller), in contrast to buffers of type a_temporary which are // allocated automatically by Tiramisu and should not be passed as arguments // to the function). // - The name of the object file to be generated. function0.codegen({&buf0}, "build/generated_fct_developers_tutorial_01.o"); // Dump the generated Halide statement (just for debugging). function0.dump_halide_stmt(); return 0; } /** If you want to compile the tutorial manuall, you can follow the following steps. Assuming that the variable TIRAMISU_ROOT contains the path to the root directory of Tiramisu and that Tiramisu and it dependences are built using the default paths. First we need to compile the generator (it requires the header files and libraries of Halide, ISL and Tiramisu which all should be built automatically if you follow the default installation process). cd ${TIRAMISU_ROOT}/build g++ -std=c++11 -fno-rtti -DHALIDE_NO_JPEG -I${TIRAMISU_ROOT}/include -I${TIRAMISU_ROOT}/3rdParty/isl/include/ -I${TIRAMISU_ROOT}/3rdParty/Halide/include -I${TIRAMISU_ROOT}/build -L${TIRAMISU_ROOT}/build -L${TIRAMISU_ROOT}/3rdParty/isl/ -L${TIRAMISU_ROOT}/3rdParty/Halide/lib/ -o developers_tutorial_01_fct_generator -ltiramisu -lisl -lHalide -ldl -lpthread -lz -lm -Wl,-rpath,${TIRAMISU_ROOT}/build ${TIRAMISU_ROOT}/tutorials/developers/tutorial_01/tutorial_01.cpp Run the generator to generate the object file. cd ${TIRAMISU_ROOT} ./build/developers_tutorial_01_fct_generator This generator generates the file generated_fct_developers_tutorial_01.o You can compile the wrapper code (code that uses the generated code) and link it to the generated object file. cd ${TIRAMISU_ROOT}/build g++ -std=c++11 -fno-rtti -I${TIRAMISU_ROOT}/include -I${TIRAMISU_ROOT}/3rdParty/Halide/include -L${TIRAMISU_ROOT}/build -L${TIRAMISU_ROOT}/3rdParty/Halide/lib/ -o wrapper_tutorial_01 -ltiramisu -lHalide -ldl -lpthread -lz -lm -Wl,-rpath,${TIRAMISU_ROOT}/build ${TIRAMISU_ROOT}/tutorials/developers/tutorial_01/wrapper_tutorial_01.cpp generated_fct_developers_tutorial_01.o To run the program. ./wrapper_tutorial_01 */ <commit_msg>Update tutorial_01.cpp<commit_after>/** The goal of this tutorial is to implement, in Tiramisu, a code that is equivalent to the following for (int i = 0; i < 10; i++) buf0[i] = 3 + 4; Tiramisu is a code generator, therefore the goal of a Tiramisu program is to generate code that is supposed to be called from another program (the user program). A Tiramisu program is structures as follows: - It starts with a call to initialize the Tiramisu compiler. The name of the function to be generated is specified during this initialization. - The user then declares the algorithm: Tiramisu expressions. - The user then specifies how the algorithm should be optimized using scheduling and data mapping commands. - The user then calls the codegen() function which generates code. This call compiles the Tiramisu program and generates an object file. The user can call the function compiled in the object file from any place in his program. How to compile ? You can use the makefile to compile the tutorial or you can do it manually. To compile and run the tutorials using the makefile use: cd build/ make run_developers_tutorial_01 Detailed compilation process (without makefile) are explained below at the end of this tutorial. */ // Every Tiramisu program needs to include the header file tiramisu/tiramisu.h // which defines classes for declaring and compiling Tiramisu expressions. #include <tiramisu/tiramisu.h> using namespace tiramisu; int main(int argc, char **argv) { // Initialize the tiramisu compiler and declare a function called "function0". // A function in tiramisu is the equivalent of a function in C. // It can have input and output arguments (buffers). These arguments // are declared later in the tutorial. tiramisu::init("function0"); // ------------------------------------------------------- // Layer I: provide the algorithm. // ------------------------------------------------------- // Declare an iterator. The range of this iterator is [0, 10[ // i.e., 0<=i<10 var i("i", 0, 10); // Declare a computation that adds 3 and 4. This computation is done // within a loop that has i as iterator. computation S0({i}, 3 + 4); // Since the iterator i is declared to be 0<=i<10 (i.e., the iteration space of S0 is 0<=i<10), // the previous declaration of S0 is equivalent to the following C code // for (i = 0; i < 10; i++) // S0(i) = 3 + 4; // ------------------------------------------------------------ // Layer II: specify how the algorithm is optimized. // ------------------------------------------------------------ // Parallelize the loop level i S0.parallelize(i); // ------------------------------------------------------- // Layer III: allocate buffers and specify how computations // should be stored in these buffers. // ------------------------------------------------------- // Create a buffer called "buf0". buffer buf0("buf0", {10}, p_uint8, a_output); // The second argument to the constructor is a vector that represents the // size of the buffer dimensions. In this example, the vector has only one // element (which is expr(10)), therefore the buffer only has one dimension // of size 10. // The third argument is the type of the buffer elements (uint8). // The fourth argument indicates whether the buffer is in input or an output buffer. // Othr types are a_input (for input buffers) and a_temporary (for temporary buffers // allocated and freed within the function). // For more details about the constructor of buffers please refer to the // documentation https://tiramisu-compiler.github.io/doc/classtiramisu_1_1buffer.html // In general, all the API of Tiramisu is documented in https://tiramisu-compiler.github.io/doc/ // Store the computation S0 to the buffer buf0. // That is, store the computation S0(i) in buf0[i]. S0.store_in(&buf0); // ------------------------------------------------------- // Code Generation // ------------------------------------------------------- // Compile code and store it in an object file. Two arguments need // to be passed to the code generator: // - The arguments (buffers) passed to the generated function. // The buffer buf0 is supposed to be allocated by the user (caller) // and is supposed to be passed to the generated function "function0". // Any buffer of type a_output or a_input are supposed to be allocated // by the user (caller), in contrast to buffers of type a_temporary which are // allocated automatically by Tiramisu and should not be passed as arguments // to the function). // - The name of the object file to be generated. tiramisu::codegen({&buf0}, "build/generated_fct_developers_tutorial_01.o"); return 0; } /** If you want to compile the tutorial manuall, you can follow the following steps. Assuming that the variable TIRAMISU_ROOT contains the path to the root directory of Tiramisu and that Tiramisu and it dependences are built using the default paths. First we need to compile the generator (it requires the header files and libraries of Halide, ISL and Tiramisu which all should be built automatically if you follow the default installation process). cd ${TIRAMISU_ROOT}/build g++ -std=c++11 -fno-rtti -DHALIDE_NO_JPEG -I${TIRAMISU_ROOT}/include -I${TIRAMISU_ROOT}/3rdParty/isl/include/ -I${TIRAMISU_ROOT}/3rdParty/Halide/include -I${TIRAMISU_ROOT}/build -L${TIRAMISU_ROOT}/build -L${TIRAMISU_ROOT}/3rdParty/isl/ -L${TIRAMISU_ROOT}/3rdParty/Halide/lib/ -o developers_tutorial_01_fct_generator -ltiramisu -lisl -lHalide -ldl -lpthread -lz -lm -Wl,-rpath,${TIRAMISU_ROOT}/build ${TIRAMISU_ROOT}/tutorials/developers/tutorial_01/tutorial_01.cpp Run the generator to generate the object file. cd ${TIRAMISU_ROOT} ./build/developers_tutorial_01_fct_generator This generator generates the file generated_fct_developers_tutorial_01.o You can compile the wrapper code (code that uses the generated code) and link it to the generated object file. cd ${TIRAMISU_ROOT}/build g++ -std=c++11 -fno-rtti -I${TIRAMISU_ROOT}/include -I${TIRAMISU_ROOT}/3rdParty/Halide/include -L${TIRAMISU_ROOT}/build -L${TIRAMISU_ROOT}/3rdParty/Halide/lib/ -o wrapper_tutorial_01 -ltiramisu -lHalide -ldl -lpthread -lz -lm -Wl,-rpath,${TIRAMISU_ROOT}/build ${TIRAMISU_ROOT}/tutorials/developers/tutorial_01/wrapper_tutorial_01.cpp generated_fct_developers_tutorial_01.o To run the program. ./wrapper_tutorial_01 */ <|endoftext|>
<commit_before>//===--- ConstraintSimplificationTests.cpp --------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include "SemaFixture.h" #include "swift/Sema/ConstraintSystem.h" using namespace swift; using namespace swift::unittest; using namespace swift::constraints; TEST_F(SemaTest, TestTrailingClosureMatchRecordingForIdenticalFunctions) { ConstraintSystem cs(DC, ConstraintSystemOptions()); auto intType = getStdlibType("Int"); auto floatType = getStdlibType("Float"); auto func = FunctionType::get( {FunctionType::Param(intType), FunctionType::Param(intType)}, floatType); cs.addConstraint( ConstraintKind::ApplicableFunction, func, func, cs.getConstraintLocator({}, ConstraintLocator::ApplyFunction)); SmallVector<Solution, 2> solutions; cs.solve(solutions); ASSERT_EQ(solutions.size(), (unsigned)1); const auto &solution = solutions.front(); auto *locator = cs.getConstraintLocator({}, ConstraintLocator::ApplyArgument); auto choice = solution.argumentMatchingChoices.find(locator); ASSERT_TRUE(choice != solution.argumentMatchingChoices.end()); MatchCallArgumentResult expected{ TrailingClosureMatching::Forward, {{0}, {1}}, None}; ASSERT_EQ(choice->second, expected); } <commit_msg>[TypeChecker] NFC: Add a unittest for closure inference with optional contextual type<commit_after>//===--- ConstraintSimplificationTests.cpp --------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include "SemaFixture.h" #include "swift/AST/Decl.h" #include "swift/AST/Expr.h" #include "swift/AST/ParameterList.h" #include "swift/AST/Types.h" #include "swift/Sema/ConstraintSystem.h" using namespace swift; using namespace swift::unittest; using namespace swift::constraints; TEST_F(SemaTest, TestTrailingClosureMatchRecordingForIdenticalFunctions) { ConstraintSystem cs(DC, ConstraintSystemOptions()); auto intType = getStdlibType("Int"); auto floatType = getStdlibType("Float"); auto func = FunctionType::get( {FunctionType::Param(intType), FunctionType::Param(intType)}, floatType); cs.addConstraint( ConstraintKind::ApplicableFunction, func, func, cs.getConstraintLocator({}, ConstraintLocator::ApplyFunction)); SmallVector<Solution, 2> solutions; cs.solve(solutions); ASSERT_EQ(solutions.size(), (unsigned)1); const auto &solution = solutions.front(); auto *locator = cs.getConstraintLocator({}, ConstraintLocator::ApplyArgument); auto choice = solution.argumentMatchingChoices.find(locator); ASSERT_TRUE(choice != solution.argumentMatchingChoices.end()); MatchCallArgumentResult expected{ TrailingClosureMatching::Forward, {{0}, {1}}, None}; ASSERT_EQ(choice->second, expected); } /// Emulates code like this: /// /// func test(_: ((Int) -> Void)?) {} /// /// test { $0 } /// /// To make sure that closure resolution propagates contextual /// information into the body of the closure even when contextual /// type is wrapped in an optional. TEST_F(SemaTest, TestClosureInferenceFromOptionalContext) { ConstraintSystem cs(DC, ConstraintSystemOptions()); DeclAttributes closureAttrs; // Anonymous closure parameter auto paramName = Context.getIdentifier("0"); auto *paramDecl = new (Context) ParamDecl(/*specifierLoc=*/SourceLoc(), /*argumentNameLoc=*/SourceLoc(), paramName, /*parameterNameLoc=*/SourceLoc(), paramName, DC); paramDecl->setSpecifier(ParamSpecifier::Default); auto *closure = new (Context) ClosureExpr( closureAttrs, /*bracketRange=*/SourceRange(), /*capturedSelfDecl=*/nullptr, ParameterList::create(Context, {paramDecl}), /*asyncLoc=*/SourceLoc(), /*throwsLoc=*/SourceLoc(), /*arrowLoc=*/SourceLoc(), /*inLoc=*/SourceLoc(), /*explicitResultType=*/nullptr, /*discriminator=*/0, /*parent=*/DC); closure->setImplicit(); closure->setBody(BraceStmt::create(Context, /*startLoc=*/SourceLoc(), {}, /*endLoc=*/SourceLoc()), /*isSingleExpression=*/false); auto *closureLoc = cs.getConstraintLocator(closure); auto *paramTy = cs.createTypeVariable( cs.getConstraintLocator(closure, LocatorPathElt::TupleElement(0)), /*options=*/TVO_CanBindToInOut); auto *resultTy = cs.createTypeVariable( cs.getConstraintLocator(closure, ConstraintLocator::ClosureResult), /*options=*/0); auto extInfo = FunctionType::ExtInfo(); auto defaultTy = FunctionType::get({FunctionType::Param(paramTy, paramName)}, resultTy, extInfo); cs.setClosureType(closure, defaultTy); auto *closureTy = cs.createTypeVariable(closureLoc, /*options=*/0); cs.addUnsolvedConstraint(Constraint::create( cs, ConstraintKind::DefaultClosureType, closureTy, defaultTy, cs.getConstraintLocator(closure), /*referencedVars=*/{})); auto contextualTy = FunctionType::get({FunctionType::Param(getStdlibType("Int"))}, Context.TheEmptyTupleType, extInfo); // Try to resolve closure: // - external type `paramTy` should get bound to `Int`. // - result type should be bound to `Void`. cs.resolveClosure(closureTy, OptionalType::get(contextualTy), closureLoc); ASSERT_TRUE(cs.simplifyType(paramTy)->isEqual(getStdlibType("Int"))); ASSERT_TRUE(cs.simplifyType(resultTy)->isEqual(Context.TheEmptyTupleType)); } <|endoftext|>
<commit_before>/* QWebSockets implements the WebSocket protocol as defined in RFC 6455. Copyright (C) 2013 Kurt Pattyn (pattyn.kurt@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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /*! \class QWebSocketDataProcessor The class QWebSocketDataProcessor is responsible for reading, validating and interpreting data from a websocket. It reads data from a QIODevice, validates it against RFC 6455, and parses it into frames (data, control). It emits signals that correspond to the type of the frame: textFrameReceived(), binaryFrameReceived(), textMessageReceived(), binaryMessageReceived(), pingReceived(), pongReceived() and closeReceived(). Whenever an error is detected, the errorEncountered() signal is emitted. QWebSocketDataProcessor also checks if a frame is allowed in a sequence of frames (e.g. a continuation frame cannot follow a final frame). This class is an internal class used by QWebSocketInternal for data processing and validation. \sa Frame() \internal */ #include "qwebsocketdataprocessor_p.h" #include "qwebsocketprotocol.h" #include "qwebsocketframe_p.h" #include <QtEndian> #include <limits.h> #include <QTextCodec> #include <QTextDecoder> #include <QDebug> QT_BEGIN_NAMESPACE /*! \internal */ QWebSocketDataProcessor::QWebSocketDataProcessor(QObject *parent) : QObject(parent), m_processingState(PS_READ_HEADER), m_isFinalFrame(false), m_isFragmented(false), m_opCode(QWebSocketProtocol::OC_CLOSE), m_isControlFrame(false), m_hasMask(false), m_mask(0), m_binaryMessage(), m_textMessage(), m_payloadLength(0), m_pConverterState(0), m_pTextCodec(QTextCodec::codecForName("UTF-8")) { clear(); } /*! \internal */ QWebSocketDataProcessor::~QWebSocketDataProcessor() { clear(); if (m_pConverterState) { delete m_pConverterState; m_pConverterState = 0; } } /*! \internal */ quint64 QWebSocketDataProcessor::maxMessageSize() { return MAX_MESSAGE_SIZE_IN_BYTES; } /*! \internal */ quint64 QWebSocketDataProcessor::maxFrameSize() { return MAX_FRAME_SIZE_IN_BYTES; } /*! \internal */ void QWebSocketDataProcessor::process(QIODevice *pIoDevice) { bool isDone = false; while (!isDone) { QWebSocketFrame frame = QWebSocketFrame::readFrame(pIoDevice); if (frame.isValid()) { if (frame.isControlFrame()) { isDone = processControlFrame(frame); } else //we have a dataframe; opcode can be OC_CONTINUE, OC_TEXT or OC_BINARY { if (!m_isFragmented && frame.isContinuationFrame()) { clear(); Q_EMIT errorEncountered(QWebSocketProtocol::CC_PROTOCOL_ERROR, tr("Received Continuation frame, while there is nothing to continue.")); return; } if (m_isFragmented && frame.isDataFrame() && !frame.isContinuationFrame()) { clear(); Q_EMIT errorEncountered(QWebSocketProtocol::CC_PROTOCOL_ERROR, tr("All data frames after the initial data frame must have opcode 0 (continuation).")); return; } if (!frame.isContinuationFrame()) { m_opCode = frame.getOpCode(); m_isFragmented = !frame.isFinalFrame(); } quint64 messageLength = (quint64)(m_opCode == QWebSocketProtocol::OC_TEXT) ? m_textMessage.length() : m_binaryMessage.length(); if ((messageLength + quint64(frame.getPayload().length())) > MAX_MESSAGE_SIZE_IN_BYTES) { clear(); Q_EMIT errorEncountered(QWebSocketProtocol::CC_TOO_MUCH_DATA, tr("Received message is too big.")); return; } if (m_opCode == QWebSocketProtocol::OC_TEXT) { QString frameTxt = m_pTextCodec->toUnicode(frame.getPayload().constData(), frame.getPayload().size(), m_pConverterState); bool failed = (m_pConverterState->invalidChars != 0) || (frame.isFinalFrame() && (m_pConverterState->remainingChars != 0)); if (failed) { clear(); Q_EMIT errorEncountered(QWebSocketProtocol::CC_WRONG_DATATYPE, tr("Invalid UTF-8 code encountered.")); return; } else { m_textMessage.append(frameTxt); Q_EMIT textFrameReceived(frameTxt, frame.isFinalFrame()); } } else { m_binaryMessage.append(frame.getPayload()); Q_EMIT binaryFrameReceived(frame.getPayload(), frame.isFinalFrame()); } if (frame.isFinalFrame()) { if (m_opCode == QWebSocketProtocol::OC_TEXT) { Q_EMIT textMessageReceived(m_textMessage); } else { Q_EMIT binaryMessageReceived(m_binaryMessage); } clear(); isDone = true; } } } else { Q_EMIT errorEncountered(frame.getCloseCode(), frame.getCloseReason()); clear(); isDone = true; } } } /*! \internal */ void QWebSocketDataProcessor::clear() { m_processingState = PS_READ_HEADER; m_isFinalFrame = false; m_isFragmented = false; m_opCode = QWebSocketProtocol::OC_CLOSE; m_hasMask = false; m_mask = 0; m_binaryMessage.clear(); m_textMessage.clear(); m_payloadLength = 0; if (m_pConverterState) { if ((m_pConverterState->remainingChars != 0) || (m_pConverterState->invalidChars != 0)) { delete m_pConverterState; m_pConverterState = 0; } } if (!m_pConverterState) { m_pConverterState = new QTextCodec::ConverterState(QTextCodec::ConvertInvalidToNull | QTextCodec::IgnoreHeader); } } /*! \internal */ bool QWebSocketDataProcessor::processControlFrame(const QWebSocketFrame &frame) { bool mustStopProcessing = false; switch (frame.getOpCode()) { case QWebSocketProtocol::OC_PING: { Q_EMIT pingReceived(frame.getPayload()); break; } case QWebSocketProtocol::OC_PONG: { Q_EMIT pongReceived(frame.getPayload()); break; } case QWebSocketProtocol::OC_CLOSE: { quint16 closeCode = QWebSocketProtocol::CC_NORMAL; QString closeReason; QByteArray payload = frame.getPayload(); if (payload.size() == 1) //size is either 0 (no close code and no reason) or >= 2 (at least a close code of 2 bytes) { closeCode = QWebSocketProtocol::CC_PROTOCOL_ERROR; closeReason = tr("Payload of close frame is too small."); } else if (payload.size() > 1) //close frame can have a close code and reason { closeCode = qFromBigEndian<quint16>(reinterpret_cast<const uchar *>(payload.constData())); if (!QWebSocketProtocol::isCloseCodeValid(closeCode)) { closeCode = QWebSocketProtocol::CC_PROTOCOL_ERROR; closeReason = tr("Invalid close code %1 detected.").arg(closeCode); } else { if (payload.size() > 2) { QTextCodec *tc = QTextCodec::codecForName("UTF-8"); QTextCodec::ConverterState state(QTextCodec::ConvertInvalidToNull); closeReason = tc->toUnicode(payload.constData() + 2, payload.size() - 2, &state); bool failed = (state.invalidChars != 0) || (state.remainingChars != 0); if (failed) { closeCode = QWebSocketProtocol::CC_WRONG_DATATYPE; closeReason = tr("Invalid UTF-8 code encountered."); } } } } mustStopProcessing = true; Q_EMIT closeReceived(static_cast<QWebSocketProtocol::CloseCode>(closeCode), closeReason); break; } case QWebSocketProtocol::OC_CONTINUE: case QWebSocketProtocol::OC_BINARY: case QWebSocketProtocol::OC_TEXT: case QWebSocketProtocol::OC_RESERVED_3: case QWebSocketProtocol::OC_RESERVED_4: case QWebSocketProtocol::OC_RESERVED_5: case QWebSocketProtocol::OC_RESERVED_6: case QWebSocketProtocol::OC_RESERVED_7: case QWebSocketProtocol::OC_RESERVED_C: case QWebSocketProtocol::OC_RESERVED_B: case QWebSocketProtocol::OC_RESERVED_D: case QWebSocketProtocol::OC_RESERVED_E: case QWebSocketProtocol::OC_RESERVED_F: { //do nothing //case added to make C++ compiler happy break; } default: { qDebug() << "DataProcessor::processControlFrame: Invalid opcode detected:" << static_cast<int>(frame.getOpCode()); //Do nothing break; } } return mustStopProcessing; } QT_END_NAMESPACE <commit_msg>Immediately stop processing after reception of a control frame<commit_after>/* QWebSockets implements the WebSocket protocol as defined in RFC 6455. Copyright (C) 2013 Kurt Pattyn (pattyn.kurt@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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /*! \class QWebSocketDataProcessor The class QWebSocketDataProcessor is responsible for reading, validating and interpreting data from a websocket. It reads data from a QIODevice, validates it against RFC 6455, and parses it into frames (data, control). It emits signals that correspond to the type of the frame: textFrameReceived(), binaryFrameReceived(), textMessageReceived(), binaryMessageReceived(), pingReceived(), pongReceived() and closeReceived(). Whenever an error is detected, the errorEncountered() signal is emitted. QWebSocketDataProcessor also checks if a frame is allowed in a sequence of frames (e.g. a continuation frame cannot follow a final frame). This class is an internal class used by QWebSocketInternal for data processing and validation. \sa Frame() \internal */ #include "qwebsocketdataprocessor_p.h" #include "qwebsocketprotocol.h" #include "qwebsocketframe_p.h" #include <QtEndian> #include <limits.h> #include <QTextCodec> #include <QTextDecoder> #include <QDebug> QT_BEGIN_NAMESPACE /*! \internal */ QWebSocketDataProcessor::QWebSocketDataProcessor(QObject *parent) : QObject(parent), m_processingState(PS_READ_HEADER), m_isFinalFrame(false), m_isFragmented(false), m_opCode(QWebSocketProtocol::OC_CLOSE), m_isControlFrame(false), m_hasMask(false), m_mask(0), m_binaryMessage(), m_textMessage(), m_payloadLength(0), m_pConverterState(0), m_pTextCodec(QTextCodec::codecForName("UTF-8")) { clear(); } /*! \internal */ QWebSocketDataProcessor::~QWebSocketDataProcessor() { clear(); if (m_pConverterState) { delete m_pConverterState; m_pConverterState = 0; } } /*! \internal */ quint64 QWebSocketDataProcessor::maxMessageSize() { return MAX_MESSAGE_SIZE_IN_BYTES; } /*! \internal */ quint64 QWebSocketDataProcessor::maxFrameSize() { return MAX_FRAME_SIZE_IN_BYTES; } /*! \internal */ void QWebSocketDataProcessor::process(QIODevice *pIoDevice) { bool isDone = false; while (!isDone) { QWebSocketFrame frame = QWebSocketFrame::readFrame(pIoDevice); if (frame.isValid()) { if (frame.isControlFrame()) { isDone = processControlFrame(frame); } else //we have a dataframe; opcode can be OC_CONTINUE, OC_TEXT or OC_BINARY { if (!m_isFragmented && frame.isContinuationFrame()) { clear(); Q_EMIT errorEncountered(QWebSocketProtocol::CC_PROTOCOL_ERROR, tr("Received Continuation frame, while there is nothing to continue.")); return; } if (m_isFragmented && frame.isDataFrame() && !frame.isContinuationFrame()) { clear(); Q_EMIT errorEncountered(QWebSocketProtocol::CC_PROTOCOL_ERROR, tr("All data frames after the initial data frame must have opcode 0 (continuation).")); return; } if (!frame.isContinuationFrame()) { m_opCode = frame.getOpCode(); m_isFragmented = !frame.isFinalFrame(); } quint64 messageLength = (quint64)(m_opCode == QWebSocketProtocol::OC_TEXT) ? m_textMessage.length() : m_binaryMessage.length(); if ((messageLength + quint64(frame.getPayload().length())) > MAX_MESSAGE_SIZE_IN_BYTES) { clear(); Q_EMIT errorEncountered(QWebSocketProtocol::CC_TOO_MUCH_DATA, tr("Received message is too big.")); return; } if (m_opCode == QWebSocketProtocol::OC_TEXT) { QString frameTxt = m_pTextCodec->toUnicode(frame.getPayload().constData(), frame.getPayload().size(), m_pConverterState); bool failed = (m_pConverterState->invalidChars != 0) || (frame.isFinalFrame() && (m_pConverterState->remainingChars != 0)); if (failed) { clear(); Q_EMIT errorEncountered(QWebSocketProtocol::CC_WRONG_DATATYPE, tr("Invalid UTF-8 code encountered.")); return; } else { m_textMessage.append(frameTxt); Q_EMIT textFrameReceived(frameTxt, frame.isFinalFrame()); } } else { m_binaryMessage.append(frame.getPayload()); Q_EMIT binaryFrameReceived(frame.getPayload(), frame.isFinalFrame()); } if (frame.isFinalFrame()) { if (m_opCode == QWebSocketProtocol::OC_TEXT) { Q_EMIT textMessageReceived(m_textMessage); } else { Q_EMIT binaryMessageReceived(m_binaryMessage); } clear(); isDone = true; } } } else { Q_EMIT errorEncountered(frame.getCloseCode(), frame.getCloseReason()); clear(); isDone = true; } } } /*! \internal */ void QWebSocketDataProcessor::clear() { m_processingState = PS_READ_HEADER; m_isFinalFrame = false; m_isFragmented = false; m_opCode = QWebSocketProtocol::OC_CLOSE; m_hasMask = false; m_mask = 0; m_binaryMessage.clear(); m_textMessage.clear(); m_payloadLength = 0; if (m_pConverterState) { if ((m_pConverterState->remainingChars != 0) || (m_pConverterState->invalidChars != 0)) { delete m_pConverterState; m_pConverterState = 0; } } if (!m_pConverterState) { m_pConverterState = new QTextCodec::ConverterState(QTextCodec::ConvertInvalidToNull | QTextCodec::IgnoreHeader); } } /*! \internal */ bool QWebSocketDataProcessor::processControlFrame(const QWebSocketFrame &frame) { bool mustStopProcessing = true; //control frames never expect additional frames to be processed switch (frame.getOpCode()) { case QWebSocketProtocol::OC_PING: { Q_EMIT pingReceived(frame.getPayload()); break; } case QWebSocketProtocol::OC_PONG: { Q_EMIT pongReceived(frame.getPayload()); break; } case QWebSocketProtocol::OC_CLOSE: { quint16 closeCode = QWebSocketProtocol::CC_NORMAL; QString closeReason; QByteArray payload = frame.getPayload(); if (payload.size() == 1) //size is either 0 (no close code and no reason) or >= 2 (at least a close code of 2 bytes) { closeCode = QWebSocketProtocol::CC_PROTOCOL_ERROR; closeReason = tr("Payload of close frame is too small."); } else if (payload.size() > 1) //close frame can have a close code and reason { closeCode = qFromBigEndian<quint16>(reinterpret_cast<const uchar *>(payload.constData())); if (!QWebSocketProtocol::isCloseCodeValid(closeCode)) { closeCode = QWebSocketProtocol::CC_PROTOCOL_ERROR; closeReason = tr("Invalid close code %1 detected.").arg(closeCode); } else { if (payload.size() > 2) { QTextCodec *tc = QTextCodec::codecForName("UTF-8"); QTextCodec::ConverterState state(QTextCodec::ConvertInvalidToNull); closeReason = tc->toUnicode(payload.constData() + 2, payload.size() - 2, &state); bool failed = (state.invalidChars != 0) || (state.remainingChars != 0); if (failed) { closeCode = QWebSocketProtocol::CC_WRONG_DATATYPE; closeReason = tr("Invalid UTF-8 code encountered."); } } } } Q_EMIT closeReceived(static_cast<QWebSocketProtocol::CloseCode>(closeCode), closeReason); break; } case QWebSocketProtocol::OC_CONTINUE: case QWebSocketProtocol::OC_BINARY: case QWebSocketProtocol::OC_TEXT: case QWebSocketProtocol::OC_RESERVED_3: case QWebSocketProtocol::OC_RESERVED_4: case QWebSocketProtocol::OC_RESERVED_5: case QWebSocketProtocol::OC_RESERVED_6: case QWebSocketProtocol::OC_RESERVED_7: case QWebSocketProtocol::OC_RESERVED_C: case QWebSocketProtocol::OC_RESERVED_B: case QWebSocketProtocol::OC_RESERVED_D: case QWebSocketProtocol::OC_RESERVED_E: case QWebSocketProtocol::OC_RESERVED_F: { //do nothing //case added to make C++ compiler happy break; } default: { qDebug() << "DataProcessor::processControlFrame: Invalid opcode detected:" << static_cast<int>(frame.getOpCode()); //Do nothing break; } } return mustStopProcessing; } QT_END_NAMESPACE <|endoftext|>
<commit_before>#include "warnings-disable.h" WARNINGS_DISABLE #include <QtTest/QtTest> WARNINGS_ENABLE #include "../qtest-platform.h" #include "app-cmdline.h" #include "persistentmodel/persistentstore.h" #include <TSettings.h> extern "C" { #include "optparse.h" WARNINGS_DISABLE #include "warnp.h" WARNINGS_ENABLE } class TestCmdline : public QObject { Q_OBJECT private slots: void initTestCase(); void init(); void cleanupTestCase(); void normal_init(); void appdir_init(); }; void TestCmdline::initTestCase() { QCoreApplication::setOrganizationName(TEST_NAME); HANDLE_IGNORING_XDG_HOME; // Initialize debug messages. const char *argv[] = {"test-cmdline"}; WARNP_INIT; } void TestCmdline::init() { // Reset TSettings TSettings::destroy(); // Reset PersistentStore PersistentStore::deinit(); PersistentStore::destroy(); } void TestCmdline::cleanupTestCase() { TSettings::destroy(); } void TestCmdline::normal_init() { struct optparse *opt; // Create command-line arguments int argc = 1; char *argv[1]; argv[0] = strdup("./test-cmdline"); // Parse command-line arguments if((opt = optparse_parse(argc, argv)) == nullptr) QVERIFY(opt != nullptr); // This scope is how we do it in main.cpp { // Basic initialization that cannot fail. AppCmdline app(argc, argv, opt); // Run more complicated initialization. if(!app.initializeCore()) QFAIL("Could not initialize app"); } // Check that it read the right config file. TSettings settings; QVERIFY(settings.value("tarsnap/user", "") == "normal_init"); // Clean up optparse_free(opt); free(argv[0]); } void TestCmdline::appdir_init() { struct optparse *opt; // Create command-line arguments int argc = 3; char *argv[3]; argv[0] = strdup("./test-cmdline"); argv[1] = strdup("--appdata"); argv[2] = strdup("confdir"); // Parse command-line arguments if((opt = optparse_parse(argc, argv)) == nullptr) QVERIFY(opt != nullptr); // This scope is how we do it in main.cpp { // Basic initialization that cannot fail. AppCmdline app(argc, argv, opt); // Run more complicated initialization. if(!app.initializeCore()) QFAIL("Could not initialize app"); } // Check that it read the right config file. TSettings settings; QVERIFY(settings.value("tarsnap/user", "") == "appdata_init"); // Clean up optparse_free(opt); free(argv[0]); free(argv[1]); free(argv[2]); } QTEST_MAIN(TestCmdline) #include "test-cmdline.moc" <commit_msg>tests/cmdline: use init_shared_free()<commit_after>#include "warnings-disable.h" WARNINGS_DISABLE #include <QtTest/QtTest> WARNINGS_ENABLE #include "../qtest-platform.h" #include "app-cmdline.h" #include "init-shared.h" #include "persistentmodel/persistentstore.h" #include <TSettings.h> extern "C" { #include "optparse.h" WARNINGS_DISABLE #include "warnp.h" WARNINGS_ENABLE } class TestCmdline : public QObject { Q_OBJECT private slots: void initTestCase(); void normal_init(); void appdir_init(); }; void TestCmdline::initTestCase() { QCoreApplication::setOrganizationName(TEST_NAME); HANDLE_IGNORING_XDG_HOME; // Initialize debug messages. const char *argv[] = {"test-cmdline"}; WARNP_INIT; } void TestCmdline::normal_init() { struct optparse *opt; // Create command-line arguments int argc = 1; char *argv[1]; argv[0] = strdup("./test-cmdline"); // Parse command-line arguments if((opt = optparse_parse(argc, argv)) == nullptr) QVERIFY(opt != nullptr); // This scope is how we do it in main.cpp { // Basic initialization that cannot fail. AppCmdline app(argc, argv, opt); // Run more complicated initialization. if(!app.initializeCore()) QFAIL("Could not initialize app"); } // Check that it read the right config file. TSettings settings; QVERIFY(settings.value("tarsnap/user", "") == "normal_init"); // Clean up PersistentStore::deinit(); init_shared_free(); optparse_free(opt); free(argv[0]); } void TestCmdline::appdir_init() { struct optparse *opt; // Create command-line arguments int argc = 3; char *argv[3]; argv[0] = strdup("./test-cmdline"); argv[1] = strdup("--appdata"); argv[2] = strdup("confdir"); // Parse command-line arguments if((opt = optparse_parse(argc, argv)) == nullptr) QVERIFY(opt != nullptr); // This scope is how we do it in main.cpp { // Basic initialization that cannot fail. AppCmdline app(argc, argv, opt); // Run more complicated initialization. if(!app.initializeCore()) QFAIL("Could not initialize app"); } // Check that it read the right config file. TSettings settings; QVERIFY(settings.value("tarsnap/user", "") == "appdata_init"); // Clean up PersistentStore::deinit(); init_shared_free(); optparse_free(opt); free(argv[0]); free(argv[1]); free(argv[2]); } QTEST_MAIN(TestCmdline) #include "test-cmdline.moc" <|endoftext|>
<commit_before>#if 0 #include "Format.h" //#include "Format_memory.h" //#include "Format_ostream.h" //#include "Format_pretty.h" //#include "Format_string.h" //#include <cstdio> //#include <iosfwd> //#include <memory> //#include <string> //#include <string_view> //#include <type_traits> int main() {} #else #define HAS_FMTLIB 0 #include "Format.h" #include "Format_memory.h" //#include "Format_ostream.h" //#include "Format_pretty.h" #include "Format_string.h" #if HAS_FMTLIB #define FMT_HEADER_ONLY 1 #include "../ext/fmt/format.h" #endif #include "benchmark/benchmark.h" #include <cstdint> #include <iostream> #include <iterator> #include <random> #include <sstream> template <typename ...Args> static void Format(char const* format, Args const&... args) { //char buf[8 * 1024]; //int const size = fmtxx::snformat(buf, format, args...); //assert(size >= 0); //std::fwrite(buf, 1, static_cast<int>(size), stderr); fmtxx::MemoryWriter<> w; fmtxx::format(w, format, args...); std::fwrite(w.data(), 1, w.size(), stderr); //fmtxx::format(std::cerr, format, args...); //fmtxx::format(stderr, format, args...); //auto const str = fmtxx::sformat(format, args...); //std::fwrite(str.data(), 1, str.size(), stderr); //fmt::print(stderr, format, args...); } #if 1 static void warm_up(benchmark::State& state) { while (state.KeepRunning()) Format("{}", 123); } BENCHMARK(warm_up); BENCHMARK(warm_up); BENCHMARK(warm_up); #endif #if 0 // -------------------------------------------------------------- TEST_INT #define TEST_INT(NAME, T, FORMAT) \ static void test_##NAME(benchmark::State& state) \ { \ std::mt19937 rng; \ std::uniform_int_distribution<T> dist; \ \ while (state.KeepRunning()) \ Format(FORMAT, dist(rng)); \ } \ BENCHMARK(test_##NAME); \ /**/ //TEST_INT(int32, int32_t, "{}"); //TEST_INT(int32_pad08, int32_t, "{:08}"); //TEST_INT(int32_pad32, int32_t, "{:32}"); //TEST_INT(int32_pad64, int32_t, "{:64}"); //TEST_INT(int32_pad32_l, int32_t, "{:<32}"); //TEST_INT(int32_pad64_l, int32_t, "{:<64}"); //TEST_INT(int32_x, int32_t, "{:x}"); //TEST_INT(int32_x_pad08, int32_t, "{:08x}"); //TEST_INT(int32_x_pad32, int32_t, "{:32x}"); //TEST_INT(int32_x_pad64, int32_t, "{:64x}"); TEST_INT(int64, int64_t, "{}"); TEST_INT(int64_pad08, int64_t, "{:08}"); TEST_INT(int64_pad32, int64_t, "{:32}"); TEST_INT(int64_pad64, int64_t, "{:64}"); TEST_INT(int64_pad32_l, int64_t, "{:<32}"); TEST_INT(int64_pad64_l, int64_t, "{:<64}"); TEST_INT(int64_x, int64_t, "{:x}"); TEST_INT(int64_x_pad08, int64_t, "{:08x}"); TEST_INT(int64_x_pad32, int64_t, "{:32x}"); TEST_INT(int64_x_pad64, int64_t, "{:64x}"); //TEST_INT(uint32, uint32_t, "{}"); //TEST_INT(uint32_x, uint32_t, "{:x}"); // //TEST_INT(uint64, uint64_t, "{}"); //TEST_INT(uint64_x, uint64_t, "{:x}"); #endif #if 0 // -------------------------------------------------------- TEST_MULTI_INT #define ARGS_1 "hello {}" #define ARGS_2 ARGS_1 ARGS_1 #define ARGS_4 ARGS_2 ARGS_2 #define ARGS_8 ARGS_4 ARGS_4 #define ARGS_16 ARGS_8 ARGS_8 #if 0 #define TEST_MULTI_INT4(NAME, T, FORMAT) \ static void test_##NAME (benchmark::State& state) \ { \ std::mt19937 rng; \ std::uniform_int_distribution<T> dist; \ \ while (state.KeepRunning()) \ Format(FORMAT, dist(rng), dist(rng), dist(rng), dist(rng)); \ } \ BENCHMARK(test_##NAME); \ /**/ TEST_MULTI_INT4(int32_multi4, int32_t, ARGS_4); TEST_MULTI_INT4(int64_multi4, int64_t, ARGS_4); #define TEST_MULTI_INT8(NAME, T, FORMAT) \ static void test_##NAME (benchmark::State& state) \ { \ std::mt19937 rng; \ std::uniform_int_distribution<T> dist; \ \ while (state.KeepRunning()) \ Format(FORMAT, dist(rng), dist(rng), dist(rng), dist(rng), \ dist(rng), dist(rng), dist(rng), dist(rng)); \ } \ BENCHMARK(test_##NAME); \ /**/ TEST_MULTI_INT8(int32_multi8, int32_t, ARGS_8); TEST_MULTI_INT8(int64_multi8, int64_t, ARGS_8); #endif #define TEST_MULTI_INT16(NAME, T, FORMAT) \ static void test_##NAME (benchmark::State& state) \ { \ std::mt19937 rng; \ std::uniform_int_distribution<T> dist; \ \ while (state.KeepRunning()) \ Format(FORMAT, dist(rng), dist(rng), dist(rng), dist(rng), \ dist(rng), dist(rng), dist(rng), dist(rng), \ dist(rng), dist(rng), dist(rng), dist(rng), \ dist(rng), dist(rng), dist(rng), dist(rng)); \ } \ BENCHMARK(test_##NAME); \ /**/ TEST_MULTI_INT16(int32_multi16, int32_t, ARGS_16); TEST_MULTI_INT16(int64_multi16, int64_t, ARGS_16); #endif #if 0 // ---------------------------------------------------- TEST_MULTI_INT_x16 #define TEST_MULTI_INT_x16(NAME, T, FORMAT) \ static void test_##NAME (benchmark::State& state) \ { \ std::mt19937 rng; \ std::uniform_int_distribution<T> dist; \ \ while (state.KeepRunning()) \ { \ Format(FORMAT, dist(rng)); \ Format(FORMAT, dist(rng)); \ Format(FORMAT, dist(rng)); \ Format(FORMAT, dist(rng)); \ Format(FORMAT, dist(rng)); \ Format(FORMAT, dist(rng)); \ Format(FORMAT, dist(rng)); \ Format(FORMAT, dist(rng)); \ Format(FORMAT, dist(rng)); \ Format(FORMAT, dist(rng)); \ Format(FORMAT, dist(rng)); \ Format(FORMAT, dist(rng)); \ Format(FORMAT, dist(rng)); \ Format(FORMAT, dist(rng)); \ Format(FORMAT, dist(rng)); \ Format(FORMAT, dist(rng)); \ } \ } \ BENCHMARK(test_##NAME); \ /**/ TEST_MULTI_INT_x16(int32_multi_x16, int32_t, "hello {}"); TEST_MULTI_INT_x16(int64_multi_x16, int64_t, "hello {}"); #endif #if 1 // ------------------------------------------------------------ TEST_FLOAT static void test_genfloats(benchmark::State& state) { std::mt19937 rng; std::uniform_real_distribution<double> dist(0, std::numeric_limits<double>::max()); while (state.KeepRunning()) benchmark::DoNotOptimize( dist(rng) ); } BENCHMARK(test_genfloats); BENCHMARK(test_genfloats); BENCHMARK(test_genfloats); #define TEST_FLOAT(NAME, T, FORMAT) \ static void test_##NAME (benchmark::State& state) \ { \ std::mt19937 rng; \ std::uniform_real_distribution<T> dist(0, std::numeric_limits<T>::max()); \ \ while (state.KeepRunning()) \ Format(FORMAT, dist(rng)); \ } \ BENCHMARK(test_##NAME); \ /**/ TEST_FLOAT(double, double, "{}"); //TEST_FLOAT(double_x, double, "{:x}"); //TEST_FLOAT(double_f, double, "{:f}"); //TEST_FLOAT(double_e, double, "{:e}"); //TEST_FLOAT(double_g, double, "{:g}"); //TEST_FLOAT(double_a, double, "{:a}"); TEST_FLOAT(double_f_17, double, "{:.17f}"); TEST_FLOAT(double_e_17, double, "{:.17e}"); TEST_FLOAT(double_g_17, double, "{:.17g}"); TEST_FLOAT(double_a_17, double, "{:.17a}"); #endif #define STRING_1 "Hello" #define STRING_2 "I'm sorry Dave. I'm afraid I can't do that." #define STRING_3 \ "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod " \ "tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At " \ "vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, " \ "no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit " \ "amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut " \ "labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam " \ "et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata " \ "sanctus est Lorem ipsum dolor sit amet." #if 0 // ----------------------------------------------------------- TEST_STRING #define TEST_STRING(NAME, FORMAT, ...) \ static void test_##NAME (benchmark::State& state) \ { \ while (state.KeepRunning()) \ Format(FORMAT, __VA_ARGS__); \ } \ BENCHMARK(test_##NAME); /**/ TEST_STRING(str_1, "{}", STRING_1); TEST_STRING(str_2, "{}", STRING_2); TEST_STRING(str_3, "{}", STRING_3); TEST_STRING(str_1_2, "{} {}", STRING_1, STRING_1); TEST_STRING(str_2_2, "{} {}", STRING_2, STRING_2); TEST_STRING(str_3_2, "{} {}", STRING_3, STRING_3); TEST_STRING(str_1_3, "{0} {0}", STRING_1); TEST_STRING(str_2_3, "{0} {0}", STRING_2); TEST_STRING(str_3_3, "{0} {0}", STRING_3); //TEST_STRING(stdstr_1, "{}", std::string{STRING_1}); //TEST_STRING(stdstr_2, "{}", std::string{STRING_2}); //TEST_STRING(stdstr_3, "{}", std::string{STRING_3}); //TEST_STRING(stdstr_1_2, "{} {}", std::string{STRING_1}, std::string{STRING_1}); //TEST_STRING(stdstr_2_2, "{} {}", std::string{STRING_2}, std::string{STRING_2}); //TEST_STRING(stdstr_3_2, "{} {}", std::string{STRING_3}, std::string{STRING_3}); //TEST_STRING(stdstr_1_3, "{0} {0}", std::string{STRING_1}); //TEST_STRING(stdstr_2_3, "{0} {0}", std::string{STRING_2}); //TEST_STRING(stdstr_3_3, "{0} {0}", std::string{STRING_3}); #endif #if 0 // --------------------------------------------------------- TEST_CUSTOM_1 struct MyString { char const* str; }; namespace fmtxx { template <> struct FormatValue<MyString> { errc operator()(Writer& w, FormatSpec const& spec, MyString const& s) const { return fmtxx::Util::format_string(w, spec, s.str); } }; } #define TEST_CUSTOM_1(NAME, FORMAT, ...) \ static void test_##NAME (benchmark::State& state) \ { \ while (state.KeepRunning()) \ Format(FORMAT, __VA_ARGS__); \ } \ BENCHMARK(test_##NAME); /**/ TEST_CUSTOM_1(custom_str_1, "{}", MyString{STRING_1}); TEST_CUSTOM_1(custom_str_2, "{}", MyString{STRING_2}); TEST_CUSTOM_1(custom_str_3, "{}", MyString{STRING_3}); TEST_CUSTOM_1(custom_str_1_2, "{} {}", MyString{STRING_1}, MyString{STRING_1}); TEST_CUSTOM_1(custom_str_2_2, "{} {}", MyString{STRING_2}, MyString{STRING_2}); TEST_CUSTOM_1(custom_str_3_2, "{} {}", MyString{STRING_3}, MyString{STRING_3}); TEST_CUSTOM_1(custom_str_1_3, "{0} {0}", MyString{STRING_1}); TEST_CUSTOM_1(custom_str_2_3, "{0} {0}", MyString{STRING_2}); TEST_CUSTOM_1(custom_str_3_3, "{0} {0}", MyString{STRING_3}); #endif int main(int argc, char* argv[]) { const size_t iobuf_size = 64 * 1024 * 1024; char* iobuf = static_cast<char*>(malloc(iobuf_size)); std::ios_base::sync_with_stdio(false); setvbuf(stderr, iobuf, _IOFBF, iobuf_size); benchmark::Initialize(&argc, argv); if (benchmark::ReportUnrecognizedArguments(argc, argv)) return 1; benchmark::RunSpecifiedBenchmarks(); return 0; } #endif <commit_msg>Compile fix<commit_after>#if 0 #include "Format.h" //#include "Format_memory.h" //#include "Format_ostream.h" //#include "Format_pretty.h" //#include "Format_string.h" //#include <cstdio> //#include <iosfwd> //#include <memory> //#include <string> //#include <string_view> //#include <type_traits> int main() {} #else #define HAS_FMTLIB 0 #include "Format.h" #include "Format_memory.h" //#include "Format_ostream.h" #if HAS_FMTLIB #define FMT_HEADER_ONLY 1 #include "../ext/fmt/format.h" #endif #include "benchmark/benchmark.h" #include <cstdint> #include <iostream> #include <iterator> #include <random> #include <sstream> template <typename ...Args> static void Format(char const* format, Args const&... args) { //char buf[8 * 1024]; //int const size = fmtxx::snformat(buf, format, args...); //assert(size >= 0); //std::fwrite(buf, 1, static_cast<int>(size), stderr); fmtxx::MemoryWriter<> w; fmtxx::format(w, format, args...); std::fwrite(w.data(), 1, w.size(), stderr); //fmtxx::format(std::cerr, format, args...); //fmtxx::format(stderr, format, args...); //auto const str = fmtxx::sformat(format, args...); //std::fwrite(str.data(), 1, str.size(), stderr); //fmt::print(stderr, format, args...); } #if 1 static void warm_up(benchmark::State& state) { while (state.KeepRunning()) Format("{}", 123); } BENCHMARK(warm_up); BENCHMARK(warm_up); BENCHMARK(warm_up); #endif #if 0 // -------------------------------------------------------------- TEST_INT #define TEST_INT(NAME, T, FORMAT) \ static void test_##NAME(benchmark::State& state) \ { \ std::mt19937 rng; \ std::uniform_int_distribution<T> dist; \ \ while (state.KeepRunning()) \ Format(FORMAT, dist(rng)); \ } \ BENCHMARK(test_##NAME); \ /**/ //TEST_INT(int32, int32_t, "{}"); //TEST_INT(int32_pad08, int32_t, "{:08}"); //TEST_INT(int32_pad32, int32_t, "{:32}"); //TEST_INT(int32_pad64, int32_t, "{:64}"); //TEST_INT(int32_pad32_l, int32_t, "{:<32}"); //TEST_INT(int32_pad64_l, int32_t, "{:<64}"); //TEST_INT(int32_x, int32_t, "{:x}"); //TEST_INT(int32_x_pad08, int32_t, "{:08x}"); //TEST_INT(int32_x_pad32, int32_t, "{:32x}"); //TEST_INT(int32_x_pad64, int32_t, "{:64x}"); TEST_INT(int64, int64_t, "{}"); TEST_INT(int64_pad08, int64_t, "{:08}"); TEST_INT(int64_pad32, int64_t, "{:32}"); TEST_INT(int64_pad64, int64_t, "{:64}"); TEST_INT(int64_pad32_l, int64_t, "{:<32}"); TEST_INT(int64_pad64_l, int64_t, "{:<64}"); TEST_INT(int64_x, int64_t, "{:x}"); TEST_INT(int64_x_pad08, int64_t, "{:08x}"); TEST_INT(int64_x_pad32, int64_t, "{:32x}"); TEST_INT(int64_x_pad64, int64_t, "{:64x}"); //TEST_INT(uint32, uint32_t, "{}"); //TEST_INT(uint32_x, uint32_t, "{:x}"); // //TEST_INT(uint64, uint64_t, "{}"); //TEST_INT(uint64_x, uint64_t, "{:x}"); #endif #if 0 // -------------------------------------------------------- TEST_MULTI_INT #define ARGS_1 "hello {}" #define ARGS_2 ARGS_1 ARGS_1 #define ARGS_4 ARGS_2 ARGS_2 #define ARGS_8 ARGS_4 ARGS_4 #define ARGS_16 ARGS_8 ARGS_8 #if 0 #define TEST_MULTI_INT4(NAME, T, FORMAT) \ static void test_##NAME (benchmark::State& state) \ { \ std::mt19937 rng; \ std::uniform_int_distribution<T> dist; \ \ while (state.KeepRunning()) \ Format(FORMAT, dist(rng), dist(rng), dist(rng), dist(rng)); \ } \ BENCHMARK(test_##NAME); \ /**/ TEST_MULTI_INT4(int32_multi4, int32_t, ARGS_4); TEST_MULTI_INT4(int64_multi4, int64_t, ARGS_4); #define TEST_MULTI_INT8(NAME, T, FORMAT) \ static void test_##NAME (benchmark::State& state) \ { \ std::mt19937 rng; \ std::uniform_int_distribution<T> dist; \ \ while (state.KeepRunning()) \ Format(FORMAT, dist(rng), dist(rng), dist(rng), dist(rng), \ dist(rng), dist(rng), dist(rng), dist(rng)); \ } \ BENCHMARK(test_##NAME); \ /**/ TEST_MULTI_INT8(int32_multi8, int32_t, ARGS_8); TEST_MULTI_INT8(int64_multi8, int64_t, ARGS_8); #endif #define TEST_MULTI_INT16(NAME, T, FORMAT) \ static void test_##NAME (benchmark::State& state) \ { \ std::mt19937 rng; \ std::uniform_int_distribution<T> dist; \ \ while (state.KeepRunning()) \ Format(FORMAT, dist(rng), dist(rng), dist(rng), dist(rng), \ dist(rng), dist(rng), dist(rng), dist(rng), \ dist(rng), dist(rng), dist(rng), dist(rng), \ dist(rng), dist(rng), dist(rng), dist(rng)); \ } \ BENCHMARK(test_##NAME); \ /**/ TEST_MULTI_INT16(int32_multi16, int32_t, ARGS_16); TEST_MULTI_INT16(int64_multi16, int64_t, ARGS_16); #endif #if 0 // ---------------------------------------------------- TEST_MULTI_INT_x16 #define TEST_MULTI_INT_x16(NAME, T, FORMAT) \ static void test_##NAME (benchmark::State& state) \ { \ std::mt19937 rng; \ std::uniform_int_distribution<T> dist; \ \ while (state.KeepRunning()) \ { \ Format(FORMAT, dist(rng)); \ Format(FORMAT, dist(rng)); \ Format(FORMAT, dist(rng)); \ Format(FORMAT, dist(rng)); \ Format(FORMAT, dist(rng)); \ Format(FORMAT, dist(rng)); \ Format(FORMAT, dist(rng)); \ Format(FORMAT, dist(rng)); \ Format(FORMAT, dist(rng)); \ Format(FORMAT, dist(rng)); \ Format(FORMAT, dist(rng)); \ Format(FORMAT, dist(rng)); \ Format(FORMAT, dist(rng)); \ Format(FORMAT, dist(rng)); \ Format(FORMAT, dist(rng)); \ Format(FORMAT, dist(rng)); \ } \ } \ BENCHMARK(test_##NAME); \ /**/ TEST_MULTI_INT_x16(int32_multi_x16, int32_t, "hello {}"); TEST_MULTI_INT_x16(int64_multi_x16, int64_t, "hello {}"); #endif #if 1 // ------------------------------------------------------------ TEST_FLOAT static void test_genfloats(benchmark::State& state) { std::mt19937 rng; std::uniform_real_distribution<double> dist(0, std::numeric_limits<double>::max()); while (state.KeepRunning()) benchmark::DoNotOptimize( dist(rng) ); } BENCHMARK(test_genfloats); BENCHMARK(test_genfloats); BENCHMARK(test_genfloats); #define TEST_FLOAT(NAME, T, FORMAT) \ static void test_##NAME (benchmark::State& state) \ { \ std::mt19937 rng; \ std::uniform_real_distribution<T> dist(0, std::numeric_limits<T>::max()); \ \ while (state.KeepRunning()) \ Format(FORMAT, dist(rng)); \ } \ BENCHMARK(test_##NAME); \ /**/ TEST_FLOAT(double, double, "{}"); //TEST_FLOAT(double_x, double, "{:x}"); //TEST_FLOAT(double_f, double, "{:f}"); //TEST_FLOAT(double_e, double, "{:e}"); //TEST_FLOAT(double_g, double, "{:g}"); //TEST_FLOAT(double_a, double, "{:a}"); TEST_FLOAT(double_f_17, double, "{:.17f}"); TEST_FLOAT(double_e_17, double, "{:.17e}"); TEST_FLOAT(double_g_17, double, "{:.17g}"); TEST_FLOAT(double_a_17, double, "{:.17a}"); #endif #define STRING_1 "Hello" #define STRING_2 "I'm sorry Dave. I'm afraid I can't do that." #define STRING_3 \ "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod " \ "tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At " \ "vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, " \ "no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit " \ "amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut " \ "labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam " \ "et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata " \ "sanctus est Lorem ipsum dolor sit amet." #if 0 // ----------------------------------------------------------- TEST_STRING #define TEST_STRING(NAME, FORMAT, ...) \ static void test_##NAME (benchmark::State& state) \ { \ while (state.KeepRunning()) \ Format(FORMAT, __VA_ARGS__); \ } \ BENCHMARK(test_##NAME); /**/ TEST_STRING(str_1, "{}", STRING_1); TEST_STRING(str_2, "{}", STRING_2); TEST_STRING(str_3, "{}", STRING_3); TEST_STRING(str_1_2, "{} {}", STRING_1, STRING_1); TEST_STRING(str_2_2, "{} {}", STRING_2, STRING_2); TEST_STRING(str_3_2, "{} {}", STRING_3, STRING_3); TEST_STRING(str_1_3, "{0} {0}", STRING_1); TEST_STRING(str_2_3, "{0} {0}", STRING_2); TEST_STRING(str_3_3, "{0} {0}", STRING_3); //TEST_STRING(stdstr_1, "{}", std::string{STRING_1}); //TEST_STRING(stdstr_2, "{}", std::string{STRING_2}); //TEST_STRING(stdstr_3, "{}", std::string{STRING_3}); //TEST_STRING(stdstr_1_2, "{} {}", std::string{STRING_1}, std::string{STRING_1}); //TEST_STRING(stdstr_2_2, "{} {}", std::string{STRING_2}, std::string{STRING_2}); //TEST_STRING(stdstr_3_2, "{} {}", std::string{STRING_3}, std::string{STRING_3}); //TEST_STRING(stdstr_1_3, "{0} {0}", std::string{STRING_1}); //TEST_STRING(stdstr_2_3, "{0} {0}", std::string{STRING_2}); //TEST_STRING(stdstr_3_3, "{0} {0}", std::string{STRING_3}); #endif #if 0 // --------------------------------------------------------- TEST_CUSTOM_1 struct MyString { char const* str; }; namespace fmtxx { template <> struct FormatValue<MyString> { errc operator()(Writer& w, FormatSpec const& spec, MyString const& s) const { return fmtxx::Util::format_string(w, spec, s.str); } }; } #define TEST_CUSTOM_1(NAME, FORMAT, ...) \ static void test_##NAME (benchmark::State& state) \ { \ while (state.KeepRunning()) \ Format(FORMAT, __VA_ARGS__); \ } \ BENCHMARK(test_##NAME); /**/ TEST_CUSTOM_1(custom_str_1, "{}", MyString{STRING_1}); TEST_CUSTOM_1(custom_str_2, "{}", MyString{STRING_2}); TEST_CUSTOM_1(custom_str_3, "{}", MyString{STRING_3}); TEST_CUSTOM_1(custom_str_1_2, "{} {}", MyString{STRING_1}, MyString{STRING_1}); TEST_CUSTOM_1(custom_str_2_2, "{} {}", MyString{STRING_2}, MyString{STRING_2}); TEST_CUSTOM_1(custom_str_3_2, "{} {}", MyString{STRING_3}, MyString{STRING_3}); TEST_CUSTOM_1(custom_str_1_3, "{0} {0}", MyString{STRING_1}); TEST_CUSTOM_1(custom_str_2_3, "{0} {0}", MyString{STRING_2}); TEST_CUSTOM_1(custom_str_3_3, "{0} {0}", MyString{STRING_3}); #endif int main(int argc, char* argv[]) { const size_t iobuf_size = 64 * 1024 * 1024; char* iobuf = static_cast<char*>(malloc(iobuf_size)); std::ios_base::sync_with_stdio(false); setvbuf(stderr, iobuf, _IOFBF, iobuf_size); benchmark::Initialize(&argc, argv); if (benchmark::ReportUnrecognizedArguments(argc, argv)) return 1; benchmark::RunSpecifiedBenchmarks(); return 0; } #endif <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <vector> #include <sstream> #include <thread> #include <chrono> #include "lcomm/lcomm.h" //! This test is a simple ping-pong test for the endpoint system. //! It implements two endpoints (each one with an associated subscriber) //! bound to local client and server TCP sockets. //! The server endpoint subscriber answers (the pong) to any received packets (the ping). //! A simple packet structure. class MyPacket : public lcomm::Packet<MyPacket> { public: //! This constructor must be defined, and must call //! fromJson(node) after setting up bindings. MyPacket(lconf::json::Node* node) { M_setup(); fromJson(node); } //! This is a custom constructor (that sets up bindings too). MyPacket(std::string const& cmd) : m_cmd(cmd) { M_setup(); } //! Just a getter. std::string const& cmd() const { return m_cmd; } //! Just a setter. void setCmd(std::string const& cmd) { m_cmd = cmd; } private: //! This function sets up bindings. void M_setup() { //! This call to bind(name, ref) exposes the member 'm_cmd' //! to the serializing system (by reference), meaning //! that it will be preserved during transmission of this packet //! instance. bind("cmd", m_cmd); } private: std::string m_cmd; }; //! A simple ping-pong subscriber. //! Create with pong == false for the pinger and pong == true //! for the ponger. class PingPonger : public lcomm::Subscriber { public: PingPonger(bool pong) : m_pong(pong) { } //! The endpoint calls this function when a packet is received. void notify(lcomm::Endpoint* ep, lcomm::PacketBase const* packet) { // Don't cast directly as it is really unsafe, call the downcast<T>() // function, that checks the tag of the packet. MyPacket* ctrl = packet->downcast<MyPacket>(); if(ctrl) { std::cout << ctrl->cmd() << std::endl; // If we're a ponger, reply to the packet. if(m_pong) { MyPacket ctrl("<- pong"); ep->write(&ctrl); } } } private: bool m_pong; }; int main() { // Just a random port int port = 48953; using namespace lcomm; try { // Remember to register our packet to the system PacketManager::registerPacketClass<MyPacket>(); /*** Server side ***/ // Create the server socket ServerSocket* server = new ServerSocket(port); // Create and attach the endpoint Endpoint* server_ep = new Endpoint(); server_ep->bind(server); // Create the ponger (that receives pings and send pongs) PingPonger server_sub(true); server_ep->registerSubscriber(&server_sub); /*** Client side ***/ // Wait for the server to be properly init'ed std::this_thread::sleep_for(std::chrono::seconds(1)); // Create the client socket ClientSocket* client = new ClientSocket("127.0.0.1", port); // Create and attach the client endpoint Endpoint* client_ep = new Endpoint(); client_ep->bind(client); // Create the pinger subscriber (that receives pongs) PingPonger client_sub(false); client_ep->registerSubscriber(&client_sub); // Wait for the client to be opened, otherwise // write() will throw for(; !client->opened();) ; /*** Send some data ***/ for(int i = 0; i < 10; ++i) { // Create a ping packet and send it through the endpoint MyPacket ctrl("-> ping"); client_ep->write(&ctrl); std::this_thread::sleep_for(std::chrono::milliseconds(100)); } // Remember to delete endpoints **before** their sockets ! delete client_ep; delete server_ep; // Deleting sockets closes all connections delete client; delete server; } catch(std::exception const& exc) { std::cerr << "Exception: " << exc.what() << std::endl; return -1; } return 0; } <commit_msg>Fixed tests<commit_after>#include <iostream> #include <string> #include <vector> #include <sstream> #include <thread> #include <chrono> #include "lcomm/lcomm.h" //! This test is a simple ping-pong test for the endpoint system. //! It implements two endpoints (each one with an associated subscriber) //! bound to local client and server TCP sockets. //! The server endpoint subscriber answers (the pong) to any received packets (the ping). //! A simple packet structure. class MyPacket : public lcomm::Packet<MyPacket> { public: //! This constructor must be defined, and must call //! fromJson(node) after setting up bindings. MyPacket(lconf::json::Node* node) { M_setup(); fromJson(node); } //! This is a custom constructor (that sets up bindings too). MyPacket(std::string const& cmd) : m_cmd(cmd) { M_setup(); } //! Just a getter. std::string const& cmd() const { return m_cmd; } //! Just a setter. void setCmd(std::string const& cmd) { m_cmd = cmd; } private: //! This function sets up bindings. void M_setup() { //! This call to bind(name, ref) exposes the member 'm_cmd' //! to the serializing system (by reference), meaning //! that it will be preserved during transmission of this packet //! instance. bind("cmd", m_cmd); } private: std::string m_cmd; }; //! A simple ping-pong subscriber. //! Create with pong == false for the pinger and pong == true //! for the ponger. class PingPonger : public lcomm::Subscriber { public: PingPonger(bool pong) : m_pong(pong) { } //! The endpoint calls this function when a packet is received. void notify(lcomm::Endpoint* ep, lcomm::PacketBase const* packet) { // Don't cast directly as it is really unsafe, call the downcast<T>() // function, that checks the tag of the packet. MyPacket* ctrl = packet->downcast<MyPacket>(); if(ctrl) { std::cout << ctrl->cmd() << std::endl; // If we're a ponger, reply to the packet. if(m_pong) { MyPacket ctrl("<- pong"); ep->write(&ctrl); } } } private: bool m_pong; }; int main() { // Just a random port int port = 48953; using namespace lcomm; try { // Remember to register our packet to the system PacketManager::registerPacketClass<MyPacket>(); /*** Server side ***/ // Create the server socket // Create and attach the endpoint Endpoint server_ep(std::make_unique<ServerSocket>(port)); // Create the ponger (that receives pings and send pongs) PingPonger server_sub(true); server_ep.registerSubscriber(&server_sub); /*** Client side ***/ // Wait for the server to be properly init'ed std::this_thread::sleep_for(std::chrono::seconds(1)); // Create the client socket // Create and attach the client endpoint Endpoint client_ep(std::make_unique<ClientSocket>("127.0.0.1", port)); // Create the pinger subscriber (that receives pongs) PingPonger client_sub(false); client_ep.registerSubscriber(&client_sub); // Wait for the client to be opened, otherwise // write() will throw for(; !client_ep.socket().opened();) ; /*** Send some data ***/ for(int i = 0; i < 10; ++i) { // Create a ping packet and send it through the endpoint MyPacket ctrl("-> ping"); client_ep.write(&ctrl); std::this_thread::sleep_for(std::chrono::milliseconds(100)); } } catch(std::exception const& exc) { std::cerr << "Exception: " << exc.what() << std::endl; return -1; } return 0; } <|endoftext|>
<commit_before>#include <iostream> #include <sstream> #include <string> #include <arpa/inet.h> #include <netdb.h> #include <sys/socket.h> #include <string.h> #include <unistd.h> #ifdef __FreeBSD__ #include <netinet/in.h> #endif #include "MailServer.hh" namespace sieve { MailServer MailServer::create(std::string host_with_port) { bool in_port = false; std::string hostname, port; for (char const &c: host_with_port) { if (c == ':') { in_port = true; continue; } if (in_port) port += c; else hostname += c; } return MailServer(hostname, atoi(port.c_str())); } MailServer::MailServer(std::string hostname, uint32_t port) : _hostname(hostname) , _port(port) , _socket(-1) { } MailServer::~MailServer() { close(_socket); } std::map<std::string, bool> MailServer::capabilities() { auto capabilities = std::map<std::string, bool>(); this->_connect(); auto hello_dictionary = this->_parse_response(_greeting); std::string capability = ""; for (char const &c: hello_dictionary["SIEVE"]) { if (c == ' ') { capabilities[capability] = true; capability = ""; continue; } capability += c; } return capabilities; } void MailServer::_connect() { if (_socket >= 0) return; if ((_socket = socket(AF_INET, SOCK_STREAM, 0)) < 0) { std::cout << "Socket creation error" << std::endl; abort(); } struct sockaddr_in server_address; server_address.sin_family = AF_INET; server_address.sin_port = htons(this->_port); struct hostent *host_entry; struct in_addr **address_list; if ((host_entry = gethostbyname(this->_hostname.c_str())) == nullptr) { herror("gethostbyname"); abort(); } address_list = (struct in_addr **) host_entry->h_addr_list; char ip[100] = {}; if (address_list[0] == nullptr) { std::cout << "Could not map hostname: " << this->_hostname << " to an IP address." << std::endl; abort(); } strcpy(ip, inet_ntoa(*address_list[0])); if (inet_pton(AF_INET, ip, &server_address.sin_addr) <= 0) { std::cout << "Invalid address / Address not supported" << ip << std::endl; abort(); } if (connect(_socket, (struct sockaddr *)&server_address, sizeof(server_address)) < 0) { std::cout << "Connection Failed" << std::endl; abort(); } char buffer[1024] = {}; send(_socket, "", 0, 0); read(_socket, buffer, 1024); _greeting = std::string(buffer); } std::map<std::string, std::string> MailServer::_parse_response(std::string response) { auto dictionary = std::map<std::string, std::string>(); std::istringstream response_stream(response); for (std::string line; std::getline(response_stream, line);) { bool in_key = false, in_value = false; bool key_found = false, value_found = false; std::string key, value; for (char const &c: line) { switch (c) { case '"': if (!in_key && !key_found) { in_key = true; break; } if (in_key) { in_key = false; key_found = true; break; } if (!in_value && !value_found) { in_value = true; break; } if (in_value) { in_value = false; value_found = true; break; } break; default: if (in_key) key = key + c; if (in_value) value = value + c; break; } } dictionary[key] = value; } return dictionary; } } //-- namespace sieve<commit_msg>Lowercase keys when parsing server response.<commit_after>#include <iostream> #include <sstream> #include <string> #include <arpa/inet.h> #include <ctype.h> #include <netdb.h> #include <sys/socket.h> #include <string.h> #include <unistd.h> #ifdef __FreeBSD__ #include <netinet/in.h> #endif #include "MailServer.hh" namespace sieve { MailServer MailServer::create(std::string host_with_port) { bool in_port = false; std::string hostname, port; for (char const &c: host_with_port) { if (c == ':') { in_port = true; continue; } if (in_port) port += c; else hostname += c; } return MailServer(hostname, atoi(port.c_str())); } MailServer::MailServer(std::string hostname, uint32_t port) : _hostname(hostname) , _port(port) , _socket(-1) { } MailServer::~MailServer() { close(_socket); } std::map<std::string, bool> MailServer::capabilities() { auto capabilities = std::map<std::string, bool>(); this->_connect(); auto hello_dictionary = this->_parse_response(_greeting); std::string capability = ""; for (char const &c: hello_dictionary["sieve"]) { if (c == ' ') { capabilities[capability] = true; capability = ""; continue; } capability += c; } return capabilities; } void MailServer::_connect() { if (_socket >= 0) return; if ((_socket = socket(AF_INET, SOCK_STREAM, 0)) < 0) { std::cout << "Socket creation error" << std::endl; abort(); } struct sockaddr_in server_address; server_address.sin_family = AF_INET; server_address.sin_port = htons(this->_port); struct hostent *host_entry; struct in_addr **address_list; if ((host_entry = gethostbyname(this->_hostname.c_str())) == nullptr) { herror("gethostbyname"); abort(); } address_list = (struct in_addr **) host_entry->h_addr_list; char ip[100] = {}; if (address_list[0] == nullptr) { std::cout << "Could not map hostname: " << this->_hostname << " to an IP address." << std::endl; abort(); } strcpy(ip, inet_ntoa(*address_list[0])); if (inet_pton(AF_INET, ip, &server_address.sin_addr) <= 0) { std::cout << "Invalid address / Address not supported" << ip << std::endl; abort(); } if (connect(_socket, (struct sockaddr *)&server_address, sizeof(server_address)) < 0) { std::cout << "Connection Failed" << std::endl; abort(); } char buffer[1024] = {}; send(_socket, "", 0, 0); read(_socket, buffer, 1024); _greeting = std::string(buffer); } std::map<std::string, std::string> MailServer::_parse_response(std::string response) { auto dictionary = std::map<std::string, std::string>(); std::istringstream response_stream(response); for (std::string line; std::getline(response_stream, line);) { bool in_key = false, in_value = false; bool key_found = false, value_found = false; std::string key, value; for (char const &c: line) { switch (c) { case '"': if (!in_key && !key_found) { in_key = true; break; } if (in_key) { in_key = false; key_found = true; break; } if (!in_value && !value_found) { in_value = true; break; } if (in_value) { in_value = false; value_found = true; break; } break; default: if (in_key) key = key + tolower(c); if (in_value) value = value + c; break; } } dictionary[key] = value; } return dictionary; } } //-- namespace sieve<|endoftext|>
<commit_before>#include <stdlib.h> #include <string.h> #include <sys/time.h> #include <utility> #include "API.h" #include "Proxy.h" using namespace java::lang; using namespace java::io; using namespace java::util; int main(int,char**) { JavaVM* vm; void* envPtr; JavaVMInitArgs vm_args; memset(&vm_args, 0, sizeof(vm_args)); char classPath[] = {"-Djava.class.path=build"}; JavaVMOption options[1]; options[0].optionString = classPath; vm_args.options = options; vm_args.nOptions = 1; vm_args.version = JNI_VERSION_1_6; JNI_CreateJavaVM(&vm, &envPtr, &vm_args); JNIEnv* env = (JNIEnv*)envPtr; jni::Initialize(*vm); // ------------------------------------------------------------------------ // System.out.println("Hello world"); // ------------------------------------------------------------------------ // pure JNI { jstring helloWorldString = env->NewStringUTF("RAW"); jclass javaLangSystem = env->FindClass("java/lang/System"); jclass javaIoPrintStream = env->FindClass("java/io/PrintStream"); jfieldID javaLangSystem_outFID = env->GetStaticFieldID(javaLangSystem, "out", "Ljava/io/PrintStream;"); jobject javaLangSystem_out = env->GetStaticObjectField(javaLangSystem, javaLangSystem_outFID); jmethodID javaIoPrintStream_printlnMID = env->GetMethodID(javaIoPrintStream, "println", "(Ljava/lang/String;)V"); env->CallVoidMethod(javaLangSystem_out, javaIoPrintStream_printlnMID, helloWorldString); } // JNI.h jni::Errno error; { jni::Initialize(*vm); if ((env = jni::AttachCurrentThread())) { jni::LocalFrame frame; jstring helloWorldString = env->NewStringUTF("JNI"); jclass javaLangSystem = env->FindClass("java/lang/System"); jclass javaIoPrintStream = env->FindClass("java/io/PrintStream"); jfieldID javaLangSystem_outFID = env->GetStaticFieldID(javaLangSystem, "out", "Ljava/io/PrintStream;"); jobject javaLangSystem_out = env->GetStaticObjectField(javaLangSystem, javaLangSystem_outFID); jmethodID javaIoPrintStream_printlnMID = env->GetMethodID(javaIoPrintStream, "println", "(Ljava/lang/String;)V"); env->CallVoidMethod(javaLangSystem_out, javaIoPrintStream_printlnMID, helloWorldString); if ((error = jni::CheckError())) printf("JNI %s\n", jni::GetErrorMessage()); } } // Ops.h { jni::LocalFrame frame; jstring helloWorldString = env->NewStringUTF("Ops"); jclass javaLangSystem = env->FindClass("java/lang/System"); jclass javaIoPrintStream = env->FindClass("java/io/PrintStream"); jfieldID javaLangSystem_outFID = env->GetStaticFieldID(javaLangSystem, "out", "Ljava/io/PrintStream;"); jobject javaLangSystem_out = jni::Op<jobject>::GetStaticField(javaLangSystem, javaLangSystem_outFID); jmethodID javaIoPrintStream_printlnMID = env->GetMethodID(javaIoPrintStream, "println", "(Ljava/lang/String;)V"); jni::Op<jvoid>::CallMethod(javaLangSystem_out, javaIoPrintStream_printlnMID, helloWorldString); if ((error = jni::CheckError())) printf("Ops %d:%s\n", error, jni::GetErrorMessage()); } { System::fOut().Println("Api"); } // ------------------------------------------------------------------------ // import java.io.PrintStream; // import java.util.Properties; // import java.util.Enumerator; // // PrintStream out = System.out; // Properties properties = System.getPropertes(); // Enumerator keys = properties.keys(); // while (keys.hasMoreElements()) // out.println(properties.getProperty((String)keys.next())); // ------------------------------------------------------------------------ timeval start, stop; // Optimized version gettimeofday(&start, NULL); { jni::LocalFrame frame; PrintStream out = System::fOut(); Properties properties = System::GetProperties(); Enumeration keys = properties.Keys(); while (keys.HasMoreElements()) out.Println(properties.GetProperty(jni::Cast<String>(keys.NextElement()))); } gettimeofday(&stop, NULL); printf("%f ms.\n", (stop.tv_sec - start.tv_sec) * 1000.0 + (stop.tv_usec - start.tv_usec) / 1000.0); // CharSequence test java::lang::CharSequence string = "hello world"; printf("%s\n", string.ToString().c_str()); // ------------------------------------------------------------- // Util functions // ------------------------------------------------------------- java::lang::Object object = java::lang::Integer(23754); if (jni::InstanceOf<java::lang::Number>(object) && jni::Cast<java::lang::Number>(object)) { printf("%d\n", static_cast<int>(java::lang::Number(object))); } else { int* p = 0; *p = 3; } // ------------------------------------------------------------- // Array Test // ------------------------------------------------------------- { jni::LocalFrame frame; jni::Array<int> test01(4, (int[]){1, 2, 3, 4}); for (int i = 0; i < test01.Length(); ++i) printf("ArrayTest01[%d],", test01[i]); printf("\n"); jni::Array<java::lang::Integer> test02(4, (java::lang::Integer[]){1, 2, 3, 4}); for (int i = 0; i < test02.Length(); ++i) printf("ArrayTest02[%d],", test02[i].IntValue()); printf("\n"); jni::Array<jobject> test03(java::lang::Integer::__CLASS, 4, (jobject[]){java::lang::Integer(1), java::lang::Integer(2), java::lang::Integer(3), java::lang::Integer(4)}); for (int i = 0; i < test03.Length(); ++i) printf("ArrayTest03[%d],", java::lang::Integer(test03[i]).IntValue()); printf("\n"); jni::Array<jobject> test04(java::lang::Integer::__CLASS, 4, (java::lang::Integer[]){1, 2, 3, 4}); for (int i = 0; i < test04.Length(); ++i) printf("ArrayTest04[%d],", java::lang::Integer(test04[i]).IntValue()); printf("\n"); jni::Array<int> test05(4, (java::lang::Integer[]){1, 2, 3, 4}); for (int i = 0; i < test05.Length(); ++i) printf("ArrayTest05[%d],", test05[i]); printf("\n"); jni::Array<java::lang::Integer> test10(4, 4733); for (int i = 0; i < test10.Length(); ++i) printf("ArrayTest10[%d],", test10[i].IntValue()); printf("\n"); jni::Array<jobject> test11(java::lang::Integer::__CLASS, 4, java::lang::Integer(4733)); for (int i = 0; i < test11.Length(); ++i) printf("ArrayTest11[%d],", java::lang::Integer(test11[i]).IntValue()); printf("\n"); } // ------------------------------------------------------------- // Proxy test // ------------------------------------------------------------- if (!jni::ProxyInvoker::__Register()) printf("%s\n", jni::GetErrorMessage()); struct PretendRunnable : jni::Proxy<Runnable> { virtual void Run() {printf("%s\n", "hello world!!!!"); } }; PretendRunnable pretendRunnable; Runnable runnable = pretendRunnable; Thread thread(pretendRunnable); thread.Start(); thread.Join(); runnable.Run(); // Make sure we don't get crashes from deleting the native object. PretendRunnable* pretendRunnable2 = new PretendRunnable; Runnable runnable2 = *pretendRunnable2; runnable2.Run(); delete pretendRunnable2; runnable2.Run(); // <-- should not log anything // ------------------------------------------------------------- // Performance Proxy Test // ------------------------------------------------------------- struct PerformanceRunnable : jni::Proxy<Runnable> { int i; PerformanceRunnable() : i(0) {} virtual void Run() { ++i; } }; PerformanceRunnable* perfRunner = new PerformanceRunnable; Runnable perfRunnable = *perfRunner; gettimeofday(&start, NULL); for (int i = 0; i < 1024; ++i) perfRunnable.Run(); gettimeofday(&stop, NULL); printf("count: %d, time: %f ms.\n", perfRunner->i, (stop.tv_sec - start.tv_sec) * 1000.0 + (stop.tv_usec - start.tv_usec) / 1000.0); delete perfRunner; gettimeofday(&start, NULL); for (int i = 0; i < 1024; ++i) perfRunnable.Run(); gettimeofday(&stop, NULL); printf("count: %d, time: %f ms.\n", 1024, (stop.tv_sec - start.tv_sec) * 1000.0 + (stop.tv_usec - start.tv_usec) / 1000.0); // ------------------------------------------------------------- // Weak Proxy Test // ------------------------------------------------------------- struct KillMePleazeRunnable : jni::WeakProxy<Runnable> { virtual ~KillMePleazeRunnable() { printf("%s\n", "KillMePleazeRunnable");} virtual void Run() { } }; { jni::LocalFrame frame; new KillMePleazeRunnable; } for (int i = 0; i < 32; ++i) // Do a couple of loops to massage the GC { jni::LocalFrame frame; jni::Array<int> array(1024*1024); System::Gc(); } // ------------------------------------------------------------- // Multiple Proxy Interface Test // ------------------------------------------------------------- { class MultipleInterfaces : public jni::WeakProxy<Runnable, Iterator> { public: MultipleInterfaces() : m_Count(10) { } virtual ~MultipleInterfaces() { printf("destroyed[%p]\n", this); } virtual void Run() { printf("Run[%p]!\n", this); } virtual void Remove() { jni::ThrowNew(UnsupportedOperationException::__CLASS, "This iterator does not support remove."); } virtual ::jboolean HasNext() { printf("HasNext[%p]!\n", this); bool result = (--m_Count != 0); printf("m_Count[%d][%d]\n", m_Count, result); return result; } virtual ::java::lang::Object Next() { return ::java::lang::String("this is a string"); } virtual void ForEachRemaining(const ::java::util::function::Consumer& arg0) { printf("ForEachRemaining[%p]!\n", this); } private: unsigned m_Count; }; { jni::LocalFrame frame; MultipleInterfaces* testProxy = new MultipleInterfaces(); Runnable runnable = *testProxy; runnable.Run(); Iterator iterator = *testProxy; while (iterator.HasNext()) { String javaString = jni::Cast<String>(iterator.Next()); printf("%s\n", javaString.c_str()); } } for (int i = 0; i < 32; ++i) // Do a couple of loops to massage the GC { jni::LocalFrame frame; jni::Array<int> array(1024*1024); System::Gc(); } printf("%s", "end of multi interface test\n"); } // ------------------------------------------------------------- // Proxy Object Test // ------------------------------------------------------------- { jni::LocalFrame frame; struct PretendRunnable : jni::Proxy<Runnable> { virtual void Run() {printf("%s\n", "hello world!!!!"); } }; PretendRunnable pretendRunnable; Runnable runnable = pretendRunnable; printf("equals: %d\n", runnable.Equals(runnable)); printf("hashcode: %d\n", runnable.HashCode()); printf("toString: %s\n", runnable.ToString().c_str()); } // ------------------------------------------------------------- // Move semantics // ------------------------------------------------------------- { jni::LocalFrame frame; java::lang::Integer integer(1234); java::lang::Integer integer_moved(std::move(integer)); if (static_cast<jobject>(integer) != 0) { puts("Interger was supposed to be moved from!!!!"); abort(); } printf("Value of moved integer: %d\n", static_cast<jint>(integer_moved)); java::lang::Integer integer_assigned(4321); integer_assigned = std::move(integer_moved); if (static_cast<jobject>(integer_moved) != 0) { puts("integer_moved was supposed to be moved from when assigning!!!!"); abort(); } printf("Value of move-assigned integer: %d\n", static_cast<jint>(integer_assigned)); integer = integer_assigned; printf("Value of copy-assigned integer: %d\n", static_cast<jint>(integer)); } // ------------------------------------------------------------- // Move semantics for String class // ------------------------------------------------------------- { jni::LocalFrame frame; java::lang::String str("hello"); printf("Java string: %s\n", str.c_str()); java::lang::String str_moved("other"); str_moved = std::move(str); if (static_cast<jobject>(str) != 0) { puts("str was supposed to be moved from when assigning"); abort(); } printf("Moved string: %s\n", str_moved.c_str()); } printf("%s\n", "EOP"); // print resolution of clock() jni::DetachCurrentThread(); vm->DestroyJavaVM(); return 0; } <commit_msg>Improve String move testing<commit_after>#include <stdlib.h> #include <string.h> #include <sys/time.h> #include <utility> #include "API.h" #include "Proxy.h" using namespace java::lang; using namespace java::io; using namespace java::util; int main(int,char**) { JavaVM* vm; void* envPtr; JavaVMInitArgs vm_args; memset(&vm_args, 0, sizeof(vm_args)); char classPath[] = {"-Djava.class.path=build"}; JavaVMOption options[1]; options[0].optionString = classPath; vm_args.options = options; vm_args.nOptions = 1; vm_args.version = JNI_VERSION_1_6; JNI_CreateJavaVM(&vm, &envPtr, &vm_args); JNIEnv* env = (JNIEnv*)envPtr; jni::Initialize(*vm); // ------------------------------------------------------------------------ // System.out.println("Hello world"); // ------------------------------------------------------------------------ // pure JNI { jstring helloWorldString = env->NewStringUTF("RAW"); jclass javaLangSystem = env->FindClass("java/lang/System"); jclass javaIoPrintStream = env->FindClass("java/io/PrintStream"); jfieldID javaLangSystem_outFID = env->GetStaticFieldID(javaLangSystem, "out", "Ljava/io/PrintStream;"); jobject javaLangSystem_out = env->GetStaticObjectField(javaLangSystem, javaLangSystem_outFID); jmethodID javaIoPrintStream_printlnMID = env->GetMethodID(javaIoPrintStream, "println", "(Ljava/lang/String;)V"); env->CallVoidMethod(javaLangSystem_out, javaIoPrintStream_printlnMID, helloWorldString); } // JNI.h jni::Errno error; { jni::Initialize(*vm); if ((env = jni::AttachCurrentThread())) { jni::LocalFrame frame; jstring helloWorldString = env->NewStringUTF("JNI"); jclass javaLangSystem = env->FindClass("java/lang/System"); jclass javaIoPrintStream = env->FindClass("java/io/PrintStream"); jfieldID javaLangSystem_outFID = env->GetStaticFieldID(javaLangSystem, "out", "Ljava/io/PrintStream;"); jobject javaLangSystem_out = env->GetStaticObjectField(javaLangSystem, javaLangSystem_outFID); jmethodID javaIoPrintStream_printlnMID = env->GetMethodID(javaIoPrintStream, "println", "(Ljava/lang/String;)V"); env->CallVoidMethod(javaLangSystem_out, javaIoPrintStream_printlnMID, helloWorldString); if ((error = jni::CheckError())) printf("JNI %s\n", jni::GetErrorMessage()); } } // Ops.h { jni::LocalFrame frame; jstring helloWorldString = env->NewStringUTF("Ops"); jclass javaLangSystem = env->FindClass("java/lang/System"); jclass javaIoPrintStream = env->FindClass("java/io/PrintStream"); jfieldID javaLangSystem_outFID = env->GetStaticFieldID(javaLangSystem, "out", "Ljava/io/PrintStream;"); jobject javaLangSystem_out = jni::Op<jobject>::GetStaticField(javaLangSystem, javaLangSystem_outFID); jmethodID javaIoPrintStream_printlnMID = env->GetMethodID(javaIoPrintStream, "println", "(Ljava/lang/String;)V"); jni::Op<jvoid>::CallMethod(javaLangSystem_out, javaIoPrintStream_printlnMID, helloWorldString); if ((error = jni::CheckError())) printf("Ops %d:%s\n", error, jni::GetErrorMessage()); } { System::fOut().Println("Api"); } // ------------------------------------------------------------------------ // import java.io.PrintStream; // import java.util.Properties; // import java.util.Enumerator; // // PrintStream out = System.out; // Properties properties = System.getPropertes(); // Enumerator keys = properties.keys(); // while (keys.hasMoreElements()) // out.println(properties.getProperty((String)keys.next())); // ------------------------------------------------------------------------ timeval start, stop; // Optimized version gettimeofday(&start, NULL); { jni::LocalFrame frame; PrintStream out = System::fOut(); Properties properties = System::GetProperties(); Enumeration keys = properties.Keys(); while (keys.HasMoreElements()) out.Println(properties.GetProperty(jni::Cast<String>(keys.NextElement()))); } gettimeofday(&stop, NULL); printf("%f ms.\n", (stop.tv_sec - start.tv_sec) * 1000.0 + (stop.tv_usec - start.tv_usec) / 1000.0); // CharSequence test java::lang::CharSequence string = "hello world"; printf("%s\n", string.ToString().c_str()); // ------------------------------------------------------------- // Util functions // ------------------------------------------------------------- java::lang::Object object = java::lang::Integer(23754); if (jni::InstanceOf<java::lang::Number>(object) && jni::Cast<java::lang::Number>(object)) { printf("%d\n", static_cast<int>(java::lang::Number(object))); } else { int* p = 0; *p = 3; } // ------------------------------------------------------------- // Array Test // ------------------------------------------------------------- { jni::LocalFrame frame; jni::Array<int> test01(4, (int[]){1, 2, 3, 4}); for (int i = 0; i < test01.Length(); ++i) printf("ArrayTest01[%d],", test01[i]); printf("\n"); jni::Array<java::lang::Integer> test02(4, (java::lang::Integer[]){1, 2, 3, 4}); for (int i = 0; i < test02.Length(); ++i) printf("ArrayTest02[%d],", test02[i].IntValue()); printf("\n"); jni::Array<jobject> test03(java::lang::Integer::__CLASS, 4, (jobject[]){java::lang::Integer(1), java::lang::Integer(2), java::lang::Integer(3), java::lang::Integer(4)}); for (int i = 0; i < test03.Length(); ++i) printf("ArrayTest03[%d],", java::lang::Integer(test03[i]).IntValue()); printf("\n"); jni::Array<jobject> test04(java::lang::Integer::__CLASS, 4, (java::lang::Integer[]){1, 2, 3, 4}); for (int i = 0; i < test04.Length(); ++i) printf("ArrayTest04[%d],", java::lang::Integer(test04[i]).IntValue()); printf("\n"); jni::Array<int> test05(4, (java::lang::Integer[]){1, 2, 3, 4}); for (int i = 0; i < test05.Length(); ++i) printf("ArrayTest05[%d],", test05[i]); printf("\n"); jni::Array<java::lang::Integer> test10(4, 4733); for (int i = 0; i < test10.Length(); ++i) printf("ArrayTest10[%d],", test10[i].IntValue()); printf("\n"); jni::Array<jobject> test11(java::lang::Integer::__CLASS, 4, java::lang::Integer(4733)); for (int i = 0; i < test11.Length(); ++i) printf("ArrayTest11[%d],", java::lang::Integer(test11[i]).IntValue()); printf("\n"); } // ------------------------------------------------------------- // Proxy test // ------------------------------------------------------------- if (!jni::ProxyInvoker::__Register()) printf("%s\n", jni::GetErrorMessage()); struct PretendRunnable : jni::Proxy<Runnable> { virtual void Run() {printf("%s\n", "hello world!!!!"); } }; PretendRunnable pretendRunnable; Runnable runnable = pretendRunnable; Thread thread(pretendRunnable); thread.Start(); thread.Join(); runnable.Run(); // Make sure we don't get crashes from deleting the native object. PretendRunnable* pretendRunnable2 = new PretendRunnable; Runnable runnable2 = *pretendRunnable2; runnable2.Run(); delete pretendRunnable2; runnable2.Run(); // <-- should not log anything // ------------------------------------------------------------- // Performance Proxy Test // ------------------------------------------------------------- struct PerformanceRunnable : jni::Proxy<Runnable> { int i; PerformanceRunnable() : i(0) {} virtual void Run() { ++i; } }; PerformanceRunnable* perfRunner = new PerformanceRunnable; Runnable perfRunnable = *perfRunner; gettimeofday(&start, NULL); for (int i = 0; i < 1024; ++i) perfRunnable.Run(); gettimeofday(&stop, NULL); printf("count: %d, time: %f ms.\n", perfRunner->i, (stop.tv_sec - start.tv_sec) * 1000.0 + (stop.tv_usec - start.tv_usec) / 1000.0); delete perfRunner; gettimeofday(&start, NULL); for (int i = 0; i < 1024; ++i) perfRunnable.Run(); gettimeofday(&stop, NULL); printf("count: %d, time: %f ms.\n", 1024, (stop.tv_sec - start.tv_sec) * 1000.0 + (stop.tv_usec - start.tv_usec) / 1000.0); // ------------------------------------------------------------- // Weak Proxy Test // ------------------------------------------------------------- struct KillMePleazeRunnable : jni::WeakProxy<Runnable> { virtual ~KillMePleazeRunnable() { printf("%s\n", "KillMePleazeRunnable");} virtual void Run() { } }; { jni::LocalFrame frame; new KillMePleazeRunnable; } for (int i = 0; i < 32; ++i) // Do a couple of loops to massage the GC { jni::LocalFrame frame; jni::Array<int> array(1024*1024); System::Gc(); } // ------------------------------------------------------------- // Multiple Proxy Interface Test // ------------------------------------------------------------- { class MultipleInterfaces : public jni::WeakProxy<Runnable, Iterator> { public: MultipleInterfaces() : m_Count(10) { } virtual ~MultipleInterfaces() { printf("destroyed[%p]\n", this); } virtual void Run() { printf("Run[%p]!\n", this); } virtual void Remove() { jni::ThrowNew(UnsupportedOperationException::__CLASS, "This iterator does not support remove."); } virtual ::jboolean HasNext() { printf("HasNext[%p]!\n", this); bool result = (--m_Count != 0); printf("m_Count[%d][%d]\n", m_Count, result); return result; } virtual ::java::lang::Object Next() { return ::java::lang::String("this is a string"); } virtual void ForEachRemaining(const ::java::util::function::Consumer& arg0) { printf("ForEachRemaining[%p]!\n", this); } private: unsigned m_Count; }; { jni::LocalFrame frame; MultipleInterfaces* testProxy = new MultipleInterfaces(); Runnable runnable = *testProxy; runnable.Run(); Iterator iterator = *testProxy; while (iterator.HasNext()) { String javaString = jni::Cast<String>(iterator.Next()); printf("%s\n", javaString.c_str()); } } for (int i = 0; i < 32; ++i) // Do a couple of loops to massage the GC { jni::LocalFrame frame; jni::Array<int> array(1024*1024); System::Gc(); } printf("%s", "end of multi interface test\n"); } // ------------------------------------------------------------- // Proxy Object Test // ------------------------------------------------------------- { jni::LocalFrame frame; struct PretendRunnable : jni::Proxy<Runnable> { virtual void Run() {printf("%s\n", "hello world!!!!"); } }; PretendRunnable pretendRunnable; Runnable runnable = pretendRunnable; printf("equals: %d\n", runnable.Equals(runnable)); printf("hashcode: %d\n", runnable.HashCode()); printf("toString: %s\n", runnable.ToString().c_str()); } // ------------------------------------------------------------- // Move semantics // ------------------------------------------------------------- { jni::LocalFrame frame; java::lang::Integer integer(1234); java::lang::Integer integer_moved(std::move(integer)); if (static_cast<jobject>(integer) != 0) { puts("Interger was supposed to be moved from!!!!"); abort(); } printf("Value of moved integer: %d\n", static_cast<jint>(integer_moved)); java::lang::Integer integer_assigned(4321); integer_assigned = std::move(integer_moved); if (static_cast<jobject>(integer_moved) != 0) { puts("integer_moved was supposed to be moved from when assigning!!!!"); abort(); } printf("Value of move-assigned integer: %d\n", static_cast<jint>(integer_assigned)); integer = integer_assigned; printf("Value of copy-assigned integer: %d\n", static_cast<jint>(integer)); } // ------------------------------------------------------------- // Move semantics for String class // ------------------------------------------------------------- { jni::LocalFrame frame; java::lang::String str("hello"); printf("Java string: %s\n", str.c_str()); java::lang::String str_moved("other"); str_moved = std::move(str); if (static_cast<jobject>(str) != 0 || str.c_str() != nullptr) { puts("str was supposed to be moved from when assigning"); abort(); } printf("Moved string: %s\n", str_moved.c_str()); java::lang::String str_ctor_moved(std::move(str_moved)); if (static_cast<jobject>(str_moved) != 0 || str_moved.c_str() != nullptr) { puts("str_moved was supposed to be moved from when assigning"); abort(); } printf("Moved string via constructor: %s\n", str_ctor_moved.c_str()); } printf("%s\n", "EOP"); // print resolution of clock() jni::DetachCurrentThread(); vm->DestroyJavaVM(); return 0; } <|endoftext|>
<commit_before>// // gsl-lite is based on GSL: Guidelines Support Library, // https://github.com/microsoft/gsl // // Copyright (c) 2015 Martin Moene // Copyright (c) 2015 Microsoft Corporation. All rights reserved. // // This code is licensed under the MIT License (MIT). // // 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 "gsl-lite.t.h" CASE( "at(): Terminates access to non-existing C-array elements" ) { int a[] = { 1, 2, 3, 4 }; EXPECT_THROWS( at(a, 4) ); } CASE( "at(): Terminates access to non-existing std::array elements (C++11)" ) { #if gsl_HAVE_ARRAY std::array<int, 4> a = {{ 1, 2, 3, 4 }}; EXPECT_THROWS( at(a, 4) ); #else EXPECT( !!"std::array<> is not available (no C++11)" ); #endif } CASE( "at(): Terminates access to non-existing std::vector elements" ) { std::vector<int> a; // = { 1, 2, 3, 4 }; for ( int i = 0; i < 4; ++i ) { a.push_back( i + 1 ); } EXPECT_THROWS( at(a, 4) ); } CASE( "at(): Terminates access to non-existing std::initializer_list elements" ) { std::initializer_list<int> a = { 1, 2, 3, 4 }; EXPECT_THROWS( at(a, 4) ); } CASE( "at(): Terminates access to non-existing gsl::span elements" ) { int arr[] = { 1, 2, 3, 4 }; span<int> a( arr ); EXPECT_THROWS( at(a, 4) ); } CASE( "at(): Allows access to existing C-array elements" ) { int a[] = { 1, 2, 3, 4 }; for ( int i = 0; i < 4; ++i ) { EXPECT( at(a, i) == i + 1 ); } } CASE( "at(): Allows access to existing std::array elements (C++11)" ) { #if gsl_HAVE_ARRAY std::array<int, 4> a = {{ 1, 2, 3, 4 }}; for ( int i = 0; i < 4; ++i ) { EXPECT( at(a, i) == i + 1 ); } #else EXPECT( !!"std::array<> is not available (no C++11)" ); #endif } CASE( "at(): Allows access to existing std::vector elements" ) { std::vector<int> a; // = { 1, 2, 3, 4 }; for ( int i = 0; i < 4; ++i ) { a.push_back( i + 1 ); EXPECT( at(a, i) == i + 1 ); } } CASE( "at(): Allows access to std::initializer_list elements (C++11)" ) { #if gsl_HAVE_INITIALIZER_LIST std::initializer_list<int> a = { 1, 2, 3, 4 }; for ( int i = 0; i < 4; ++i ) { EXPECT( at(a, i) == i + 1 ); } #else EXPECT( !!"std::initializer_list<> is not available (no C++11)" ); #endif } CASE( "at(): Allows access to gsl::span elements" ) { int arr[] = { 1, 2, 3, 4 }; span<int> a( arr ); for ( int i = 0; i < 4; ++i ) { EXPECT( at(a, i) == i + 1 ); } } // end of file <commit_msg>Guard usage of std::initializer_list<commit_after>// // gsl-lite is based on GSL: Guidelines Support Library, // https://github.com/microsoft/gsl // // Copyright (c) 2015 Martin Moene // Copyright (c) 2015 Microsoft Corporation. All rights reserved. // // This code is licensed under the MIT License (MIT). // // 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 "gsl-lite.t.h" CASE( "at(): Terminates access to non-existing C-array elements" ) { int a[] = { 1, 2, 3, 4 }; EXPECT_THROWS( at(a, 4) ); } CASE( "at(): Terminates access to non-existing std::array elements (C++11)" ) { #if gsl_HAVE_ARRAY std::array<int, 4> a = {{ 1, 2, 3, 4 }}; EXPECT_THROWS( at(a, 4) ); #else EXPECT( !!"std::array<> is not available (no C++11)" ); #endif } CASE( "at(): Terminates access to non-existing std::vector elements" ) { std::vector<int> a; // = { 1, 2, 3, 4 }; for ( int i = 0; i < 4; ++i ) { a.push_back( i + 1 ); } EXPECT_THROWS( at(a, 4) ); } CASE( "at(): Terminates access to non-existing std::initializer_list elements" ) { #if gsl_HAVE_INITIALIZER_LIST std::initializer_list<int> a = { 1, 2, 3, 4 }; EXPECT_THROWS( at(a, 4) ); #else EXPECT( !!"std::initializer_list<> is not available (no C++11)" ); #endif } CASE( "at(): Terminates access to non-existing gsl::span elements" ) { int arr[] = { 1, 2, 3, 4 }; span<int> a( arr ); EXPECT_THROWS( at(a, 4) ); } CASE( "at(): Allows access to existing C-array elements" ) { int a[] = { 1, 2, 3, 4 }; for ( int i = 0; i < 4; ++i ) { EXPECT( at(a, i) == i + 1 ); } } CASE( "at(): Allows access to existing std::array elements (C++11)" ) { #if gsl_HAVE_ARRAY std::array<int, 4> a = {{ 1, 2, 3, 4 }}; for ( int i = 0; i < 4; ++i ) { EXPECT( at(a, i) == i + 1 ); } #else EXPECT( !!"std::array<> is not available (no C++11)" ); #endif } CASE( "at(): Allows access to existing std::vector elements" ) { std::vector<int> a; // = { 1, 2, 3, 4 }; for ( int i = 0; i < 4; ++i ) { a.push_back( i + 1 ); EXPECT( at(a, i) == i + 1 ); } } CASE( "at(): Allows access to std::initializer_list elements (C++11)" ) { #if gsl_HAVE_INITIALIZER_LIST std::initializer_list<int> a = { 1, 2, 3, 4 }; for ( int i = 0; i < 4; ++i ) { EXPECT( at(a, i) == i + 1 ); } #else EXPECT( !!"std::initializer_list<> is not available (no C++11)" ); #endif } CASE( "at(): Allows access to gsl::span elements" ) { int arr[] = { 1, 2, 3, 4 }; span<int> a( arr ); for ( int i = 0; i < 4; ++i ) { EXPECT( at(a, i) == i + 1 ); } } // end of file <|endoftext|>
<commit_before>/* * This file is a part of Xpiks - cross platform application for * keywording and uploading images for microstocks * Copyright (C) 2014-2018 Taras Kushnir <kushnirTV@gmail.com> * * 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/. */ #include "globalimageprovider.h" namespace Helpers { QImage GlobalImageProvider::requestImage(const QString &url, QSize *size, const QSize &requestedSize) { QString id; if (url.contains(QChar('%'))) { QUrl initialUrl(url); id = initialUrl.path(); } else { id = url; } QImage image(id); QImage result; if (requestedSize.isValid()) { result = image.scaled(requestedSize, Qt::KeepAspectRatio, Qt::SmoothTransformation); } else { result = image; } *size = result.size(); return result; } } <commit_msg>More fixes for missing thumbnails. related #521<commit_after>/* * This file is a part of Xpiks - cross platform application for * keywording and uploading images for microstocks * Copyright (C) 2014-2018 Taras Kushnir <kushnirTV@gmail.com> * * 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/. */ #include "globalimageprovider.h" #include "../Helpers/stringhelper.h" namespace Helpers { QImage GlobalImageProvider::requestImage(const QString &url, QSize *size, const QSize &requestedSize) { QString id; if (url.contains(QChar('%'))) { id = Helpers::stringPercentDecode(url); } else { id = url; } QImage image(id); QImage result; if (requestedSize.isValid()) { result = image.scaled(requestedSize, Qt::KeepAspectRatio, Qt::SmoothTransformation); } else { result = image; } *size = result.size(); return result; } } <|endoftext|>
<commit_before>/** * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com> * All Rights Reserved. * * This file is CONFIDENTIAL -- Distribution or duplication of this material or * the information contained herein is strictly forbidden unless prior written * permission is obtained. */ #include "zbase/logjoin/stages/BuildEventsStage.h" #include "zbase/logjoin/common.h" using namespace stx; namespace zbase { void BuildEventsStage::process(RefPtr<SessionContext> ctx) { for (const auto& ev : ctx->events) { if (StringUtil::beginsWith(ev.evtype, "_")) { continue; } auto evptr = ctx->addOutputEvent( ev.time, SHA1::compute(ev.evid), ev.evtype); loadEvent(ev.data, evptr); } } void BuildEventsStage::loadEvent(const String& data, RefPtr<OutputEvent> ev) { if (StringUtil::beginsWith(data, "p")) { loadEventFromPlainJSON(data, ev); return; } RAISE(kRuntimeError, "illegal event data format"); } void BuildEventsStage::loadEventFromPlainJSON( const String& data, RefPtr<OutputEvent> ev) { auto json = json::parseJSON(URI::urlDecode(data.substr(1))); ev->obj.fromJSON(json.begin(), json.end()); } } // namespace zbase <commit_msg>set event time<commit_after>/** * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com> * All Rights Reserved. * * This file is CONFIDENTIAL -- Distribution or duplication of this material or * the information contained herein is strictly forbidden unless prior written * permission is obtained. */ #include "zbase/logjoin/stages/BuildEventsStage.h" #include "zbase/logjoin/common.h" using namespace stx; namespace zbase { void BuildEventsStage::process(RefPtr<SessionContext> ctx) { for (const auto& ev : ctx->events) { if (StringUtil::beginsWith(ev.evtype, "_")) { continue; } auto evptr = ctx->addOutputEvent( ev.time, SHA1::compute(ev.evid), ev.evtype); loadEvent(ev.data, evptr); evptr->obj.addDateTimeField("time", ev.time); } } void BuildEventsStage::loadEvent(const String& data, RefPtr<OutputEvent> ev) { if (StringUtil::beginsWith(data, "p")) { loadEventFromPlainJSON(data, ev); return; } RAISE(kRuntimeError, "illegal event data format"); } void BuildEventsStage::loadEventFromPlainJSON( const String& data, RefPtr<OutputEvent> ev) { auto json = json::parseJSON(URI::urlDecode(data.substr(1))); ev->obj.fromJSON(json.begin(), json.end()); } } // namespace zbase <|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. * * $Id$ * */ #ifndef PCL_SURFACE_IMPL_POISSON_H_ #define PCL_SURFACE_IMPL_POISSON_H_ #include "pcl/surface/poisson.h" #include <pcl/common/common.h> #include <pcl/common/vector_average.h> #include <pcl/Vertices.h> #include "pcl/surface/poisson/octree.h" #include "pcl/surface/poisson/sparse_matrix.h" #include "pcl/surface/poisson/function_data.h" #include "pcl/surface/poisson/ppolynomial.h" #include "pcl/surface/poisson/multi_grid_octree_data.h" #define MEMORY_ALLOCATOR_BLOCK_SIZE 1<<12 #include <stdarg.h> #include <string> using namespace pcl::surface::poisson; ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointNT> pcl::Poisson<PointNT>::Poisson () : no_reset_samples_ (false), no_clip_tree_ (false), confidence_ (false), manifold_ (false), depth_ (10), solver_divide_ (8), iso_divide_ (8), refine_ (3), kernel_depth_ (8), degree_ (2), samples_per_node_ (1.0), scale_ (1.25) { } ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointNT> pcl::Poisson<PointNT>::~Poisson () { } ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointNT> template <int Degree> void pcl::Poisson<PointNT>::execute (CoredMeshData &mesh, Point3D<float> &center) { float scale = 1; ////////////////////////////////// // Fix courtesy of David Gallup // // TreeNodeData::UseIndex = 1; // ////////////////////////////////// Octree<Degree> tree; PPolynomial<Degree> ReconstructionFunction = PPolynomial<Degree>::GaussianApproximation (); center.coords[0] = center.coords[1] = center.coords[2] = 0; TreeOctNode::SetAllocator(MEMORY_ALLOCATOR_BLOCK_SIZE); int kernel_depth=depth_-2; tree.setFunctionData (ReconstructionFunction,depth_, 0, float (1.0) / (1<<depth_)); tree.setTree (input_, depth_, kernel_depth, float(samples_per_node_), scale_, center, scale, !no_reset_samples_, confidence_); if(!no_clip_tree_) tree.ClipTree (); tree.finalize1 (refine_); tree.SetLaplacianWeights (); tree.finalize2 (refine_); tree.LaplacianMatrixIteration (solver_divide_); float isoValue=tree.GetIsoValue (); if (iso_divide_) tree.GetMCIsoTriangles (isoValue, iso_divide_, &mesh, 0, 1, manifold_); else tree.GetMCIsoTriangles (isoValue, &mesh, 0, 1, manifold_); } ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointNT> void pcl::Poisson<PointNT>::performReconstruction (PolygonMesh &output) { CoredVectorMeshData mesh; Point3D<float> center; switch (degree_) { case 1: execute<1> (mesh, center); break; case 2: execute<2> (mesh, center); break; case 3: execute<3> (mesh, center); break; case 4: execute<4> (mesh, center); break; case 5: execute<5> (mesh, center); break; default: PCL_ERROR (stderr,"Degree %d not supported\n", degree_); } /// Write output PolygonMesh float scale = 1; // write vertices pcl::PointCloud < pcl::PointXYZ > cloud; cloud.points.resize (int (mesh.outOfCorePointCount()+mesh.inCorePoints.size ())); Point3D<float> p; for (int i = 0; i < int (mesh.inCorePoints.size()); i++) { p = mesh.inCorePoints[i]; cloud.points[i].x = p.coords[0]*scale+center.coords[0]; cloud.points[i].y = p.coords[1]*scale+center.coords[1]; cloud.points[i].z = p.coords[2]*scale+center.coords[2]; } for (int i = int (mesh.inCorePoints.size ()); i < int (mesh.outOfCorePointCount () + mesh.inCorePoints.size ()); i++) { mesh.nextOutOfCorePoint (p); cloud.points[i].x = p.coords[0]*scale+center.coords[0]; cloud.points[i].y = p.coords[1]*scale+center.coords[1]; cloud.points[i].z = p.coords[2]*scale+center.coords[2]; } pcl::toROSMsg (cloud, output.cloud); output.polygons.resize (mesh.triangleCount ()); // Write faces TriangleIndex tIndex; int inCoreFlag; for (int i = 0; i < mesh.triangleCount(); i++) { // Create and fill a struct that the ply code can handle pcl::Vertices v; v.vertices.resize (3); mesh.nextTriangle(tIndex,inCoreFlag); if (!(inCoreFlag & CoredMeshData::IN_CORE_FLAG[0])) tIndex.idx[0] += int(mesh.inCorePoints.size()); if (!(inCoreFlag & CoredMeshData::IN_CORE_FLAG[1])) tIndex.idx[1] += int(mesh.inCorePoints.size()); if (!(inCoreFlag & CoredMeshData::IN_CORE_FLAG[2])) tIndex.idx[2] += int(mesh.inCorePoints.size()); for (int j = 0; j < 3; j++) v.vertices[j] = tIndex.idx[j]; output.polygons[i] = v; } } ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointNT> void pcl::Poisson<PointNT>::performReconstruction (pcl::PointCloud<PointNT> &points, std::vector<pcl::Vertices> &polygons) { CoredVectorMeshData mesh; Point3D<float> center; switch(degree_) { case 1: execute<1> (mesh, center); break; case 2: execute<2> (mesh, center); break; case 3: execute<3> (mesh, center); break; case 4: execute<4> (mesh, center); break; case 5: execute<5> (mesh, center); break; default: PCL_ERROR (stderr,"Degree %d not supported\n", degree_); } /// Write output PolygonMesh float scale = 1; // write vertices points.points.resize (int (mesh.outOfCorePointCount ()+mesh.inCorePoints.size ())); Point3D<float> p; for (int i = 0; i < int(mesh.inCorePoints.size()); i++) { p = mesh.inCorePoints[i]; points.points[i].x = p.coords[0]*scale+center.coords[0]; points.points[i].y = p.coords[1]*scale+center.coords[1]; points.points[i].z = p.coords[2]*scale+center.coords[2]; } for (int i = int(mesh.inCorePoints.size()); i < int (mesh.outOfCorePointCount() + mesh.inCorePoints.size ()); i++) { mesh.nextOutOfCorePoint(p); points.points[i].x = p.coords[0]*scale+center.coords[0]; points.points[i].y = p.coords[1]*scale+center.coords[1]; points.points[i].z = p.coords[2]*scale+center.coords[2]; } polygons.resize (mesh.triangleCount ()); // write faces TriangleIndex tIndex; int inCoreFlag; for (int i = 0; i < mesh.triangleCount (); i++) { // create and fill a struct that the ply code can handle pcl::Vertices v; v.vertices.resize (3); mesh.nextTriangle(tIndex,inCoreFlag); if (!(inCoreFlag & CoredMeshData::IN_CORE_FLAG[0])) tIndex.idx[0] += int(mesh.inCorePoints.size()); if (!(inCoreFlag & CoredMeshData::IN_CORE_FLAG[1])) tIndex.idx[1] += int(mesh.inCorePoints.size()); if (!(inCoreFlag & CoredMeshData::IN_CORE_FLAG[2])) tIndex.idx[2] += int(mesh.inCorePoints.size()); for (int j = 0; j < 3; j++) v.vertices[j] = tIndex.idx[j]; polygons[i] = v; } } #define PCL_INSTANTIATE_Poisson(T) template class PCL_EXPORTS pcl::Poisson<T>; #endif // PCL_SURFACE_IMPL_POISSON_H_ <commit_msg>minor<commit_after>/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2010-2012, 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. * * $Id$ * */ #ifndef PCL_SURFACE_IMPL_POISSON_H_ #define PCL_SURFACE_IMPL_POISSON_H_ #include "pcl/surface/poisson.h" #include <pcl/common/common.h> #include <pcl/common/vector_average.h> #include <pcl/Vertices.h> #include "pcl/surface/poisson/octree.h" #include "pcl/surface/poisson/sparse_matrix.h" #include "pcl/surface/poisson/function_data.h" #include "pcl/surface/poisson/ppolynomial.h" #include "pcl/surface/poisson/multi_grid_octree_data.h" #define MEMORY_ALLOCATOR_BLOCK_SIZE 1<<12 #include <stdarg.h> #include <string> using namespace pcl::surface::poisson; ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointNT> pcl::Poisson<PointNT>::Poisson () : no_reset_samples_ (false), no_clip_tree_ (false), confidence_ (false), manifold_ (false), depth_ (10), solver_divide_ (8), iso_divide_ (8), refine_ (3), kernel_depth_ (8), degree_ (2), samples_per_node_ (1.0), scale_ (1.25) { } ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointNT> pcl::Poisson<PointNT>::~Poisson () { } ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointNT> template <int Degree> void pcl::Poisson<PointNT>::execute (CoredMeshData &mesh, Point3D<float> &center) { float scale = 1; ////////////////////////////////// // Fix courtesy of David Gallup // // TreeNodeData::UseIndex = 1; // ////////////////////////////////// Octree<Degree> tree; PPolynomial<Degree> ReconstructionFunction = PPolynomial<Degree>::GaussianApproximation (); center.coords[0] = center.coords[1] = center.coords[2] = 0; TreeOctNode::SetAllocator (MEMORY_ALLOCATOR_BLOCK_SIZE); int kernel_depth=depth_-2; tree.setFunctionData (ReconstructionFunction, depth_, 0, float (1.0) / (1<<depth_)); tree.setTree (input_, depth_, kernel_depth, float(samples_per_node_), scale_, center, scale, !no_reset_samples_, confidence_); if (!no_clip_tree_) tree.ClipTree (); tree.finalize1 (refine_); tree.SetLaplacianWeights (); tree.finalize2 (refine_); tree.LaplacianMatrixIteration (solver_divide_); float isoValue=tree.GetIsoValue (); if (iso_divide_) tree.GetMCIsoTriangles (isoValue, iso_divide_, &mesh, 0, 1, manifold_); else tree.GetMCIsoTriangles (isoValue, &mesh, 0, 1, manifold_); } ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointNT> void pcl::Poisson<PointNT>::performReconstruction (PolygonMesh &output) { CoredVectorMeshData mesh; Point3D<float> center; switch (degree_) { case 1: { execute<1> (mesh, center); break; } case 2: { execute<2> (mesh, center); break; } case 3: { execute<3> (mesh, center); break; } case 4: { execute<4> (mesh, center); break; } case 5: { execute<5> (mesh, center); break; } default: { PCL_ERROR (stderr, "Degree %d not supported\n", degree_); } } /// Write output PolygonMesh float scale = 1; // write vertices pcl::PointCloud < pcl::PointXYZ > cloud; cloud.points.resize (int (mesh.outOfCorePointCount () + mesh.inCorePoints.size ())); Point3D<float> p; for (int i = 0; i < int (mesh.inCorePoints.size ()); i++) { p = mesh.inCorePoints[i]; cloud.points[i].x = p.coords[0]*scale+center.coords[0]; cloud.points[i].y = p.coords[1]*scale+center.coords[1]; cloud.points[i].z = p.coords[2]*scale+center.coords[2]; } for (int i = int (mesh.inCorePoints.size ()); i < int (mesh.outOfCorePointCount () + mesh.inCorePoints.size ()); i++) { mesh.nextOutOfCorePoint (p); cloud.points[i].x = p.coords[0]*scale+center.coords[0]; cloud.points[i].y = p.coords[1]*scale+center.coords[1]; cloud.points[i].z = p.coords[2]*scale+center.coords[2]; } pcl::toROSMsg (cloud, output.cloud); output.polygons.resize (mesh.triangleCount ()); // Write faces TriangleIndex tIndex; int inCoreFlag; for (int i = 0; i < mesh.triangleCount (); i++) { // Create and fill a struct that the ply code can handle pcl::Vertices v; v.vertices.resize (3); mesh.nextTriangle (tIndex,inCoreFlag); if (!(inCoreFlag & CoredMeshData::IN_CORE_FLAG[0])) tIndex.idx[0] += int(mesh.inCorePoints.size ()); if (!(inCoreFlag & CoredMeshData::IN_CORE_FLAG[1])) tIndex.idx[1] += int(mesh.inCorePoints.size ()); if (!(inCoreFlag & CoredMeshData::IN_CORE_FLAG[2])) tIndex.idx[2] += int(mesh.inCorePoints.size ()); for (int j = 0; j < 3; j++) v.vertices[j] = tIndex.idx[j]; output.polygons[i] = v; } } ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointNT> void pcl::Poisson<PointNT>::performReconstruction (pcl::PointCloud<PointNT> &points, std::vector<pcl::Vertices> &polygons) { CoredVectorMeshData mesh; Point3D<float> center; switch (degree_) { case 1: { execute<1> (mesh, center); break; } case 2: { execute<2> (mesh, center); break; } case 3: { execute<3> (mesh, center); break; } case 4: { execute<4> (mesh, center); break; } case 5: { execute<5> (mesh, center); break; } default: { PCL_ERROR (stderr, "Degree %d not supported\n", degree_); } } /// Write output PolygonMesh float scale = 1; // write vertices points.points.resize (int (mesh.outOfCorePointCount () + mesh.inCorePoints.size ())); Point3D<float> p; for (int i = 0; i < int(mesh.inCorePoints.size ()); i++) { p = mesh.inCorePoints[i]; points.points[i].x = p.coords[0]*scale+center.coords[0]; points.points[i].y = p.coords[1]*scale+center.coords[1]; points.points[i].z = p.coords[2]*scale+center.coords[2]; } for (int i = int(mesh.inCorePoints.size()); i < int (mesh.outOfCorePointCount() + mesh.inCorePoints.size ()); i++) { mesh.nextOutOfCorePoint (p); points.points[i].x = p.coords[0]*scale+center.coords[0]; points.points[i].y = p.coords[1]*scale+center.coords[1]; points.points[i].z = p.coords[2]*scale+center.coords[2]; } polygons.resize (mesh.triangleCount ()); // write faces TriangleIndex tIndex; int inCoreFlag; for (int i = 0; i < mesh.triangleCount (); i++) { // create and fill a struct that the ply code can handle pcl::Vertices v; v.vertices.resize (3); mesh.nextTriangle (tIndex,inCoreFlag); if (!(inCoreFlag & CoredMeshData::IN_CORE_FLAG[0])) tIndex.idx[0] += int(mesh.inCorePoints.size ()); if (!(inCoreFlag & CoredMeshData::IN_CORE_FLAG[1])) tIndex.idx[1] += int(mesh.inCorePoints.size ()); if (!(inCoreFlag & CoredMeshData::IN_CORE_FLAG[2])) tIndex.idx[2] += int(mesh.inCorePoints.size ()); for (int j = 0; j < 3; j++) v.vertices[j] = tIndex.idx[j]; polygons[i] = v; } } #define PCL_INSTANTIATE_Poisson(T) template class PCL_EXPORTS pcl::Poisson<T>; #endif // PCL_SURFACE_IMPL_POISSON_H_ <|endoftext|>
<commit_before>static const double cm=1; static const double cm3=cm*cm*cm; static const double volt=1; static const double C=1; // Coulomb static const double e=1.6e-19*C; // electron charge static const double epsilon0=8.854187817e-14*C/volt/cm; // vacuum permittivity // https://link.springer.com/chapter/10.1007/10832182_519 static const double epsilon=15.8; // Ge dielectric constant //_____________________________________________________________________________// V"(x)=a, https://www.wolframalpha.com/input/?i=f%27%27(x)%3Da double V(double *coordinates, double *parameters) { double x = coordinates[0]; double x0= parameters[0]; double x1= parameters[1]; double v0= parameters[2]; double v1= parameters[3]; double rho=parameters[4]; double a =-rho/epsilon0/epsilon; double c2= (v1-v0)/(x1-x0) - a/2*(x1+x0); double c1= (v0*x1-v1*x0)/(x1-x0) + a/2*x0*x1; return a*x*x/2 + c2*x + c1; } //_____________________________________________________________________________// E=-V' double E(double *coordinates, double *parameters) { double x = coordinates[0]; double x0= parameters[0]; double x1= parameters[1]; double v0= parameters[2]; double v1= parameters[3]; double rho=parameters[4]; double a =-rho/epsilon0/epsilon; double c2= (v1-v0)/(x1-x0) - a/2*(x1+x0); return -a*x - c2; } //_____________________________________________________________________________// const int n=5; // number of curves void drawV() { TLegend *l = new TLegend(0.15,0.60,0.40,0.95); l->SetHeader("Impurity [cm^{-3}]"); TF1 *fV[n]={0}; double x0[n]={0}, x1[n], v0[n]={0}, v1[n]; double rho[n]={-3.5e10*e/cm3, -1.5e10*e/cm3, 0, 1.5e10*e/cm3, 3.5e10*e/cm3}; for (int i=0; i<n; i++) { x1[i] = 1*cm; v1[i] = 2000*volt; fV[i] = new TF1(Form("fV%d",i), V, x0[i], x1[i], 5); fV[i]->SetParameters(x0[i],x1[i],v0[i],v1[i],rho[i]); fV[i]->SetLineStyle(i+1); fV[i]->SetLineColor(i+1); if (i+1==5) fV[i]->SetLineColor(kMagenta); // yellow -> magenta if (i==0) fV[i]->Draw(); else fV[i]->Draw("same"); l->AddEntry(fV[i],Form("%8.1e",rho[i]/e*cm3),"l"); } fV[0]->SetTitle(""); fV[0]->GetXaxis()->SetTitle("Thickness [cm]"); fV[0]->GetYaxis()->SetTitle("Voltage [V]"); l->Draw(); gPad->Print("planarV.pdf"); } //_____________________________________________________________________________ // void drawE() { TLegend *l = new TLegend(0.44,0.65,0.67,0.98); l->SetHeader("Impurity [cm^{-3}]"); TF1 *fE[n]={0}; double x0[n]={0}, x1[n], v0[n]={0}, v1[n]; double rho[n]={-3.5e10*e/cm3, -1.5e10*e/cm3, 0, 1.5e10*e/cm3, 3.5e10*e/cm3}; for (int i=0; i<n; i++) { x1[i] = 1*cm; v1[i] = 2000*volt; fE[i] = new TF1(Form("fE%d",i), E, x0[i], x1[i], 5); fE[i]->SetParameters(x0[i],x1[i],v0[i],v1[i],rho[i]); fE[i]->SetLineStyle(i+1); fE[i]->SetLineColor(i+1); if (i+1==5) fE[i]->SetLineColor(kMagenta); // yellow -> magenta if (i==0) fE[i]->Draw(); else fE[i]->Draw("same"); l->AddEntry(fE[i],Form("%8.1e",rho[i]/e*cm3),"l"); } fE[0]->SetTitle(""); fE[0]->GetXaxis()->SetTitle("Thickness [cm]"); fE[0]->GetYaxis()->SetTitle("Electric field [V/cm]"); l->Draw(); gPad->Print("planarE.pdf"); } //_____________________________________________________________________________ // void planar() { gROOT->SetStyle("Plain"); // pick up a good default drawing style // modify the default style gStyle->SetLegendBorderSize(0); gStyle->SetLegendFont(22); gStyle->SetLabelFont(22,"XY"); gStyle->SetTitleFont(22,"XY"); gStyle->SetLabelSize(0.05,"XY"); gStyle->SetTitleSize(0.05,"XY"); gStyle->SetTitleOffset(1.1,"Y"); gStyle->SetPadRightMargin(0.01); gStyle->SetPadLeftMargin(0.11); gStyle->SetPadTopMargin(0.01); gStyle->SetPadBottomMargin(0.11); drawV(); drawE(); } <commit_msg>changed output file names<commit_after>static const double cm=1; static const double cm3=cm*cm*cm; static const double volt=1; static const double C=1; // Coulomb static const double e=1.6e-19*C; // electron charge static const double epsilon0=8.854187817e-14*C/volt/cm; // vacuum permittivity // https://link.springer.com/chapter/10.1007/10832182_519 static const double epsilon=15.8; // Ge dielectric constant //_____________________________________________________________________________// V"(x)=a, https://www.wolframalpha.com/input/?i=f%27%27(x)%3Da double V(double *coordinates, double *parameters) { double x = coordinates[0]; double x0= parameters[0]; double x1= parameters[1]; double v0= parameters[2]; double v1= parameters[3]; double rho=parameters[4]; double a =-rho/epsilon0/epsilon; double c2= (v1-v0)/(x1-x0) - a/2*(x1+x0); double c1= (v0*x1-v1*x0)/(x1-x0) + a/2*x0*x1; return a*x*x/2 + c2*x + c1; } //_____________________________________________________________________________// E=-V' double E(double *coordinates, double *parameters) { double x = coordinates[0]; double x0= parameters[0]; double x1= parameters[1]; double v0= parameters[2]; double v1= parameters[3]; double rho=parameters[4]; double a =-rho/epsilon0/epsilon; double c2= (v1-v0)/(x1-x0) - a/2*(x1+x0); return -a*x - c2; } //_____________________________________________________________________________// const int n=5; // number of curves void drawV() { TLegend *l = new TLegend(0.15,0.60,0.40,0.95); l->SetHeader("Impurity [cm^{-3}]"); TF1 *fV[n]={0}; double x0[n]={0}, x1[n], v0[n]={0}, v1[n]; double rho[n]={-3.5e10*e/cm3, -1.5e10*e/cm3, 0, 1.5e10*e/cm3, 3.5e10*e/cm3}; for (int i=0; i<n; i++) { x1[i] = 1*cm; v1[i] = 2000*volt; fV[i] = new TF1(Form("fV%d",i), V, x0[i], x1[i], 5); fV[i]->SetParameters(x0[i],x1[i],v0[i],v1[i],rho[i]); fV[i]->SetLineStyle(i+1); fV[i]->SetLineColor(i+1); if (i+1==5) fV[i]->SetLineColor(kMagenta); // yellow -> magenta if (i==0) fV[i]->Draw(); else fV[i]->Draw("same"); l->AddEntry(fV[i],Form("%8.1e",rho[i]/e*cm3),"l"); } fV[0]->SetTitle(""); fV[0]->GetXaxis()->SetTitle("Thickness [cm]"); fV[0]->GetYaxis()->SetTitle("Voltage [V]"); l->Draw(); gPad->Print("Vx.pdf"); } //_____________________________________________________________________________ // void drawE() { TLegend *l = new TLegend(0.44,0.65,0.67,0.98); l->SetHeader("Impurity [cm^{-3}]"); TF1 *fE[n]={0}; double x0[n]={0}, x1[n], v0[n]={0}, v1[n]; double rho[n]={-3.5e10*e/cm3, -1.5e10*e/cm3, 0, 1.5e10*e/cm3, 3.5e10*e/cm3}; for (int i=0; i<n; i++) { x1[i] = 1*cm; v1[i] = 2000*volt; fE[i] = new TF1(Form("fE%d",i), E, x0[i], x1[i], 5); fE[i]->SetParameters(x0[i],x1[i],v0[i],v1[i],rho[i]); fE[i]->SetLineStyle(i+1); fE[i]->SetLineColor(i+1); if (i+1==5) fE[i]->SetLineColor(kMagenta); // yellow -> magenta if (i==0) fE[i]->Draw(); else fE[i]->Draw("same"); l->AddEntry(fE[i],Form("%8.1e",rho[i]/e*cm3),"l"); } fE[0]->SetTitle(""); fE[0]->GetXaxis()->SetTitle("Thickness [cm]"); fE[0]->GetYaxis()->SetTitle("Electric field [V/cm]"); l->Draw(); gPad->Print("Ex.pdf"); } //_____________________________________________________________________________ // void planar() { gROOT->SetStyle("Plain"); // pick up a good default drawing style // modify the default style gStyle->SetLegendBorderSize(0); gStyle->SetLegendFont(22); gStyle->SetLabelFont(22,"XY"); gStyle->SetTitleFont(22,"XY"); gStyle->SetLabelSize(0.05,"XY"); gStyle->SetTitleSize(0.05,"XY"); gStyle->SetTitleOffset(1.1,"Y"); gStyle->SetPadRightMargin(0.01); gStyle->SetPadLeftMargin(0.11); gStyle->SetPadTopMargin(0.01); gStyle->SetPadBottomMargin(0.11); drawV(); drawE(); } <|endoftext|>
<commit_before> #include "gtest/gtest.h" #include "Buffer.h" #include "Timing.h" #include "Log.h" #include "Network.h" #include "Socket.h" #include "TcpServer.h" #include "TcpClientFactory.h" #include "TcpClient.h" #define IP_FOR_TESTING "127.0.0.1" #define PORT_FOR_TESTING "1703" namespace { class EchoClient : public TCP::Client { public: EchoClient(std::unique_ptr<OS::Socket> inSocket) : TCP::Client (std::move (inSocket)) { } void OnReceived (const std::vector<uint8_t>& inBuffer) override { Send (inBuffer); } }; class TestClientFactory : public TCP::ClientFactory { public: std::unique_ptr<TCP::Client> Create (std::unique_ptr<OS::Socket> inSocket) const override { return std::make_unique<EchoClient> (std::move (inSocket)); } }; } // end anonymous namespace class TcpServerTester : public ::testing::Test { void SetUp () { OS::Log::Instance ().Initialize (OS::Log::kTrace); OS::Network::Initialize (); } void TearDown () { OS::Network::Done (); OS::Log::Instance ().Flush (); } }; TEST_F (TcpServerTester, OpenAndCloseConnection) { auto factory (std::make_unique<TestClientFactory>()); TCP::Server server (IP_FOR_TESTING, PORT_FOR_TESTING, std::move (factory)); server.Start(); OS::Timing::Sleep (100); OS::Socket socket(IP_FOR_TESTING, PORT_FOR_TESTING); socket.Initialize(); EXPECT_TRUE (socket.Connect()); OS::Timing::Sleep (100); const std::vector<uint8_t> bufferSend (1000u, 0xFF); EXPECT_EQ (socket.Send (bufferSend), 1000); std::vector<uint8_t> bufferReceive (1001u); EXPECT_EQ (socket.Receive (bufferReceive), 1000); EXPECT_TRUE (std::equal (bufferSend.begin(), bufferSend.end(), bufferReceive.begin())); socket.Close (); server.Stop (); } TEST_F (TcpServerTester, MultipleConnnections) { std::vector<std::unique_ptr<OS::Socket>> sockets; for (std::size_t i (0u); i < 5u; ++i) { sockets.emplace_back (std::make_unique<OS::Socket> (IP_FOR_TESTING, PORT_FOR_TESTING)); } auto factory (std::make_unique<TestClientFactory>()); TCP::Server server (IP_FOR_TESTING, PORT_FOR_TESTING, std::move (factory)); server.Start(); for (auto& socket : sockets) { socket->Initialize (); } OS::Timing::Sleep (100u); EXPECT_EQ (0u, server.GetClientCount ()); for (auto& socket : sockets) { EXPECT_TRUE (socket->Connect ()); EXPECT_TRUE (socket->IsConnected ()); } OS::Timing::Sleep (100u); EXPECT_EQ (sockets.size (), server.GetClientCount ()); for (auto& socket : sockets) { socket->Close (); EXPECT_FALSE (socket->IsConnected ()); } OS::Timing::Sleep (2000u); // Make sure cleaner ticked once EXPECT_EQ (0u, server.GetClientCount ()); server.Stop(); } TEST_F (TcpServerTester, ClosingServer) { std::vector<std::unique_ptr<OS::Socket>> sockets; for (std::size_t i (0u); i < 5u; ++i) { sockets.emplace_back (std::make_unique<OS::Socket> (IP_FOR_TESTING, PORT_FOR_TESTING)); } auto factory (std::make_unique<TestClientFactory>()); TCP::Server server (IP_FOR_TESTING, PORT_FOR_TESTING, std::move (factory)); server.Start(); for (auto& socket : sockets) { socket->Initialize (); } OS::Timing::Sleep (100u); EXPECT_EQ (0u, server.GetClientCount ()); for (auto& socket : sockets) { EXPECT_TRUE (socket->Connect ()); EXPECT_TRUE (socket->IsConnected ()); } OS::Timing::Sleep (100u); EXPECT_EQ (sockets.size (), server.GetClientCount ()); server.Stop(); OS::Timing::Sleep (100u); for (auto& socket : sockets) { std::vector<uint8_t> buffer (1u); EXPECT_LE (socket->Receive (buffer), 0); // sockets must receive before they see anything happening EXPECT_FALSE (socket->IsConnected ()); } EXPECT_EQ (0u, server.GetClientCount ()); }<commit_msg>Refactored unit test<commit_after> #include "gtest/gtest.h" #include "Buffer.h" #include "Timing.h" #include "Log.h" #include "Network.h" #include "Socket.h" #include "TcpServer.h" #include "TcpClientFactory.h" #include "TcpClient.h" #define IP_FOR_TESTING "127.0.0.1" #define PORT_FOR_TESTING "1703" namespace { class EchoClient : public TCP::Client { public: EchoClient(std::unique_ptr<OS::Socket> inSocket) : TCP::Client (std::move (inSocket)) { } void OnReceived (const std::vector<uint8_t>& inBuffer) override { Send (inBuffer); } }; class TestClientFactory : public TCP::ClientFactory { public: std::unique_ptr<TCP::Client> Create (std::unique_ptr<OS::Socket> inSocket) const override { return std::make_unique<EchoClient> (std::move (inSocket)); } }; } // end anonymous namespace class TcpServerTester : public ::testing::Test { void SetUp () { OS::Log::Instance ().Initialize (OS::Log::kTrace); OS::Network::Initialize (); } void TearDown () { OS::Network::Done (); OS::Log::Instance ().Flush (); } }; TEST_F (TcpServerTester, OpenAndCloseConnection) { const int kBufferSize (1000); auto factory (std::make_unique<TestClientFactory>()); TCP::Server server (IP_FOR_TESTING, PORT_FOR_TESTING, std::move (factory)); server.Start(); OS::Timing::Sleep (100); OS::Socket socket(IP_FOR_TESTING, PORT_FOR_TESTING); socket.Initialize(); EXPECT_TRUE (socket.Connect()); OS::Timing::Sleep (100); const std::vector<uint8_t> bufferSend (kBufferSize, 0xFF); EXPECT_EQ (socket.Send (bufferSend), kBufferSize); std::vector<uint8_t> bufferReceive (kBufferSize + 1u, 0x00); EXPECT_EQ (socket.Receive (bufferReceive), kBufferSize); EXPECT_TRUE (std::equal (bufferSend.begin(), bufferSend.end(), bufferReceive.begin())); socket.Close (); server.Stop (); } TEST_F (TcpServerTester, MultipleConnnections) { auto factory (std::make_unique<TestClientFactory>()); TCP::Server server (IP_FOR_TESTING, PORT_FOR_TESTING, std::move (factory)); server.Start(); OS::Timing::Sleep (100u); EXPECT_EQ (0u, server.GetClientCount ()); std::vector<std::unique_ptr<OS::Socket>> sockets; for (std::size_t i (0u); i < 5u; ++i) { sockets.emplace_back (std::make_unique<OS::Socket> (IP_FOR_TESTING, PORT_FOR_TESTING)); sockets.back()->Initialize(); EXPECT_TRUE (sockets.back()->Connect ()); EXPECT_TRUE (sockets.back()->IsConnected ()); } OS::Timing::Sleep (100u); EXPECT_EQ (sockets.size (), server.GetClientCount ()); for (auto& socket : sockets) { socket->Close (); EXPECT_FALSE (socket->IsConnected ()); } OS::Timing::Sleep (2000u); // Make sure cleaner ticked once EXPECT_EQ (0u, server.GetClientCount ()); server.Stop (); EXPECT_EQ (0u, server.GetClientCount ()); } TEST_F (TcpServerTester, ClosingServer) { auto factory (std::make_unique<TestClientFactory>()); TCP::Server server (IP_FOR_TESTING, PORT_FOR_TESTING, std::move (factory)); server.Start(); OS::Timing::Sleep (100u); EXPECT_EQ (0u, server.GetClientCount ()); std::vector<std::unique_ptr<OS::Socket>> sockets; for (std::size_t i (0u); i < 5u; ++i) { sockets.emplace_back (std::make_unique<OS::Socket> (IP_FOR_TESTING, PORT_FOR_TESTING)); sockets.back()->Initialize(); EXPECT_TRUE (sockets.back()->Connect ()); EXPECT_TRUE (sockets.back()->IsConnected ()); } OS::Timing::Sleep (100u); EXPECT_EQ (sockets.size (), server.GetClientCount ()); server.Stop (); OS::Timing::Sleep (100u); for (auto& socket : sockets) { std::vector<uint8_t> buffer (1u); EXPECT_LE (socket->Receive (buffer), 0); // sockets must receive before they see anything happening EXPECT_FALSE (socket->IsConnected ()); } EXPECT_EQ (0u, server.GetClientCount ()); }<|endoftext|>
<commit_before>#ifndef __STDAIR_BAS_BASCOMPARSERHELPERTYPES_HPP #define __STDAIR_BAS_BASCOMPARSERHELPERTYPES_HPP // ////////////////////////////////////////////////////////////////////// // Import section // ////////////////////////////////////////////////////////////////////// // STL #include <string> #include <sstream> // STDAIR #include <stdair/STDAIR_Types.hpp> #include <stdair/service/Logger.hpp> namespace stdair { // //////////////////////////////////////////////////////////////////// // // Parser structure helper // // //////////////////////////////////////////////////////////////////// /** Date & time element parser. */ template <int MIN = 0, int MAX = 0> struct date_time_element { unsigned int _value; // Constructors. date_time_element () { } date_time_element (const date_time_element& t) : _value (t._value) { } date_time_element (int i) : _value (i) { } // Checker. void check () const { if (_value < MIN || _value > MAX) { std::ostringstream oMessage; oMessage << "The value: " << _value << " is out of range (" << MIN << ", " << MAX << ")"; throw stdair::ParserException (oMessage.str()); } } }; /** Operator overload. */ template <int MIN, int MAX> inline date_time_element<MIN, MAX> operator* (const date_time_element<MIN, MAX>& o1, const date_time_element<MIN, MAX>& o2) { return date_time_element<MIN, MAX> (o1._value * o2._value); } template <int MIN, int MAX> inline date_time_element<MIN, MAX> operator+ (const date_time_element<MIN, MAX>& o1, const date_time_element<MIN, MAX>& o2) { return date_time_element<MIN, MAX> (o1._value + o2._value); } /** Type definitions for the date & time elements. */ typedef date_time_element<0, 23> hour_t; typedef date_time_element<0, 59> minute_t; typedef date_time_element<0, 59> second_t; typedef date_time_element<1900, 2100> year_t; typedef date_time_element<1, 12> month_t; typedef date_time_element<1, 31> day_t; } #endif // __STDAIR_BAS_BASCOMPARSERHELPERTYPES_HPP <commit_msg>[Branch 0.9.0][API] Fixed a few compilation errors with the new API.<commit_after>#ifndef __STDAIR_BAS_BASCOMPARSERHELPERTYPES_HPP #define __STDAIR_BAS_BASCOMPARSERHELPERTYPES_HPP // ////////////////////////////////////////////////////////////////////// // Import section // ////////////////////////////////////////////////////////////////////// // STL #include <string> #include <sstream> // StdAir #include <stdair/stdair_exceptions.hpp> #include <stdair/service/Logger.hpp> namespace stdair { // //////////////////////////////////////////////////////////////////// // // Parser structure helper // // //////////////////////////////////////////////////////////////////// /** Date & time element parser. */ template <int MIN = 0, int MAX = 0> struct date_time_element { unsigned int _value; // ////////// Constructors /////////// /** Default constructor. */ date_time_element () { } /** Default copy constructor. */ date_time_element (const date_time_element& t) : _value (t._value) { } /** Constructor. */ date_time_element (int i) : _value (i) { } /** Checker. */ void check () const { if (_value < MIN || _value > MAX) { std::ostringstream oMessage; oMessage << "The value: " << _value << " is out of range (" << MIN << ", " << MAX << ")"; throw stdair::ParserException (oMessage.str()); } } }; /** Operator* overload. */ template <int MIN, int MAX> inline date_time_element<MIN, MAX> operator*(const date_time_element<MIN, MAX>& o1, const date_time_element<MIN, MAX>& o2){ return date_time_element<MIN, MAX> (o1._value * o2._value); } /** Operator+ overload. */ template <int MIN, int MAX> inline date_time_element<MIN, MAX> operator+(const date_time_element<MIN, MAX>& o1, const date_time_element<MIN, MAX>& o2){ return date_time_element<MIN, MAX> (o1._value + o2._value); } /** Type definitions for the date and time elements. */ typedef date_time_element<0, 23> hour_t; typedef date_time_element<0, 59> minute_t; typedef date_time_element<0, 59> second_t; typedef date_time_element<1900, 2100> year_t; typedef date_time_element<1, 12> month_t; typedef date_time_element<1, 31> day_t; } #endif // __STDAIR_BAS_BASCOMPARSERHELPERTYPES_HPP <|endoftext|>
<commit_before>// Copyright *********************************************************** // // File ecmdQueryUser.C // // IBM Confidential // OCO Source Materials // 9400 Licensed Internal Code // (C) COPYRIGHT IBM CORP. 1996 // // The source code for this program is not published or otherwise // divested of its trade secrets, irrespective of what has been // deposited with the U.S. Copyright Office. // // End Copyright ******************************************************* /* $Header$ */ // Module Description ************************************************** // // Description: // // End Module Description ********************************************** //---------------------------------------------------------------------- // Includes //---------------------------------------------------------------------- #define ecmdQueryUser_C #include <stdio.h> #include <ecmdCommandUtils.H> #include <ecmdReturnCodes.H> #include <ecmdClientCapi.H> #include <ecmdUtils.H> #include <ecmdDataBuffer.H> #undef ecmdQueryUser_C //---------------------------------------------------------------------- // User Types //---------------------------------------------------------------------- //---------------------------------------------------------------------- // Constants //---------------------------------------------------------------------- //---------------------------------------------------------------------- // Macros //---------------------------------------------------------------------- //---------------------------------------------------------------------- // Internal Function Prototypes //---------------------------------------------------------------------- //---------------------------------------------------------------------- // Global Variables //---------------------------------------------------------------------- //--------------------------------------------------------------------- // Member Function Specifications //--------------------------------------------------------------------- int ecmdQueryUser(int argc, char* argv[]) { int rc = ECMD_SUCCESS; std::string printed; ecmdLooperData looperdata; ///< Store internal Looper data /************************************************************************/ /* Parse Common Cmdline Args */ /************************************************************************/ rc = ecmdCommandArgs(&argc, &argv); if (rc) return rc; if (argc == 0) { ecmdOutputError("ecmdquery - Too few arguments specified; you need at least a query mode.\n"); ecmdOutputError("ecmdquery - Type 'ecmdquery -h' for usage.\n"); return ECMD_INVALID_ARGS; } if (!strcmp(argv[0], "rings")) { char invmask = 'N'; char chkable = 'N'; char broadmode = 'N'; std::list<ecmdRingData> ringdata; std::list<ecmdRingData>::iterator ringit; std::list<std::string>::iterator strit; if (argc < 2) { ecmdOutputError("ecmdquery - Too few arguments specified for rings; you need at least a query rings <chipname>.\n"); ecmdOutputError("ecmdquery - Type 'ecmdquery -h' for usage.\n"); return ECMD_INVALID_ARGS; } ecmdChipData chipdata; //Setup the target that will be used to query the system config ecmdChipTarget target; target.chipType = argv[1]; target.chipTypeState = ECMD_TARGET_QUERY_FIELD_VALID; target.cageState = target.nodeState = target.slotState = target.posState = ECMD_TARGET_QUERY_WILDCARD; target.threadState = target.coreState = ECMD_TARGET_FIELD_UNUSED; /************************************************************************/ /* Kickoff Looping Stuff */ /************************************************************************/ bool validPosFound = false; rc = ecmdConfigLooperInit(target, ECMD_SELECTED_TARGETS_LOOP, looperdata); if (rc) return rc; char buf[200]; while ( ecmdConfigLooperNext(target, looperdata) ) { rc = ecmdQueryRing(target, ringdata,argv[2]); if (rc == ECMD_TARGET_NOT_CONFIGURED) { continue; } else if (rc) { printed = "ecmdquery - Error occured performing ring query on "; printed += ecmdWriteTarget(target); printed += "\n"; ecmdOutputError( printed.c_str() ); return rc; } else { validPosFound = true; } /* Let's look up other info about the chip, namely the ec level */ rc = ecmdGetChipData (target, chipdata); if (rc) { printed = "ecmdquery - Unable to lookup ec information for chip "; printed += ecmdWriteTarget(target); printed += "\n"; ecmdOutputError( printed.c_str() ); return rc; } sprintf(buf,"\nAvailable rings for %s ec %d:\n", ecmdWriteTarget(target).c_str(), chipdata.chipEc); ecmdOutput(buf); printed = "Ring Names Address Length Mask Chkable BroadSide ClockState\n"; ecmdOutput(printed.c_str()); printed = "----------------------------------- -------- ------ ---- ------- --------- ----------\n"; ecmdOutput(printed.c_str()); for (ringit = ringdata.begin(); ringit != ringdata.end(); ringit ++) { printed = ""; /* The Ring Names */ for (strit = ringit->ringNames.begin(); strit != ringit->ringNames.end(); strit ++) { if (strit != ringit->ringNames.begin()) printed += ", "; printed += (*strit); } for (int i = printed.length(); i <= 36; i++) { printed += " "; } if(ringit->hasInversionMask) { invmask = 'Y'; } else { invmask = 'N'; } if (ringit->isCheckable) { chkable = 'Y'; } else chkable = 'N'; if (ringit->supportsBroadsideLoad) { broadmode = 'Y'; } else broadmode = 'N'; sprintf(buf,"0x%.6X\t%d\t %c %c %c ", ringit->address, ringit->bitLength, invmask, chkable, broadmode); printed += buf; if (ringit->clockState == ECMD_CLOCKSTATE_UNKNOWN) printed += "UNKNOWN\n"; else if (ringit->clockState == ECMD_CLOCKSTATE_ON) printed += "ON\n"; else if (ringit->clockState == ECMD_CLOCKSTATE_OFF) printed += "OFF\n"; else if (ringit->clockState == ECMD_CLOCKSTATE_NA) printed += "NA\n"; ecmdOutput(printed.c_str()); } } if (!validPosFound) { ecmdOutputError("ecmdquery - Unable to find a valid chip to execute command on\n"); return ECMD_TARGET_NOT_CONFIGURED; } } else if (!strcmp(argv[0],"version")) { /* Let's display the dllInfo to the user */ ecmdDllInfo info; rc = ecmdQueryDllInfo(info); if (rc) { ecmdOutputError("ecmdquery - Problems occurred trying to get Dll Info\n"); return rc; } ecmdOutput("================================================\n"); printed = "Dll Type : "; if (info.dllType == ECMD_DLL_STUB) printed += "Stub\n"; else if (info.dllType == ECMD_DLL_STUB) printed += "Stub\n"; else if (info.dllType == ECMD_DLL_CRONUS) printed += "Cronus\n"; else if (info.dllType == ECMD_DLL_IPSERIES) printed += "IP-Series\n"; else if (info.dllType == ECMD_DLL_ZSERIES) printed += "Z-Series\n"; else printed = "Unknown\n"; ecmdOutput(printed.c_str()); printed = "Dll Product : "; if (info.dllProduct == ECMD_DLL_PRODUCT_ECLIPZ) printed += "Eclipz\n"; else printed += "Unknown\n"; ecmdOutput(printed.c_str()); printed = "Dll Environment : "; if (info.dllEnv == ECMD_DLL_ENV_HW) printed += "Hardware\n"; else printed += "Simulation\n"; ecmdOutput(printed.c_str()); printed = "Dll Build Date : "; printed += info.dllBuildDate; printed += "\n"; ecmdOutput(printed.c_str()); printed = "Dll Capi Version : "; printed += info.dllCapiVersion; printed += "\n"; ecmdOutput(printed.c_str()); ecmdOutput("================================================\n"); } else if (!strcmp(argv[0],"configd")) { if (argc < 2) { ecmdOutputError("ecmdquery - Too few arguments specified for configd; you need at least a query configd <chipname>.\n"); ecmdOutputError("ecmdquery - Type 'ecmdquery -h' for usage.\n"); return ECMD_INVALID_ARGS; } //Setup the target that will be used to query the system config ecmdChipTarget target; target.chipType = argv[1]; target.chipTypeState = ECMD_TARGET_QUERY_FIELD_VALID; target.cageState = target.nodeState = target.slotState = target.posState = target.threadState = target.coreState = ECMD_TARGET_QUERY_WILDCARD; if (ecmdQueryTargetConfigured(target)) { printed = "ecmdquery - Target "; printed += ecmdWriteTarget(target); printed += " is configured!\n"; ecmdOutput(printed.c_str()); } else { printed = "ecmdquery - Target "; printed += ecmdWriteTarget(target); printed += " is not configured!\n"; ecmdOutputError(printed.c_str()); return ECMD_TARGET_NOT_CONFIGURED; } } else { /* Invalid Query Mode */ ecmdOutputError("ecmdquery - Invalid Query Mode.\n"); ecmdOutputError("ecmdquery - Type 'ecmdquery -h' for usage.\n"); return ECMD_INVALID_ARGS; } return rc; } // Change Log ********************************************************* // // Flag Reason Vers Date Coder Description // ---- -------- ---- -------- -------- ------------------------------ // CENGEL Initial Creation // // End Change Log ***************************************************** <commit_msg>Added ecmdquery format function<commit_after>// Copyright *********************************************************** // // File ecmdQueryUser.C // // IBM Confidential // OCO Source Materials // 9400 Licensed Internal Code // (C) COPYRIGHT IBM CORP. 1996 // // The source code for this program is not published or otherwise // divested of its trade secrets, irrespective of what has been // deposited with the U.S. Copyright Office. // // End Copyright ******************************************************* /* $Header$ */ // Module Description ************************************************** // // Description: // // End Module Description ********************************************** //---------------------------------------------------------------------- // Includes //---------------------------------------------------------------------- #define ecmdQueryUser_C #include <stdio.h> #include <ecmdCommandUtils.H> #include <ecmdReturnCodes.H> #include <ecmdClientCapi.H> #include <ecmdUtils.H> #include <ecmdDataBuffer.H> #undef ecmdQueryUser_C //---------------------------------------------------------------------- // User Types //---------------------------------------------------------------------- //---------------------------------------------------------------------- // Constants //---------------------------------------------------------------------- //---------------------------------------------------------------------- // Macros //---------------------------------------------------------------------- //---------------------------------------------------------------------- // Internal Function Prototypes //---------------------------------------------------------------------- //---------------------------------------------------------------------- // Global Variables //---------------------------------------------------------------------- //--------------------------------------------------------------------- // Member Function Specifications //--------------------------------------------------------------------- int ecmdQueryUser(int argc, char* argv[]) { int rc = ECMD_SUCCESS; std::string printed; ecmdLooperData looperdata; ///< Store internal Looper data /************************************************************************/ /* Parse Common Cmdline Args */ /************************************************************************/ rc = ecmdCommandArgs(&argc, &argv); if (rc) return rc; if (argc == 0) { ecmdOutputError("ecmdquery - Too few arguments specified; you need at least a query mode.\n"); ecmdOutputError("ecmdquery - Type 'ecmdquery -h' for usage.\n"); return ECMD_INVALID_ARGS; } if (!strcmp(argv[0], "rings")) { char invmask = 'N'; char chkable = 'N'; char broadmode = 'N'; std::list<ecmdRingData> ringdata; std::list<ecmdRingData>::iterator ringit; std::list<std::string>::iterator strit; if (argc < 2) { ecmdOutputError("ecmdquery - Too few arguments specified for rings; you need at least a query rings <chipname>.\n"); ecmdOutputError("ecmdquery - Type 'ecmdquery -h' for usage.\n"); return ECMD_INVALID_ARGS; } ecmdChipData chipdata; //Setup the target that will be used to query the system config ecmdChipTarget target; target.chipType = argv[1]; target.chipTypeState = ECMD_TARGET_QUERY_FIELD_VALID; target.cageState = target.nodeState = target.slotState = target.posState = ECMD_TARGET_QUERY_WILDCARD; target.threadState = target.coreState = ECMD_TARGET_FIELD_UNUSED; /************************************************************************/ /* Kickoff Looping Stuff */ /************************************************************************/ bool validPosFound = false; rc = ecmdConfigLooperInit(target, ECMD_SELECTED_TARGETS_LOOP, looperdata); if (rc) return rc; char buf[200]; while ( ecmdConfigLooperNext(target, looperdata) ) { rc = ecmdQueryRing(target, ringdata,argv[2]); if (rc == ECMD_TARGET_NOT_CONFIGURED) { continue; } else if (rc) { printed = "ecmdquery - Error occured performing ring query on "; printed += ecmdWriteTarget(target); printed += "\n"; ecmdOutputError( printed.c_str() ); return rc; } else { validPosFound = true; } /* Let's look up other info about the chip, namely the ec level */ rc = ecmdGetChipData (target, chipdata); if (rc) { printed = "ecmdquery - Unable to lookup ec information for chip "; printed += ecmdWriteTarget(target); printed += "\n"; ecmdOutputError( printed.c_str() ); return rc; } sprintf(buf,"\nAvailable rings for %s ec %d:\n", ecmdWriteTarget(target).c_str(), chipdata.chipEc); ecmdOutput(buf); printed = "Ring Names Address Length Mask Chkable BroadSide ClockState\n"; ecmdOutput(printed.c_str()); printed = "----------------------------------- -------- ------ ---- ------- --------- ----------\n"; ecmdOutput(printed.c_str()); for (ringit = ringdata.begin(); ringit != ringdata.end(); ringit ++) { printed = ""; /* The Ring Names */ for (strit = ringit->ringNames.begin(); strit != ringit->ringNames.end(); strit ++) { if (strit != ringit->ringNames.begin()) printed += ", "; printed += (*strit); } for (int i = printed.length(); i <= 36; i++) { printed += " "; } if(ringit->hasInversionMask) { invmask = 'Y'; } else { invmask = 'N'; } if (ringit->isCheckable) { chkable = 'Y'; } else chkable = 'N'; if (ringit->supportsBroadsideLoad) { broadmode = 'Y'; } else broadmode = 'N'; sprintf(buf,"0x%.6X\t%d\t %c %c %c ", ringit->address, ringit->bitLength, invmask, chkable, broadmode); printed += buf; if (ringit->clockState == ECMD_CLOCKSTATE_UNKNOWN) printed += "UNKNOWN\n"; else if (ringit->clockState == ECMD_CLOCKSTATE_ON) printed += "ON\n"; else if (ringit->clockState == ECMD_CLOCKSTATE_OFF) printed += "OFF\n"; else if (ringit->clockState == ECMD_CLOCKSTATE_NA) printed += "NA\n"; ecmdOutput(printed.c_str()); } } if (!validPosFound) { ecmdOutputError("ecmdquery - Unable to find a valid chip to execute command on\n"); return ECMD_TARGET_NOT_CONFIGURED; } } else if (!strcmp(argv[0],"version")) { /* Let's display the dllInfo to the user */ ecmdDllInfo info; rc = ecmdQueryDllInfo(info); if (rc) { ecmdOutputError("ecmdquery - Problems occurred trying to get Dll Info\n"); return rc; } ecmdOutput("================================================\n"); printed = "Dll Type : "; if (info.dllType == ECMD_DLL_STUB) printed += "Stub\n"; else if (info.dllType == ECMD_DLL_STUB) printed += "Stub\n"; else if (info.dllType == ECMD_DLL_CRONUS) printed += "Cronus\n"; else if (info.dllType == ECMD_DLL_IPSERIES) printed += "IP-Series\n"; else if (info.dllType == ECMD_DLL_ZSERIES) printed += "Z-Series\n"; else printed = "Unknown\n"; ecmdOutput(printed.c_str()); printed = "Dll Product : "; if (info.dllProduct == ECMD_DLL_PRODUCT_ECLIPZ) printed += "Eclipz\n"; else printed += "Unknown\n"; ecmdOutput(printed.c_str()); printed = "Dll Environment : "; if (info.dllEnv == ECMD_DLL_ENV_HW) printed += "Hardware\n"; else printed += "Simulation\n"; ecmdOutput(printed.c_str()); printed = "Dll Build Date : "; printed += info.dllBuildDate; printed += "\n"; ecmdOutput(printed.c_str()); printed = "Dll Capi Version : "; printed += info.dllCapiVersion; printed += "\n"; ecmdOutput(printed.c_str()); ecmdOutput("================================================\n"); } else if (!strcmp(argv[0],"configd")) { if (argc < 2) { ecmdOutputError("ecmdquery - Too few arguments specified for configd; you need at least a query configd <chipname>.\n"); ecmdOutputError("ecmdquery - Type 'ecmdquery -h' for usage.\n"); return ECMD_INVALID_ARGS; } //Setup the target that will be used to query the system config ecmdChipTarget target; target.chipType = argv[1]; target.chipTypeState = ECMD_TARGET_QUERY_FIELD_VALID; target.cageState = target.nodeState = target.slotState = target.posState = target.threadState = target.coreState = ECMD_TARGET_QUERY_WILDCARD; if (ecmdQueryTargetConfigured(target)) { printed = "ecmdquery - Target "; printed += ecmdWriteTarget(target); printed += " is configured!\n"; ecmdOutput(printed.c_str()); } else { printed = "ecmdquery - Target "; printed += ecmdWriteTarget(target); printed += " is not configured!\n"; ecmdOutputError(printed.c_str()); return ECMD_TARGET_NOT_CONFIGURED; } } else if ("format") { /* We will just print this from the format helpfile */ return ecmdPrintHelp("format"); } else { /* Invalid Query Mode */ ecmdOutputError("ecmdquery - Invalid Query Mode.\n"); ecmdOutputError("ecmdquery - Type 'ecmdquery -h' for usage.\n"); return ECMD_INVALID_ARGS; } return rc; } // Change Log ********************************************************* // // Flag Reason Vers Date Coder Description // ---- -------- ---- -------- -------- ------------------------------ // CENGEL Initial Creation // // End Change Log ***************************************************** <|endoftext|>
<commit_before>#ifndef STAN_MATH_PRIM_MAT_FUN_ORDERED_CONSTRAIN_HPP #define STAN_MATH_PRIM_MAT_FUN_ORDERED_CONSTRAIN_HPP #include <stan/math/prim/mat/fun/Eigen.hpp> #include <stan/math/prim/mat/meta/index_type.hpp> #include <cmath> namespace stan { namespace math { /** * Return an increasing ordered vector derived from the specified * free vector. The returned constrained vector will have the * same dimensionality as the specified free vector. * * @param x Free vector of scalars. * @return Positive, increasing ordered vector. * @tparam T Type of scalar. */ template <typename T> Eigen::Matrix<T, Eigen::Dynamic, 1> ordered_constrain( const Eigen::Matrix<T, Eigen::Dynamic, 1>& x) { using Eigen::Dynamic; using Eigen::Matrix; using std::exp; typedef typename index_type<Matrix<T, Dynamic, 1> >::type size_type; size_type k = x.size(); Matrix<T, Dynamic, 1> y(k); if (k == 0) return y; y[0] = x[0]; for (size_type i = 1; i < k; ++i) y[i] = y[i - 1] + exp(x[i]); return y; } /** * Return a positive valued, increasing ordered vector derived * from the specified free vector and increment the specified log * probability reference with the log absolute Jacobian determinant * of the transform. The returned constrained vector * will have the same dimensionality as the specified free vector. * * @param x Free vector of scalars. * @param lp Log probability reference. * @return Positive, increasing ordered vector. * @tparam T Type of scalar. */ template <typename T> inline Eigen::Matrix<T, Eigen::Dynamic, 1> ordered_constrain( const Eigen::Matrix<T, Eigen::Dynamic, 1>& x, T& lp) { using Eigen::Dynamic; using Eigen::Matrix; typedef typename index_type<Matrix<T, Dynamic, 1> >::type size_type; for (size_type i = 1; i < x.size(); ++i) lp += x(i); return ordered_constrain(x); } } // namespace math } // namespace stan #endif <commit_msg>meta include<commit_after>#ifndef STAN_MATH_PRIM_MAT_FUN_ORDERED_CONSTRAIN_HPP #define STAN_MATH_PRIM_MAT_FUN_ORDERED_CONSTRAIN_HPP #include <stan/math/prim/meta.hpp> #include <stan/math/prim/mat/fun/Eigen.hpp> #include <cmath> namespace stan { namespace math { /** * Return an increasing ordered vector derived from the specified * free vector. The returned constrained vector will have the * same dimensionality as the specified free vector. * * @param x Free vector of scalars. * @return Positive, increasing ordered vector. * @tparam T Type of scalar. */ template <typename T> Eigen::Matrix<T, Eigen::Dynamic, 1> ordered_constrain( const Eigen::Matrix<T, Eigen::Dynamic, 1>& x) { using Eigen::Dynamic; using Eigen::Matrix; using std::exp; typedef typename index_type<Matrix<T, Dynamic, 1> >::type size_type; size_type k = x.size(); Matrix<T, Dynamic, 1> y(k); if (k == 0) return y; y[0] = x[0]; for (size_type i = 1; i < k; ++i) y[i] = y[i - 1] + exp(x[i]); return y; } /** * Return a positive valued, increasing ordered vector derived * from the specified free vector and increment the specified log * probability reference with the log absolute Jacobian determinant * of the transform. The returned constrained vector * will have the same dimensionality as the specified free vector. * * @param x Free vector of scalars. * @param lp Log probability reference. * @return Positive, increasing ordered vector. * @tparam T Type of scalar. */ template <typename T> inline Eigen::Matrix<T, Eigen::Dynamic, 1> ordered_constrain( const Eigen::Matrix<T, Eigen::Dynamic, 1>& x, T& lp) { using Eigen::Dynamic; using Eigen::Matrix; typedef typename index_type<Matrix<T, Dynamic, 1> >::type size_type; for (size_type i = 1; i < x.size(); ++i) lp += x(i); return ordered_constrain(x); } } // namespace math } // namespace stan #endif <|endoftext|>
<commit_before>/* * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /* * Copyright (C) 2017 The Android Open Source Project * * Modified by joogab yun(joogab.yun@samsung.com) */ // CLASS HEADER #include "focus-finder.h" // EXTERNAL INCLUDES #include <dali/devel-api/actors/actor-devel.h> #include <dali/integration-api/adaptor-framework/scene-holder.h> #include <dali/public-api/actors/layer.h> namespace Dali { namespace Toolkit { namespace FocusFinder { namespace { static constexpr float FULLY_TRANSPARENT(0.01f); ///< Alpha values must rise above this, before an object is considered to be visible. static int MajorAxisDistanceRaw(Dali::Toolkit::Control::KeyboardFocus::Direction direction, Dali::Rect<float> source, Dali::Rect<float> dest) { switch(direction) { case Dali::Toolkit::Control::KeyboardFocus::LEFT: { return source.left - dest.right; } case Dali::Toolkit::Control::KeyboardFocus::RIGHT: { return dest.left - source.right; } case Dali::Toolkit::Control::KeyboardFocus::UP: { return source.top - dest.bottom; } case Dali::Toolkit::Control::KeyboardFocus::DOWN: { return dest.top - source.bottom; } default: { return 0; } } } /** * @return The distance from the edge furthest in the given direction * of source to the edge nearest in the given direction of dest. * If the dest is not in the direction from source, return 0. */ static int MajorAxisDistance(Dali::Toolkit::Control::KeyboardFocus::Direction direction, Dali::Rect<float> source, Dali::Rect<float> dest) { return std::max(0, MajorAxisDistanceRaw(direction, source, dest)); } static int MajorAxisDistanceToFarEdgeRaw(Dali::Toolkit::Control::KeyboardFocus::Direction direction, Dali::Rect<float> source, Dali::Rect<float> dest) { switch(direction) { case Dali::Toolkit::Control::KeyboardFocus::LEFT: { return source.left - dest.left; } case Dali::Toolkit::Control::KeyboardFocus::RIGHT: { return dest.right - source.right; } case Dali::Toolkit::Control::KeyboardFocus::UP: { return source.top - dest.top; } case Dali::Toolkit::Control::KeyboardFocus::DOWN: { return dest.bottom - source.bottom; } default: { return 0; } } } /** * @return The distance along the major axis w.r.t the direction from the * edge of source to the far edge of dest. * If the dest is not in the direction from source, return 1 */ static int MajorAxisDistanceToFarEdge(Dali::Toolkit::Control::KeyboardFocus::Direction direction, Dali::Rect<float> source, Dali::Rect<float> dest) { return std::max(1, MajorAxisDistanceToFarEdgeRaw(direction, source, dest)); } /** * Find the distance on the minor axis w.r.t the direction to the nearest * edge of the destination rectangle. * @param direction the direction (up, down, left, right) * @param source The source rect. * @param dest The destination rect. * @return The distance. */ static int MinorAxisDistance(Dali::Toolkit::Control::KeyboardFocus::Direction direction, Dali::Rect<float> source, Dali::Rect<float> dest) { switch(direction) { case Dali::Toolkit::Control::KeyboardFocus::LEFT: case Dali::Toolkit::Control::KeyboardFocus::RIGHT: { // the distance between the center verticals return std::abs((source.top + (source.bottom - source.top) * 0.5f) - (dest.top + (dest.bottom - dest.top) * 0.5f)); } case Dali::Toolkit::Control::KeyboardFocus::UP: case Dali::Toolkit::Control::KeyboardFocus::DOWN: { // the distance between the center horizontals return std::abs((source.left + (source.right - source.left) * 0.5f) - (dest.left + (dest.right - dest.left) * 0.5f)); } default: { return 0; } } } /** * Calculate distance given major and minor axis distances. * @param majorAxisDistance The majorAxisDistance * @param minorAxisDistance The minorAxisDistance * @return The distance */ static int GetWeightedDistanceFor(int majorAxisDistance, int minorAxisDistance) { return 13 * majorAxisDistance * majorAxisDistance + minorAxisDistance * minorAxisDistance; } /** * Convert x,y,width,height coordinates into left, right, bottom, top coordinates. * @param[in,out] rect The rect */ static void ConvertCoordinate(Dali::Rect<float>& rect) { // convert x, y, width, height -> left, right, bottom, top float left = rect.x; float right = rect.x + rect.width; float bottom = rect.y + rect.height; float top = rect.y; rect.left = left; rect.right = right; rect.bottom = bottom; rect.top = top; } /** * Is destRect a candidate for the next focus given the direction? * @param srcRect The source rect. * @param destRect The dest rect. * @param direction The direction (up, down, left, right) * @return Whether destRect is a candidate. */ static bool IsCandidate(Dali::Rect<float> srcRect, Dali::Rect<float> destRect, Dali::Toolkit::Control::KeyboardFocus::Direction direction) { switch(direction) { case Dali::Toolkit::Control::KeyboardFocus::LEFT: { return (srcRect.right > destRect.right || srcRect.left >= destRect.right) && srcRect.left > destRect.left; } case Dali::Toolkit::Control::KeyboardFocus::RIGHT: { return (srcRect.left < destRect.left || srcRect.right <= destRect.left) && srcRect.right < destRect.right; } case Dali::Toolkit::Control::KeyboardFocus::UP: { return (srcRect.bottom > destRect.bottom || srcRect.top >= destRect.bottom) && srcRect.top > destRect.top; } case Dali::Toolkit::Control::KeyboardFocus::DOWN: { return (srcRect.top < destRect.top || srcRect.bottom <= destRect.top) && srcRect.bottom < destRect.bottom; } default: { return false; } } return false; } /** * Is dest in a given direction from src? * @param direction the direction (up, down, left, right) * @param src The source rect * @param dest The dest rect */ static bool IsToDirectionOf(Dali::Toolkit::Control::KeyboardFocus::Direction direction, Dali::Rect<float> src, Dali::Rect<float> dest) { switch(direction) { case Dali::Toolkit::Control::KeyboardFocus::LEFT: { return src.left >= dest.right; } case Dali::Toolkit::Control::KeyboardFocus::RIGHT: { return src.right <= dest.left; } case Dali::Toolkit::Control::KeyboardFocus::UP: { return src.top >= dest.bottom; } case Dali::Toolkit::Control::KeyboardFocus::DOWN: { return src.bottom <= dest.top; } default: { return false; } } } /** * Do the given direction's axis of rect1 and rect2 overlap? * @param direction the direction (up, down, left, right) * @param rect1 The first rect * @param rect2 The second rect * @return whether the beams overlap */ static bool BeamsOverlap(Dali::Toolkit::Control::KeyboardFocus::Direction direction, Dali::Rect<float> rect1, Dali::Rect<float> rect2) { switch(direction) { case Dali::Toolkit::Control::KeyboardFocus::LEFT: case Dali::Toolkit::Control::KeyboardFocus::RIGHT: { return (rect2.bottom >= rect1.top) && (rect2.top <= rect1.bottom); } case Dali::Toolkit::Control::KeyboardFocus::UP: case Dali::Toolkit::Control::KeyboardFocus::DOWN: { return (rect2.right >= rect1.left) && (rect2.left <= rect1.right); } default: { return false; } } } /** * One rectangle may be another candidate than another by virtue of being exclusively in the beam of the source rect. * @param direction The direction (up, down, left, right) * @param source The source rect * @param rect1 The first rect * @param rect2 The second rect * @return Whether rect1 is a better candidate than rect2 by virtue of it being in src's beam */ static bool BeamBeats(Dali::Toolkit::Control::KeyboardFocus::Direction direction, Dali::Rect<float> source, Dali::Rect<float> rect1, Dali::Rect<float> rect2) { const bool rect1InSrcBeam = BeamsOverlap(direction, source, rect1); const bool rect2InSrcBeam = BeamsOverlap(direction, source, rect2); // if rect1 isn't exclusively in the src beam, it doesn't win if(rect2InSrcBeam || !rect1InSrcBeam) { return false; } // we know rect1 is in the beam, and rect2 is not // if rect1 is to the direction of, and rect2 is not, rect1 wins. // for example, for direction left, if rect1 is to the left of the source // and rect2 is below, then we always prefer the in beam rect1, since rect2 // could be reached by going down. if(!IsToDirectionOf(direction, source, rect2)) { return true; } // for horizontal directions, being exclusively in beam always wins if((direction == Dali::Toolkit::Control::KeyboardFocus::LEFT || direction == Dali::Toolkit::Control::KeyboardFocus::RIGHT)) { return true; } // for vertical directions, beams only beat up to a point: // now, as long as rect2 isn't completely closer, rect1 wins // e.g for direction down, completely closer means for rect2's top // edge to be closer to the source's top edge than rect1's bottom edge. return (MajorAxisDistance(direction, source, rect1) < MajorAxisDistanceToFarEdge(direction, source, rect2)); } bool IsBetterCandidate(Toolkit::Control::KeyboardFocus::Direction direction, Rect<float>& focusedRect, Rect<float>& candidateRect, Rect<float>& bestCandidateRect) { // to be a better candidate, need to at least be a candidate in the first place if(!IsCandidate(focusedRect, candidateRect, direction)) { return false; } // we know that candidateRect is a candidate.. if bestCandidateRect is not a candidate, // candidateRect is better if(!IsCandidate(focusedRect, bestCandidateRect, direction)) { return true; } // if candidateRect is better by beam, it wins if(BeamBeats(direction, focusedRect, candidateRect, bestCandidateRect)) { return true; } // if bestCandidateRect is better, then candidateRect cant' be :) if(BeamBeats(direction, focusedRect, bestCandidateRect, candidateRect)) { return false; } // otherwise, do fudge-tastic comparison of the major and minor axis return (GetWeightedDistanceFor( MajorAxisDistance(direction, focusedRect, candidateRect), MinorAxisDistance(direction, focusedRect, candidateRect)) < GetWeightedDistanceFor(MajorAxisDistance(direction, focusedRect, bestCandidateRect), MinorAxisDistance(direction, focusedRect, bestCandidateRect))); } bool IsFocusable(Actor& actor) { return (actor.GetProperty<bool>(Actor::Property::KEYBOARD_FOCUSABLE) && actor.GetProperty<bool>(Actor::Property::VISIBLE) && actor.GetProperty<bool>(Actor::Property::SENSITIVE) && actor.GetProperty<Vector4>(Actor::Property::WORLD_COLOR).a > FULLY_TRANSPARENT); } Actor FindNextFocus(Actor& actor, Actor& focusedActor, Rect<float>& focusedRect, Rect<float>& bestCandidateRect, Toolkit::Control::KeyboardFocus::Direction direction) { Actor nearestActor; if(actor) { // Recursively children const auto childCount = actor.GetChildCount(); for(auto i = 0u; i < childCount; ++i) { Dali::Actor child = actor.GetChildAt(i); if(child && child != focusedActor && IsFocusable(child)) { Rect<float> candidateRect = DevelActor::CalculateScreenExtents(child); // convert x, y, width, height -> left, right, bottom, top ConvertCoordinate(candidateRect); if(IsBetterCandidate(direction, focusedRect, candidateRect, bestCandidateRect)) { bestCandidateRect = candidateRect; nearestActor = child; } } Actor nextActor = FindNextFocus(child, focusedActor, focusedRect, bestCandidateRect, direction); if(nextActor) { nearestActor = nextActor; } } } return nearestActor; } } // unnamed namespace Actor GetNearestFocusableActor(Actor focusedActor, Toolkit::Control::KeyboardFocus::Direction direction) { Actor nearestActor; if(!focusedActor) { return nearestActor; } Rect<float> focusedRect = DevelActor::CalculateScreenExtents(focusedActor); // initialize the best candidate to something impossible // (so the first plausible actor will become the best choice) Rect<float> bestCandidateRect = focusedRect; switch(direction) { case Toolkit::Control::KeyboardFocus::LEFT: { bestCandidateRect.x += 1; break; } case Toolkit::Control::KeyboardFocus::RIGHT: { bestCandidateRect.x -= 1; break; } case Toolkit::Control::KeyboardFocus::UP: { bestCandidateRect.y += 1; break; } case Toolkit::Control::KeyboardFocus::DOWN: { bestCandidateRect.y -= 1; break; } default: { break; } } ConvertCoordinate(bestCandidateRect); ConvertCoordinate(focusedRect); Integration::SceneHolder window = Integration::SceneHolder::Get(focusedActor); if(window) { Actor rootActor = window.GetRootLayer(); nearestActor = FindNextFocus(rootActor, focusedActor, focusedRect, bestCandidateRect, direction); } return nearestActor; } } // namespace FocusFinder } // namespace Toolkit } // namespace Dali <commit_msg>If parent is hidden, the child cannot be focused.<commit_after>/* * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /* * Copyright (C) 2017 The Android Open Source Project * * Modified by joogab yun(joogab.yun@samsung.com) */ // CLASS HEADER #include "focus-finder.h" // EXTERNAL INCLUDES #include <dali/devel-api/actors/actor-devel.h> #include <dali/integration-api/adaptor-framework/scene-holder.h> #include <dali/public-api/actors/layer.h> namespace Dali { namespace Toolkit { namespace FocusFinder { namespace { static constexpr float FULLY_TRANSPARENT(0.01f); ///< Alpha values must rise above this, before an object is considered to be visible. static int MajorAxisDistanceRaw(Dali::Toolkit::Control::KeyboardFocus::Direction direction, Dali::Rect<float> source, Dali::Rect<float> dest) { switch(direction) { case Dali::Toolkit::Control::KeyboardFocus::LEFT: { return source.left - dest.right; } case Dali::Toolkit::Control::KeyboardFocus::RIGHT: { return dest.left - source.right; } case Dali::Toolkit::Control::KeyboardFocus::UP: { return source.top - dest.bottom; } case Dali::Toolkit::Control::KeyboardFocus::DOWN: { return dest.top - source.bottom; } default: { return 0; } } } /** * @return The distance from the edge furthest in the given direction * of source to the edge nearest in the given direction of dest. * If the dest is not in the direction from source, return 0. */ static int MajorAxisDistance(Dali::Toolkit::Control::KeyboardFocus::Direction direction, Dali::Rect<float> source, Dali::Rect<float> dest) { return std::max(0, MajorAxisDistanceRaw(direction, source, dest)); } static int MajorAxisDistanceToFarEdgeRaw(Dali::Toolkit::Control::KeyboardFocus::Direction direction, Dali::Rect<float> source, Dali::Rect<float> dest) { switch(direction) { case Dali::Toolkit::Control::KeyboardFocus::LEFT: { return source.left - dest.left; } case Dali::Toolkit::Control::KeyboardFocus::RIGHT: { return dest.right - source.right; } case Dali::Toolkit::Control::KeyboardFocus::UP: { return source.top - dest.top; } case Dali::Toolkit::Control::KeyboardFocus::DOWN: { return dest.bottom - source.bottom; } default: { return 0; } } } /** * @return The distance along the major axis w.r.t the direction from the * edge of source to the far edge of dest. * If the dest is not in the direction from source, return 1 */ static int MajorAxisDistanceToFarEdge(Dali::Toolkit::Control::KeyboardFocus::Direction direction, Dali::Rect<float> source, Dali::Rect<float> dest) { return std::max(1, MajorAxisDistanceToFarEdgeRaw(direction, source, dest)); } /** * Find the distance on the minor axis w.r.t the direction to the nearest * edge of the destination rectangle. * @param direction the direction (up, down, left, right) * @param source The source rect. * @param dest The destination rect. * @return The distance. */ static int MinorAxisDistance(Dali::Toolkit::Control::KeyboardFocus::Direction direction, Dali::Rect<float> source, Dali::Rect<float> dest) { switch(direction) { case Dali::Toolkit::Control::KeyboardFocus::LEFT: case Dali::Toolkit::Control::KeyboardFocus::RIGHT: { // the distance between the center verticals return std::abs((source.top + (source.bottom - source.top) * 0.5f) - (dest.top + (dest.bottom - dest.top) * 0.5f)); } case Dali::Toolkit::Control::KeyboardFocus::UP: case Dali::Toolkit::Control::KeyboardFocus::DOWN: { // the distance between the center horizontals return std::abs((source.left + (source.right - source.left) * 0.5f) - (dest.left + (dest.right - dest.left) * 0.5f)); } default: { return 0; } } } /** * Calculate distance given major and minor axis distances. * @param majorAxisDistance The majorAxisDistance * @param minorAxisDistance The minorAxisDistance * @return The distance */ static int GetWeightedDistanceFor(int majorAxisDistance, int minorAxisDistance) { return 13 * majorAxisDistance * majorAxisDistance + minorAxisDistance * minorAxisDistance; } /** * Convert x,y,width,height coordinates into left, right, bottom, top coordinates. * @param[in,out] rect The rect */ static void ConvertCoordinate(Dali::Rect<float>& rect) { // convert x, y, width, height -> left, right, bottom, top float left = rect.x; float right = rect.x + rect.width; float bottom = rect.y + rect.height; float top = rect.y; rect.left = left; rect.right = right; rect.bottom = bottom; rect.top = top; } /** * Is destRect a candidate for the next focus given the direction? * @param srcRect The source rect. * @param destRect The dest rect. * @param direction The direction (up, down, left, right) * @return Whether destRect is a candidate. */ static bool IsCandidate(Dali::Rect<float> srcRect, Dali::Rect<float> destRect, Dali::Toolkit::Control::KeyboardFocus::Direction direction) { switch(direction) { case Dali::Toolkit::Control::KeyboardFocus::LEFT: { return (srcRect.right > destRect.right || srcRect.left >= destRect.right) && srcRect.left > destRect.left; } case Dali::Toolkit::Control::KeyboardFocus::RIGHT: { return (srcRect.left < destRect.left || srcRect.right <= destRect.left) && srcRect.right < destRect.right; } case Dali::Toolkit::Control::KeyboardFocus::UP: { return (srcRect.bottom > destRect.bottom || srcRect.top >= destRect.bottom) && srcRect.top > destRect.top; } case Dali::Toolkit::Control::KeyboardFocus::DOWN: { return (srcRect.top < destRect.top || srcRect.bottom <= destRect.top) && srcRect.bottom < destRect.bottom; } default: { return false; } } return false; } /** * Is dest in a given direction from src? * @param direction the direction (up, down, left, right) * @param src The source rect * @param dest The dest rect */ static bool IsToDirectionOf(Dali::Toolkit::Control::KeyboardFocus::Direction direction, Dali::Rect<float> src, Dali::Rect<float> dest) { switch(direction) { case Dali::Toolkit::Control::KeyboardFocus::LEFT: { return src.left >= dest.right; } case Dali::Toolkit::Control::KeyboardFocus::RIGHT: { return src.right <= dest.left; } case Dali::Toolkit::Control::KeyboardFocus::UP: { return src.top >= dest.bottom; } case Dali::Toolkit::Control::KeyboardFocus::DOWN: { return src.bottom <= dest.top; } default: { return false; } } } /** * Do the given direction's axis of rect1 and rect2 overlap? * @param direction the direction (up, down, left, right) * @param rect1 The first rect * @param rect2 The second rect * @return whether the beams overlap */ static bool BeamsOverlap(Dali::Toolkit::Control::KeyboardFocus::Direction direction, Dali::Rect<float> rect1, Dali::Rect<float> rect2) { switch(direction) { case Dali::Toolkit::Control::KeyboardFocus::LEFT: case Dali::Toolkit::Control::KeyboardFocus::RIGHT: { return (rect2.bottom >= rect1.top) && (rect2.top <= rect1.bottom); } case Dali::Toolkit::Control::KeyboardFocus::UP: case Dali::Toolkit::Control::KeyboardFocus::DOWN: { return (rect2.right >= rect1.left) && (rect2.left <= rect1.right); } default: { return false; } } } /** * One rectangle may be another candidate than another by virtue of being exclusively in the beam of the source rect. * @param direction The direction (up, down, left, right) * @param source The source rect * @param rect1 The first rect * @param rect2 The second rect * @return Whether rect1 is a better candidate than rect2 by virtue of it being in src's beam */ static bool BeamBeats(Dali::Toolkit::Control::KeyboardFocus::Direction direction, Dali::Rect<float> source, Dali::Rect<float> rect1, Dali::Rect<float> rect2) { const bool rect1InSrcBeam = BeamsOverlap(direction, source, rect1); const bool rect2InSrcBeam = BeamsOverlap(direction, source, rect2); // if rect1 isn't exclusively in the src beam, it doesn't win if(rect2InSrcBeam || !rect1InSrcBeam) { return false; } // we know rect1 is in the beam, and rect2 is not // if rect1 is to the direction of, and rect2 is not, rect1 wins. // for example, for direction left, if rect1 is to the left of the source // and rect2 is below, then we always prefer the in beam rect1, since rect2 // could be reached by going down. if(!IsToDirectionOf(direction, source, rect2)) { return true; } // for horizontal directions, being exclusively in beam always wins if((direction == Dali::Toolkit::Control::KeyboardFocus::LEFT || direction == Dali::Toolkit::Control::KeyboardFocus::RIGHT)) { return true; } // for vertical directions, beams only beat up to a point: // now, as long as rect2 isn't completely closer, rect1 wins // e.g for direction down, completely closer means for rect2's top // edge to be closer to the source's top edge than rect1's bottom edge. return (MajorAxisDistance(direction, source, rect1) < MajorAxisDistanceToFarEdge(direction, source, rect2)); } bool IsBetterCandidate(Toolkit::Control::KeyboardFocus::Direction direction, Rect<float>& focusedRect, Rect<float>& candidateRect, Rect<float>& bestCandidateRect) { // to be a better candidate, need to at least be a candidate in the first place if(!IsCandidate(focusedRect, candidateRect, direction)) { return false; } // we know that candidateRect is a candidate.. if bestCandidateRect is not a candidate, // candidateRect is better if(!IsCandidate(focusedRect, bestCandidateRect, direction)) { return true; } // if candidateRect is better by beam, it wins if(BeamBeats(direction, focusedRect, candidateRect, bestCandidateRect)) { return true; } // if bestCandidateRect is better, then candidateRect cant' be :) if(BeamBeats(direction, focusedRect, bestCandidateRect, candidateRect)) { return false; } // otherwise, do fudge-tastic comparison of the major and minor axis return (GetWeightedDistanceFor( MajorAxisDistance(direction, focusedRect, candidateRect), MinorAxisDistance(direction, focusedRect, candidateRect)) < GetWeightedDistanceFor(MajorAxisDistance(direction, focusedRect, bestCandidateRect), MinorAxisDistance(direction, focusedRect, bestCandidateRect))); } bool IsFocusable(Actor& actor) { return (actor.GetProperty<bool>(Actor::Property::KEYBOARD_FOCUSABLE) && actor.GetProperty<bool>(Actor::Property::VISIBLE) && actor.GetProperty<Vector4>(Actor::Property::WORLD_COLOR).a > FULLY_TRANSPARENT); } Actor FindNextFocus(Actor& actor, Actor& focusedActor, Rect<float>& focusedRect, Rect<float>& bestCandidateRect, Toolkit::Control::KeyboardFocus::Direction direction) { Actor nearestActor; if(actor && actor.GetProperty<bool>(Actor::Property::VISIBLE)) { // Recursively children const auto childCount = actor.GetChildCount(); for(auto i = 0u; i < childCount; ++i) { Dali::Actor child = actor.GetChildAt(i); if(child && child != focusedActor && IsFocusable(child)) { Rect<float> candidateRect = DevelActor::CalculateScreenExtents(child); // convert x, y, width, height -> left, right, bottom, top ConvertCoordinate(candidateRect); if(IsBetterCandidate(direction, focusedRect, candidateRect, bestCandidateRect)) { bestCandidateRect = candidateRect; nearestActor = child; } } Actor nextActor = FindNextFocus(child, focusedActor, focusedRect, bestCandidateRect, direction); if(nextActor) { nearestActor = nextActor; } } } return nearestActor; } } // unnamed namespace Actor GetNearestFocusableActor(Actor focusedActor, Toolkit::Control::KeyboardFocus::Direction direction) { Actor nearestActor; if(!focusedActor) { return nearestActor; } Rect<float> focusedRect = DevelActor::CalculateScreenExtents(focusedActor); // initialize the best candidate to something impossible // (so the first plausible actor will become the best choice) Rect<float> bestCandidateRect = focusedRect; switch(direction) { case Toolkit::Control::KeyboardFocus::LEFT: { bestCandidateRect.x += 1; break; } case Toolkit::Control::KeyboardFocus::RIGHT: { bestCandidateRect.x -= 1; break; } case Toolkit::Control::KeyboardFocus::UP: { bestCandidateRect.y += 1; break; } case Toolkit::Control::KeyboardFocus::DOWN: { bestCandidateRect.y -= 1; break; } default: { break; } } ConvertCoordinate(bestCandidateRect); ConvertCoordinate(focusedRect); Integration::SceneHolder window = Integration::SceneHolder::Get(focusedActor); if(window) { Actor rootActor = window.GetRootLayer(); nearestActor = FindNextFocus(rootActor, focusedActor, focusedRect, bestCandidateRect, direction); } return nearestActor; } } // namespace FocusFinder } // namespace Toolkit } // namespace Dali <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <sstream> #include <stdio.h> #include <boost/algorithm/string.hpp> #include <boost/range.hpp> #include <boost/tokenizer.hpp> #include <SOIL.h> #include "ObjLoaderUtils.hpp" #include "MtlLoader.hpp" #include "../../DebugUtils.h" using namespace boost; using namespace ObjLoaderUtils; MtlLoader::MtlLoader(): last_material_name("") { } GLuint create_texture(float r, float g, float b) { //Hope 0 isn't a legal value for glGenTextures GLuint texture = 0; glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_2D, texture); float* data = new float[3]; data[0] = r; data[1] = g; data[2] = b; glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 1, 1, 0, GL_RGB, GL_FLOAT, &data[0]); glBindTexture(GL_TEXTURE_2D, 0); return texture; } void MtlLoader::load_materials(const std::string& path) { std::ifstream file(path); if(!file.is_open()) { printf("Failed to open %s!", path.c_str()); exit(EXIT_FAILURE); } std::string line; char_separator<char> space_sep(" "); while(getline(file, line)) { boost::trim(line); std::vector<std::string> tokens; boost::split(tokens, line, boost::is_any_of(" ")); //Might make parsing faster. //tokens.reserve(4); if(tokens.size() > 0) { handle_tokens(tokens); } } for(auto& str_mat_pair: materials) { auto& mat = str_mat_pair.second; if(!mat.diffuse_map) mat.diffuse_map = create_texture(1, 1, 1); if(!mat.specular_map) mat.specular_map = create_texture(0, 0, 0); if(!mat.normal_map) mat.normal_map = create_texture(0.5, 0.5, 1); if(!mat.mask) mat.mask = create_texture(1, 1, 1); } } GLuint MtlLoader::load_texture(const std::string& path) { std::string fixed_path = path; boost::replace_all(fixed_path, "//", "/"); boost::replace_all(fixed_path, "\\", "/"); std::cout << "load texture: assets/" << fixed_path; GLuint tex_2d = SOIL_load_OGL_texture( ("assets/" + fixed_path).c_str(), SOIL_LOAD_AUTO, SOIL_CREATE_NEW_ID, SOIL_FLAG_INVERT_Y | SOIL_FLAG_TEXTURE_REPEATS ); if(tex_2d == 0) { std::cout << " <--- Failed!\n"; } else { std::cout << "\n"; } return tex_2d; } void MtlLoader::handle_tokens(std::vector<std::string> tokens) { const char* type = popFirstToken(tokens).c_str(); if(!strcmp(type, "newmtl")) { if(strcmp(last_material_name.c_str(), "")) { materials[last_material_name] = current_material; } last_material_name = tokens[0]; current_material = Material(tokens[0]); } else if(!strcmp(type, "map_Kd")) { current_material.diffuse_map = load_texture(tokens[0]); GLfloat fLargest; glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &fLargest); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, fLargest); } else if(!strcmp(type, "map_Ns")) { current_material.specular_map = load_texture(tokens[0]); } else if(!strcmp(type, "map_bump")) { current_material.normal_map = load_texture(tokens[0]); } else if(!strcmp(type, "map_d")) { current_material.mask = load_texture(tokens[0]); } materials[last_material_name] = current_material; } <commit_msg>Added anisotropic filtering for normal & specular maps<commit_after>#include <iostream> #include <fstream> #include <sstream> #include <stdio.h> #include <boost/algorithm/string.hpp> #include <boost/range.hpp> #include <boost/tokenizer.hpp> #include <SOIL.h> #include "ObjLoaderUtils.hpp" #include "MtlLoader.hpp" #include "../../DebugUtils.h" using namespace boost; using namespace ObjLoaderUtils; MtlLoader::MtlLoader(): last_material_name("") { } GLuint create_texture(float r, float g, float b) { //Hope 0 isn't a legal value for glGenTextures GLuint texture = 0; glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_2D, texture); float* data = new float[3]; data[0] = r; data[1] = g; data[2] = b; glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 1, 1, 0, GL_RGB, GL_FLOAT, &data[0]); glBindTexture(GL_TEXTURE_2D, 0); return texture; } void MtlLoader::load_materials(const std::string& path) { std::ifstream file(path); if(!file.is_open()) { printf("Failed to open %s!", path.c_str()); exit(EXIT_FAILURE); } std::string line; char_separator<char> space_sep(" "); while(getline(file, line)) { boost::trim(line); std::vector<std::string> tokens; boost::split(tokens, line, boost::is_any_of(" ")); //Might make parsing faster. //tokens.reserve(4); if(tokens.size() > 0) { handle_tokens(tokens); } } for(auto& str_mat_pair: materials) { auto& mat = str_mat_pair.second; if(!mat.diffuse_map) mat.diffuse_map = create_texture(1, 1, 1); if(!mat.specular_map) mat.specular_map = create_texture(0, 0, 0); if(!mat.normal_map) mat.normal_map = create_texture(0.5, 0.5, 1); if(!mat.mask) mat.mask = create_texture(1, 1, 1); } } GLuint MtlLoader::load_texture(const std::string& path) { std::string fixed_path = path; boost::replace_all(fixed_path, "//", "/"); boost::replace_all(fixed_path, "\\", "/"); std::cout << "load texture: assets/" << fixed_path; GLuint tex_2d = SOIL_load_OGL_texture( ("assets/" + fixed_path).c_str(), SOIL_LOAD_AUTO, SOIL_CREATE_NEW_ID, SOIL_FLAG_INVERT_Y | SOIL_FLAG_TEXTURE_REPEATS ); if(tex_2d == 0) { std::cout << " <--- Failed!\n"; } else { std::cout << "\n"; } return tex_2d; } void MtlLoader::handle_tokens(std::vector<std::string> tokens) { const char* type = popFirstToken(tokens).c_str(); if(!strcmp(type, "newmtl")) { if(strcmp(last_material_name.c_str(), "")) { materials[last_material_name] = current_material; } last_material_name = tokens[0]; current_material = Material(tokens[0]); } else if(!strcmp(type, "map_Kd")) { current_material.diffuse_map = load_texture(tokens[0]); GLfloat fLargest; glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &fLargest); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, fLargest); } else if(!strcmp(type, "map_Ns")) { current_material.specular_map = load_texture(tokens[0]); GLfloat fLargest; glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &fLargest); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, fLargest); } else if(!strcmp(type, "map_bump")) { current_material.normal_map = load_texture(tokens[0]); GLfloat fLargest; glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &fLargest); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, fLargest); } else if(!strcmp(type, "map_d")) { current_material.mask = load_texture(tokens[0]); GLfloat fLargest; glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &fLargest); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, fLargest); } materials[last_material_name] = current_material; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: swmodalredlineacceptdlg.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: hr $ $Date: 2004-05-10 16:30:04 $ * * 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 _SWMODALREDLINEACCEPTDLG_HXX #define _SWMODALREDLINEACCEPTDLG_HXX #include "chldwrap.hxx" #ifndef _BASEDLGS_HXX //autogen #include <sfx2/basedlgs.hxx> #endif class SwChildWinWrapper; class SwRedlineAcceptDlg; class SwModalRedlineAcceptDlg : public SfxModalDialog { SwRedlineAcceptDlg* pImplDlg; virtual void Resize(); public: SwModalRedlineAcceptDlg(Window *pParent); ~SwModalRedlineAcceptDlg(); void AcceptAll( BOOL bAccept ); virtual void Activate(); }; #endif<commit_msg>INTEGRATION: CWS tune05 (1.2.68); FILE MERGED 2004/07/21 15:32:57 cmc 1.2.68.1: #i30554# remove new newline warnings<commit_after>/************************************************************************* * * $RCSfile: swmodalredlineacceptdlg.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: obo $ $Date: 2004-08-12 13:07:31 $ * * 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 _SWMODALREDLINEACCEPTDLG_HXX #define _SWMODALREDLINEACCEPTDLG_HXX #include "chldwrap.hxx" #ifndef _BASEDLGS_HXX //autogen #include <sfx2/basedlgs.hxx> #endif class SwChildWinWrapper; class SwRedlineAcceptDlg; class SwModalRedlineAcceptDlg : public SfxModalDialog { SwRedlineAcceptDlg* pImplDlg; virtual void Resize(); public: SwModalRedlineAcceptDlg(Window *pParent); ~SwModalRedlineAcceptDlg(); void AcceptAll( BOOL bAccept ); virtual void Activate(); }; #endif <|endoftext|>
<commit_before>/** Handles the hardware level functions of the SdFat library * * SdCard.cpp * Created 1-5-18 By: Smitty * * A longer description. */ #include "SdCard.hpp" #include "../../Controller/Logger/Logger.hpp" //FIXME: rip out all the demo code and put into functions /** * @brief SdCard constructor */ SdCard::SdCard(void) { sdEx = new SdFatSdioEX(); hasBegun = false; fileOpen = false; writeCount = 0; } SdCard::~SdCard(void) { if(fileOpen) { closeFile(); } } bool SdCard::beginCard() { if(!sdEx->begin()){ Logger::getInstance()->log("SD_CARD", "Could not Initalize SD card", MSG_ERR); //sdEx->initErrorHalt(); sdEx->errorPrint(); hasBegun = false; return false; } Logger::getInstance()->log("SD_CARD", "SD card Initalized", MSG_LOG); hasBegun = true; return true; } bool SdCard::openFile() { char fileName[30]; determineFileName(fileName); Logger::getInstance()->log("SD_CARD", fileName, MSG_LOG); //TODO: load in files from root dir and sift through them. Create a file 1 newer than last if(!logFile.open("test.csv", O_RDWR | O_CREAT)){ Logger::getInstance()->log("SD_CARD", "Could not Open SD file", MSG_ERR); fileOpen = false; return false; } Logger::getInstance()->log("SD_CARD", "SD file opened", MSG_LOG); fileOpen = true; return true; } void SdCard::determineFileName(char* buf){ uint8_t fileNum = 0; //which file we're on char fileName[30]; // the base filename and the one we use to track it char fileEnding[8]; //holds the filename ending ie '00.csv' strcpy(fileName, FILE_BASE_NAME); //put the base name in sprintf(fileEnding, "%05d.csv", fileNum); //construct the file ending '00.csv' strcat(fileName, fileEnding); //concat BASE_FILE_NAME and ending ie 'EVOS_LOG00.csv' Logger::getInstance()->log("SD_CARD", fileName, MSG_LOG); // used to increment the file number while (sdEx->exists(fileName)) { fileNum++; //increment the file number since this one exists already memset(); strcpy(fileName, FILE_BASE_NAME); //copy in the base string sprintf(fileEnding, "%05d.csv", fileNum); //construct the file ending again strcat(fileName, fileEnding); //concat BASE_FILE_NAME and ending ie 'EVOS_LOG00.csv' } strcpy(buf, fileName); } bool SdCard::writeMessage(const char* message, bool writeOut) { if(logFile.println(message)< 0) //if write successful { Logger::getInstance()->log("SD_CARD", "SD Write Error", MSG_ERR); return false; } if(writeOut) { Logger::getInstance()->log("SD_CARD", "Writing special warn/error data out", MSG_DEBUG); writeCount = 0; if (!logFile.sync() || logFile.getWriteError()) { sdEx->errorPrint(); Logger::getInstance()->log("SD_CARD", "SD Sync Write Error", MSG_ERR); } } else if(writeCount >= WRITE_THRESH){ //Logger::getInstance()->log("SD_CARD", "Writing data out", MSG_DEBUG); writeCount = 0; if (!logFile.sync() || logFile.getWriteError()) { sdEx->errorPrint(); Logger::getInstance()->log("SD_CARD", "SD Sync Write Error", MSG_ERR); } } writeCount++; return true; } void SdCard::closeFile() { logFile.close(); fileOpen = false; Logger::getInstance()->log("SD_CARD", "SD card file closed.", MSG_LOG); } bool SdCard::isFileOpen() { return fileOpen; } bool SdCard::hasCardBegun() { return hasBegun; } // // Log file base name // #define FILE_BASE_NAME "Smitty" // //file system object // SdFatSdioEX sdEx; // //log file // SdFile myFile; // // Time in micros for next data record. // uint32_t logTime; // //------------------------------------------------------------------------------ // // Write data header. // void writeHeader() { // myFile.print(F("micros")); // for (uint8_t i = 0; i < 4; i++) { // myFile.print(F(",adc")); // myFile.print(i, DEC); // } // myFile.println(); // } // //------------------------------------------------------------------------------ // // Log a data record. // void logData() { // uint16_t data[4]; // // Read all channels to avoid SD write latency between readings. // for (uint8_t i = 0; i < 4; i++) { // data[i] = analogRead(i); // } // // Write data to file. Start with log time in micros. // myFile.print(logTime); // // Write data to CSV record. // for (uint8_t i = 0; i < 4; i++) { // myFile.write(','); // myFile.print(data[i]); // } // myFile.println(); // } // void setup() { // const uint8_t BASE_NAME_SIZE = sizeof(FILE_BASE_NAME) - 1; // char fileName[13] = FILE_BASE_NAME "00.csv"; // Serial.print("Initializing SD card..."); // if (!sdEx.begin()) { // Serial.println("initialization failed!"); // sdEx.initErrorHalt(); // } // Serial.println("initialization done."); // // used to increment the file number // while (sdEx.exists(fileName)) { // if (fileName[BASE_NAME_SIZE + 1] != '9') // fileName[BASE_NAME_SIZE + 1]++; // else if (fileName[BASE_NAME_SIZE] != '9') // { // fileName[BASE_NAME_SIZE + 1] = '0'; // fileName[BASE_NAME_SIZE]++; // } // } // if (!myFile.open(fileName, O_CREAT | O_WRITE | O_EXCL)) { // } // // Data header. // writeHeader(); // } // void loop() { // logData(); // // Force data to SD and update the directory entry to avoid data loss. // if (!myFile.sync() || myFile.getWriteError()) { // // error("write error"); // } // // Close file // myFile.close(); // Serial.println(F("Done")); // }<commit_msg>Finsished SD card logging, #151. GLCD next<commit_after>/** Handles the hardware level functions of the SdFat library * * SdCard.cpp * Created 1-5-18 By: Smitty * * A longer description. */ #include "SdCard.hpp" #include "../../Controller/Logger/Logger.hpp" //FIXME: rip out all the demo code and put into functions /** * @brief SdCard constructor */ SdCard::SdCard(void) { sdEx = new SdFatSdioEX(); hasBegun = false; fileOpen = false; writeCount = 0; } SdCard::~SdCard(void) { if(fileOpen) { closeFile(); } } bool SdCard::beginCard() { if(!sdEx->begin()){ Logger::getInstance()->log("SD_CARD", "Could not Initalize SD card", MSG_ERR); //sdEx->initErrorHalt(); sdEx->errorPrint(); hasBegun = false; return false; } Logger::getInstance()->log("SD_CARD", "SD card Initalized", MSG_LOG); hasBegun = true; return true; } bool SdCard::openFile() { char fileName[30]; determineFileName(fileName); Logger::getInstance()->log("SD_CARD", fileName, MSG_LOG); if(!logFile.open(fileName, O_RDWR | O_CREAT)){ Logger::getInstance()->log("SD_CARD", "Could not Open SD file", MSG_ERR); fileOpen = false; return false; } Logger::getInstance()->log("SD_CARD", "SD file opened", MSG_LOG); fileOpen = true; return true; } void SdCard::determineFileName(char* buf){ uint8_t fileNum = 0; //which file we're on String fname = String(FILE_BASE_NAME + String(fileNum, DEC) + ".csv"); //construct filename string from filenum Logger::getInstance()->log("SD_CARD", fname.c_str(), MSG_LOG); // used to increment the file number until it finds a name we can use for a new file while (sdEx->exists(fname.c_str())) { fileNum++; //increment the file number since this one exists already fname = FILE_BASE_NAME + String(fileNum, DEC) + ".csv"; } strcpy(buf, fname.c_str()); } bool SdCard::writeMessage(const char* message, bool writeOut) { if(logFile.println(message)< 0) //if write successful { Logger::getInstance()->log("SD_CARD", "SD Write Error", MSG_ERR); return false; } if(writeOut) { Logger::getInstance()->log("SD_CARD", "Writing special warn/error data out", MSG_DEBUG); writeCount = 0; if (!logFile.sync() || logFile.getWriteError()) { sdEx->errorPrint(); Logger::getInstance()->log("SD_CARD", "SD Sync Write Error", MSG_ERR); } } else if(writeCount >= WRITE_THRESH){ //Logger::getInstance()->log("SD_CARD", "Writing data out", MSG_DEBUG); writeCount = 0; if (!logFile.sync() || logFile.getWriteError()) { sdEx->errorPrint(); Logger::getInstance()->log("SD_CARD", "SD Sync Write Error", MSG_ERR); } } writeCount++; return true; } void SdCard::closeFile() { logFile.close(); fileOpen = false; Logger::getInstance()->log("SD_CARD", "SD card file closed.", MSG_LOG); } bool SdCard::isFileOpen() { return fileOpen; } bool SdCard::hasCardBegun() { return hasBegun; } // // Log file base name // #define FILE_BASE_NAME "Smitty" // //file system object // SdFatSdioEX sdEx; // //log file // SdFile myFile; // // Time in micros for next data record. // uint32_t logTime; // //------------------------------------------------------------------------------ // // Write data header. // void writeHeader() { // myFile.print(F("micros")); // for (uint8_t i = 0; i < 4; i++) { // myFile.print(F(",adc")); // myFile.print(i, DEC); // } // myFile.println(); // } // //------------------------------------------------------------------------------ // // Log a data record. // void logData() { // uint16_t data[4]; // // Read all channels to avoid SD write latency between readings. // for (uint8_t i = 0; i < 4; i++) { // data[i] = analogRead(i); // } // // Write data to file. Start with log time in micros. // myFile.print(logTime); // // Write data to CSV record. // for (uint8_t i = 0; i < 4; i++) { // myFile.write(','); // myFile.print(data[i]); // } // myFile.println(); // } // void setup() { // const uint8_t BASE_NAME_SIZE = sizeof(FILE_BASE_NAME) - 1; // char fileName[13] = FILE_BASE_NAME "00.csv"; // Serial.print("Initializing SD card..."); // if (!sdEx.begin()) { // Serial.println("initialization failed!"); // sdEx.initErrorHalt(); // } // Serial.println("initialization done."); // // used to increment the file number // while (sdEx.exists(fileName)) { // if (fileName[BASE_NAME_SIZE + 1] != '9') // fileName[BASE_NAME_SIZE + 1]++; // else if (fileName[BASE_NAME_SIZE] != '9') // { // fileName[BASE_NAME_SIZE + 1] = '0'; // fileName[BASE_NAME_SIZE]++; // } // } // if (!myFile.open(fileName, O_CREAT | O_WRITE | O_EXCL)) { // } // // Data header. // writeHeader(); // } // void loop() { // logData(); // // Force data to SD and update the directory entry to avoid data loss. // if (!myFile.sync() || myFile.getWriteError()) { // // error("write error"); // } // // Close file // myFile.close(); // Serial.println(F("Done")); // }<|endoftext|>
<commit_before>// MapMaker (c) 2016 Andrey Fidrya. MIT license. See LICENSE for more information. #include <QSplitter> #include <QMessageBox> #include <QCloseEvent> #include <QTimer> #include <QMenuBar> #include <QFileDialog> #include <QStandardPaths> #include <QUndoStack> #include "MainWindow.h" #include "MapView.h" #include "ObjectBrowser.h" #include "PropertyBrowser.h" #include "Controllers/LevelLoader.h" #include "Dialogs/SettingsDialog/SettingsDialog.h" #include "Models/MapScene.h" #include "Models/LevelObjectsModel.h" #include "Utils/Settings.h" #include "Utils/Utils.h" #include "Utils/FileUtils.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , settings_(Settings::sharedInstance()) { connect(settings_, SIGNAL(mapFilenameChanged(QString)), this, SLOT(updateWindowTitle())); updateWindowTitle(); resize(800, 600); mapView_ = new MapView(this); connect(mapView_, SIGNAL(sceneCreated(QGraphicsScene*)), this, SLOT(onSceneCreated(QGraphicsScene*))); ObjectBrowser *objectBrowser = new ObjectBrowser(this); propertyBrowser_ = new PropertyBrowser(this); connect(mapView_, SIGNAL(selectedLevelObjectChanged(LevelObject*)), propertyBrowser_, SLOT(setLevelObject(LevelObject*))); QSplitter *rightColumnSplitter = new QSplitter(this); rightColumnSplitter->setOrientation(Qt::Vertical); rightColumnSplitter->addWidget(objectBrowser); rightColumnSplitter->addWidget(propertyBrowser_); rightColumnSplitter->setSizes(QList<int>() << 350 << 250); QSplitter *splitter = new QSplitter(this); splitter->addWidget(mapView_); splitter->addWidget(rightColumnSplitter); splitter->setSizes(QList<int>() << 400 << 200); setCentralWidget(splitter); onSceneCreated(mapView_->scene()); connect(settings_, SIGNAL(imagesDirectoryChanged(QString)), this, SLOT(loadImages())); loadImages(); if (!settings_->mapFilename().isEmpty()) QTimer::singleShot(0, this, SLOT(loadLevel())); } MainWindow::~MainWindow() { } void MainWindow::closeEvent(QCloseEvent *event) { Q_UNUSED(event); if (!mapView_->modified()) return; QMessageBox::StandardButton result = QMessageBox::warning(this, "Confirmation", "Level modified. Save the changes?", QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel); if (result == QMessageBox::Yes) { LevelLoader *levelLoader = LevelLoader::sharedInstance(); if (!levelLoader->saveToFile( mapView_, settings_->mapFilename())) { QMessageBox::critical(this, "Error", levelLoader->lastErrorDescription()); event->ignore(); } } else if (result == QMessageBox::Cancel){ event->ignore(); } } void MainWindow::loadImages() { LevelObjectsModel *model = LevelObjectsModel::sharedInstance(); model->reset(); if (!settings_->imagesDirectory().isEmpty()) { model->addImagesFromDirectory(settings_->imagesDirectory()); } } void MainWindow::updateWindowTitle() { QString title; if (settings_->mapFilename().isEmpty()) { title = "MapMaker"; } else { QFileInfo fileInfo(settings_->mapFilename()); title = fileInfo.fileName() + " | MapMaker"; } setWindowTitle(title); } void MainWindow::onOpen() { QStringList locations = QStandardPaths::standardLocations(QStandardPaths::DataLocation); QString dataLocation; if (!locations.empty()) dataLocation = locations.first(); QString mapFilename = QFileDialog::getOpenFileName(this, tr("MapMaker"), dataLocation, tr("MapMaker Files (*.mmj);;All files (*.*)")); if (mapFilename.isNull()) return; settings_->setMapFilename(mapFilename); loadLevel(); } void MainWindow::onPreferences() { SettingsDialog *dialog = new SettingsDialog(this); dialog->setWindowModality(Qt::WindowModal); dialog->setWindowFlags((dialog->windowFlags() | Qt::CustomizeWindowHint) & ~Qt::WindowMaximizeButtonHint); dialog->setAttribute(Qt::WA_DeleteOnClose); dialog->exec(); } void MainWindow::loadLevel() { LevelLoader *levelLoader = LevelLoader::sharedInstance(); if (!levelLoader->loadFromFile(mapView_, settings_->mapFilename())) { /* QMessageBox::StandardButton result = */ QMessageBox::warning(this, "Error", levelLoader->lastErrorDescription(), QMessageBox::Ok); // If loading completed with errors, treat the map as modified mapView_->setModified(true); } } void MainWindow::onSceneCreated(QGraphicsScene *scene) { Q_UNUSED(scene); menuBar()->clear(); createFileMenu(); createEditMenu(); createMapMenu(); createViewMenu(); } void MainWindow::createFileMenu() { QMenu *fileMenu = menuBar()->addMenu(tr("&File")); QKeySequence openShortcut(tr("Ctrl+O", "File|Open...")); fileMenu->addAction(tr("Open..."), this, SLOT(onOpen()), openShortcut); } void MainWindow::createEditMenu() { QMenu *editMenu = menuBar()->addMenu(tr("&Edit")); QUndoStack *undoStack = mapView_->mapScene()->undoStack(); QAction *undoAction = undoStack->createUndoAction(this, tr("&Undo")); undoAction->setShortcuts(QKeySequence::Undo); editMenu->addAction(undoAction); QAction *redoAction = undoStack->createRedoAction(this, tr("&Redo")); redoAction->setShortcuts(QKeySequence::Redo); editMenu->addAction(redoAction); editMenu->addSeparator(); QKeySequence preferencesShortcut(tr("Ctrl+K", "Edit|Preferences...")); editMenu->addAction(tr("Preferences..."), this, SLOT(onPreferences()), preferencesShortcut); } void MainWindow::createMapMenu() { QMenu *mapMenu = menuBar()->addMenu(tr("&Map")); } void MainWindow::createViewMenu() { QMenu *viewMenu = menuBar()->addMenu(tr("&View")); QKeySequence showGridShortcut(tr("Ctrl+'", "View|Show Grid")); QAction *showGridAction = viewMenu->addAction( tr("Show Grid"), settings_, SLOT(setShowGrid(bool)), showGridShortcut); showGridAction->setCheckable(true); showGridAction->setChecked(settings_->showGrid()); QKeySequence snapToGridShortcut(tr("Ctrl+Shift+;", "View|Snap to Grid")); QAction *snapToGridAction = viewMenu->addAction( tr("Snap to Grid"), settings_, SLOT(setSnapToGrid(bool)), snapToGridShortcut); snapToGridAction->setCheckable(true); snapToGridAction->setChecked(settings_->snapToGrid()); } <commit_msg>Add autosize grid option (not impl yet)<commit_after>// MapMaker (c) 2016 Andrey Fidrya. MIT license. See LICENSE for more information. #include <QSplitter> #include <QMessageBox> #include <QCloseEvent> #include <QTimer> #include <QMenuBar> #include <QFileDialog> #include <QStandardPaths> #include <QUndoStack> #include "MainWindow.h" #include "MapView.h" #include "ObjectBrowser.h" #include "PropertyBrowser.h" #include "Controllers/LevelLoader.h" #include "Dialogs/SettingsDialog/SettingsDialog.h" #include "Models/MapScene.h" #include "Models/LevelObjectsModel.h" #include "Utils/Settings.h" #include "Utils/Utils.h" #include "Utils/FileUtils.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , settings_(Settings::sharedInstance()) { connect(settings_, SIGNAL(mapFilenameChanged(QString)), this, SLOT(updateWindowTitle())); updateWindowTitle(); resize(800, 600); mapView_ = new MapView(this); connect(mapView_, SIGNAL(sceneCreated(QGraphicsScene*)), this, SLOT(onSceneCreated(QGraphicsScene*))); ObjectBrowser *objectBrowser = new ObjectBrowser(this); propertyBrowser_ = new PropertyBrowser(this); connect(mapView_, SIGNAL(selectedLevelObjectChanged(LevelObject*)), propertyBrowser_, SLOT(setLevelObject(LevelObject*))); QSplitter *rightColumnSplitter = new QSplitter(this); rightColumnSplitter->setOrientation(Qt::Vertical); rightColumnSplitter->addWidget(objectBrowser); rightColumnSplitter->addWidget(propertyBrowser_); rightColumnSplitter->setSizes(QList<int>() << 350 << 250); QSplitter *splitter = new QSplitter(this); splitter->addWidget(mapView_); splitter->addWidget(rightColumnSplitter); splitter->setSizes(QList<int>() << 400 << 200); setCentralWidget(splitter); onSceneCreated(mapView_->scene()); connect(settings_, SIGNAL(imagesDirectoryChanged(QString)), this, SLOT(loadImages())); loadImages(); if (!settings_->mapFilename().isEmpty()) QTimer::singleShot(0, this, SLOT(loadLevel())); } MainWindow::~MainWindow() { } void MainWindow::closeEvent(QCloseEvent *event) { Q_UNUSED(event); if (!mapView_->modified()) return; QMessageBox::StandardButton result = QMessageBox::warning(this, "Confirmation", "Level modified. Save the changes?", QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel); if (result == QMessageBox::Yes) { LevelLoader *levelLoader = LevelLoader::sharedInstance(); if (!levelLoader->saveToFile( mapView_, settings_->mapFilename())) { QMessageBox::critical(this, "Error", levelLoader->lastErrorDescription()); event->ignore(); } } else if (result == QMessageBox::Cancel){ event->ignore(); } } void MainWindow::loadImages() { LevelObjectsModel *model = LevelObjectsModel::sharedInstance(); model->reset(); if (!settings_->imagesDirectory().isEmpty()) { model->addImagesFromDirectory(settings_->imagesDirectory()); } } void MainWindow::updateWindowTitle() { QString title; if (settings_->mapFilename().isEmpty()) { title = "MapMaker"; } else { QFileInfo fileInfo(settings_->mapFilename()); title = fileInfo.fileName() + " | MapMaker"; } setWindowTitle(title); } void MainWindow::onOpen() { QStringList locations = QStandardPaths::standardLocations(QStandardPaths::DataLocation); QString dataLocation; if (!locations.empty()) dataLocation = locations.first(); QString mapFilename = QFileDialog::getOpenFileName(this, tr("MapMaker"), dataLocation, tr("MapMaker Files (*.mmj);;All files (*.*)")); if (mapFilename.isNull()) return; settings_->setMapFilename(mapFilename); loadLevel(); } void MainWindow::onPreferences() { SettingsDialog *dialog = new SettingsDialog(this); dialog->setWindowModality(Qt::WindowModal); dialog->setWindowFlags((dialog->windowFlags() | Qt::CustomizeWindowHint) & ~Qt::WindowMaximizeButtonHint); dialog->setAttribute(Qt::WA_DeleteOnClose); dialog->exec(); } void MainWindow::loadLevel() { LevelLoader *levelLoader = LevelLoader::sharedInstance(); if (!levelLoader->loadFromFile(mapView_, settings_->mapFilename())) { /* QMessageBox::StandardButton result = */ QMessageBox::warning(this, "Error", levelLoader->lastErrorDescription(), QMessageBox::Ok); // If loading completed with errors, treat the map as modified mapView_->setModified(true); } } void MainWindow::onSceneCreated(QGraphicsScene *scene) { Q_UNUSED(scene); menuBar()->clear(); createFileMenu(); createEditMenu(); createMapMenu(); createViewMenu(); } void MainWindow::createFileMenu() { QMenu *fileMenu = menuBar()->addMenu(tr("&File")); QKeySequence openShortcut(tr("Ctrl+O", "File|Open...")); fileMenu->addAction(tr("Open..."), this, SLOT(onOpen()), openShortcut); } void MainWindow::createEditMenu() { QMenu *editMenu = menuBar()->addMenu(tr("&Edit")); QUndoStack *undoStack = mapView_->mapScene()->undoStack(); QAction *undoAction = undoStack->createUndoAction(this, tr("&Undo")); undoAction->setShortcuts(QKeySequence::Undo); editMenu->addAction(undoAction); QAction *redoAction = undoStack->createRedoAction(this, tr("&Redo")); redoAction->setShortcuts(QKeySequence::Redo); editMenu->addAction(redoAction); editMenu->addSeparator(); QKeySequence preferencesShortcut(tr("Ctrl+K", "Edit|Preferences...")); editMenu->addAction(tr("Preferences..."), this, SLOT(onPreferences()), preferencesShortcut); } void MainWindow::createMapMenu() { //QMenu *mapMenu = menuBar()->addMenu(tr("&Map")); } void MainWindow::createViewMenu() { QMenu *viewMenu = menuBar()->addMenu(tr("&View")); QKeySequence showGridShortcut(tr("Ctrl+'", "View|Show Grid")); QAction *showGridAction = viewMenu->addAction( tr("Show Grid"), settings_, SLOT(setShowGrid(bool)), showGridShortcut); showGridAction->setCheckable(true); showGridAction->setChecked(settings_->showGrid()); QKeySequence snapToGridShortcut(tr("Ctrl+Shift+;", "View|Snap to Grid")); QAction *snapToGridAction = viewMenu->addAction( tr("Snap to Grid"), settings_, SLOT(setSnapToGrid(bool)), snapToGridShortcut); snapToGridAction->setCheckable(true); snapToGridAction->setChecked(settings_->snapToGrid()); } <|endoftext|>
<commit_before>#ifndef STAN_MATH_REV_MAT_FUN_CHOLESKY_DECOMPOSE_HPP #define STAN_MATH_REV_MAT_FUN_CHOLESKY_DECOMPOSE_HPP #include <stan/math/prim/mat/fun/Eigen.hpp> #include <stan/math/prim/mat/fun/typedefs.hpp> #include <stan/math/prim/mat/fun/cholesky_decompose.hpp> #include <stan/math/rev/scal/fun/value_of_rec.hpp> #include <stan/math/rev/scal/fun/value_of.hpp> #include <stan/math/rev/core.hpp> #include <stan/math/prim/mat/fun/value_of_rec.hpp> #include <stan/math/prim/mat/err/check_pos_definite.hpp> #include <stan/math/prim/mat/err/check_square.hpp> #include <stan/math/prim/mat/err/check_symmetric.hpp> #include <algorithm> namespace stan { namespace math { class cholesky_block : public vari { public: int M_; int block_size_; typedef Eigen::Block<Eigen::MatrixXd> Block_; vari** variRefA_; vari** variRefL_; /** * Constructor for cholesky function. * * Stores varis for A. Instantiates and stores varis for L. * Instantiates and stores dummy vari for upper triangular part of var * result returned in cholesky_decompose function call * * variRefL aren't on the chainable autodiff stack, only used for storage * and computation. Note that varis for L are constructed externally in * cholesky_decompose. * * block_size_ determined using the same calculation Eigen/LLT.h * * @param A matrix * @param L_A matrix, cholesky factor of A */ cholesky_block(const Eigen::Matrix<var, -1, -1>& A, const Eigen::Matrix<double, -1, -1>& L_A) : vari(0.0), M_(A.rows()), variRefA_(ChainableStack::memalloc_.alloc_array<vari*> (A.rows() * (A.rows() + 1) / 2)), variRefL_(ChainableStack::memalloc_.alloc_array<vari*> (A.rows() * (A.rows() + 1) / 2)) { size_t pos = 0; block_size_ = std::max((M_ / 8 / 16) * 16, 8); block_size_ = std::min(block_size_, 128); for (size_type j = 0; j < M_; ++j) { for (size_type i = j; i < M_; ++i) { variRefA_[pos] = A.coeffRef(i, j).vi_; variRefL_[pos] = new vari(L_A.coeffRef(i, j), false); ++pos; } } } /** * Symbolic adjoint calculation for cholesky factor A * * @param L cholesky factor * @param Lbar matrix of adjoints of L */ inline void symbolic_rev(Block_& L, Block_& Lbar) { using Eigen::Lower; using Eigen::Upper; using Eigen::StrictlyUpper; L.transposeInPlace(); Lbar = (L * Lbar.triangularView<Lower>()).eval(); Lbar.triangularView<StrictlyUpper>() = Lbar.adjoint().triangularView<StrictlyUpper>(); L.triangularView<Upper>().solveInPlace(Lbar); L.triangularView<Upper>().solveInPlace(Lbar.transpose()); } /** * Reverse mode differentiation algorithm refernce: * * Iain Murray: Differentiation of the Cholesky decomposition, 2016. * */ virtual void chain() { using Eigen::MatrixXd; using Eigen::Lower; using Eigen::Block; using Eigen::Upper; using Eigen::StrictlyUpper; MatrixXd Lbar(M_, M_); MatrixXd L(M_, M_); Lbar.setZero(); L.setZero(); size_t pos = 0; for (size_type j = 0; j < M_; ++j) { for (size_type i = j; i < M_; ++i) { Lbar.coeffRef(i, j) = variRefL_[pos]->adj_; L.coeffRef(i, j) = variRefL_[pos]->val_; ++pos; } } for (int k = M_; k > 0; k -= block_size_) { int j = std::max(0, k - block_size_); Block_ R = L.block(j, 0, k - j, j); Block_ D = L.block(j, j, k - j, k - j); Block_ B = L.block(k, 0, M_ - k, j); Block_ C = L.block(k, j, M_ - k, k - j); Block_ Rbar = Lbar.block(j, 0, k - j, j); Block_ Dbar = Lbar.block(j, j, k - j, k - j); Block_ Bbar = Lbar.block(k, 0, M_ - k, j); Block_ Cbar = Lbar.block(k, j, M_ - k, k - j); if (Cbar.size() > 0) { Cbar = D.transpose().triangularView<Upper>() .solve(Cbar.transpose()).transpose(); Bbar.noalias() -= Cbar * R; Dbar.noalias() -= Cbar.transpose() * C; } symbolic_rev(D, Dbar); Rbar.noalias() -= Cbar.transpose() * B; Rbar.noalias() -= Dbar.selfadjointView<Lower>() * R; Dbar.diagonal() *= 0.5; Dbar.triangularView<StrictlyUpper>().setZero(); } pos = 0; for (size_type j = 0; j < M_; ++j) for (size_type i = j; i < M_; ++i) variRefA_[pos++]->adj_ += Lbar.coeffRef(i, j); } }; class cholesky_scalar : public vari { public: int M_; vari** variRefA_; vari** variRefL_; /** * Constructor for cholesky function. * * Stores varis for A Instantiates and stores varis for L Instantiates * and stores dummy vari for upper triangular part of var result returned * in cholesky_decompose function call * * variRefL aren't on the chainable autodiff stack, only used for storage * and computation. Note that varis for L are constructed externally in * cholesky_decompose. * * @param A matrix * @param L_A matrix, cholesky factor of A */ cholesky_scalar(const Eigen::Matrix<var, -1, -1>& A, const Eigen::Matrix<double, -1, -1>& L_A) : vari(0.0), M_(A.rows()), variRefA_(ChainableStack::memalloc_.alloc_array<vari*> (A.rows() * (A.rows() + 1) / 2)), variRefL_(ChainableStack::memalloc_.alloc_array<vari*> (A.rows() * (A.rows() + 1) / 2)) { size_t accum = 0; size_t accum_i = accum; for (size_type j = 0; j < M_; ++j) { for (size_type i = j; i < M_; ++i) { accum_i += i; size_t pos = j + accum_i; variRefA_[pos] = A.coeffRef(i, j).vi_; variRefL_[pos] = new vari(L_A.coeffRef(i, j), false); } accum += j; accum_i = accum; } } /** * Reverse mode differentiation algorithm refernce: * * Mike Giles. An extended collection of matrix derivative results for * forward and reverse mode AD. Jan. 2008. * * Note algorithm as laid out in Giles is row-major, so Eigen::Matrices * are explicitly storage order RowMajor, whereas Eigen defaults to * ColumnMajor. Also note algorithm starts by calculating the adjoint for * A(M_ - 1, M_ - 1), hence pos on line 94 is decremented to start at pos * = M_ * (M_ + 1) / 2. */ virtual void chain() { using Eigen::Matrix; using Eigen::RowMajor; Matrix<double, -1, -1, RowMajor> adjL(M_, M_); Matrix<double, -1, -1, RowMajor> LA(M_, M_); Matrix<double, -1, -1, RowMajor> adjA(M_, M_); size_t pos = 0; for (size_type i = 0; i < M_; ++i) { for (size_type j = 0; j <= i; ++j) { adjL.coeffRef(i, j) = variRefL_[pos]->adj_; LA.coeffRef(i, j) = variRefL_[pos]->val_; ++pos; } } --pos; for (int i = M_ - 1; i >= 0; --i) { for (int j = i; j >= 0; --j) { if (i == j) { adjA.coeffRef(i, j) = 0.5 * adjL.coeff(i, j) / LA.coeff(i, j); } else { adjA.coeffRef(i, j) = adjL.coeff(i, j) / LA.coeff(j, j); adjL.coeffRef(j, j) -= adjL.coeff(i, j) * LA.coeff(i, j) / LA.coeff(j, j); } for (int k = j - 1; k >=0; --k) { adjL.coeffRef(i, k) -= adjA.coeff(i, j) * LA.coeff(j, k); adjL.coeffRef(j, k) -= adjA.coeff(i, j) * LA.coeff(i, k); } variRefA_[pos--]->adj_ += adjA.coeffRef(i, j); } } } }; /** * Reverse mode specialization of cholesky decomposition * * Internally calls llt rather than using cholesky_decompose in order to * use selfadjointView<Lower> optimization. * * TODO(rtrangucci): Use Eigen 3.3 inplace Cholesky when possible * * Note chainable stack varis are created below in Matrix<var, -1, -1> * * @param A Matrix * @return L cholesky factor of A */ inline Eigen::Matrix<var, -1, -1> cholesky_decompose(const Eigen::Matrix<var, -1, -1> &A) { check_square("cholesky_decompose", "A", A); check_symmetric("cholesky_decompose", "A", A); Eigen::Matrix<double, -1, -1> L_A(value_of_rec(A)); Eigen::LLT<Eigen::MatrixXd> L_factor = L_A.selfadjointView<Eigen::Lower>().llt(); check_pos_definite("cholesky_decompose", "m", L_factor); L_A = L_factor.matrixL(); // Memory allocated in arena. // cholesky_scalar gradient faster for small matrices compared to // cholesky_block vari* dummy = new vari(0.0, false); Eigen::Matrix<var, -1, -1> L(A.rows(), A.cols()); if (L_A.rows() <= 35) { cholesky_scalar *baseVari = new cholesky_scalar(A, L_A); size_t accum = 0; size_t accum_i = accum; for (size_type j = 0; j < L.cols(); ++j) { for (size_type i = j; i < L.cols(); ++i) { accum_i += i; size_t pos = j + accum_i; L.coeffRef(i, j).vi_ = baseVari->variRefL_[pos]; } for (size_type k = 0; k < j; ++k) L.coeffRef(k, j).vi_ = dummy; accum += j; accum_i = accum; } } else { cholesky_block *baseVari = new cholesky_block(A, L_A); size_t pos = 0; for (size_type j = 0; j < L.cols(); ++j) { for (size_type i = j; i < L.cols(); ++i) { L.coeffRef(i, j).vi_ = baseVari->variRefL_[pos++]; } for (size_type k = 0; k < j; ++k) L.coeffRef(k, j).vi_ = dummy; } } return L; } } } #endif <commit_msg>Updates LLT to inplace decomposition per eigen 3.3 doc<commit_after>#ifndef STAN_MATH_REV_MAT_FUN_CHOLESKY_DECOMPOSE_HPP #define STAN_MATH_REV_MAT_FUN_CHOLESKY_DECOMPOSE_HPP #include <stan/math/prim/mat/fun/Eigen.hpp> #include <stan/math/prim/mat/fun/typedefs.hpp> #include <stan/math/prim/mat/fun/cholesky_decompose.hpp> #include <stan/math/rev/scal/fun/value_of_rec.hpp> #include <stan/math/rev/scal/fun/value_of.hpp> #include <stan/math/rev/core.hpp> #include <stan/math/prim/mat/fun/value_of_rec.hpp> #include <stan/math/prim/mat/err/check_pos_definite.hpp> #include <stan/math/prim/mat/err/check_square.hpp> #include <stan/math/prim/mat/err/check_symmetric.hpp> #include <algorithm> namespace stan { namespace math { class cholesky_block : public vari { public: int M_; int block_size_; typedef Eigen::Block<Eigen::MatrixXd> Block_; vari** variRefA_; vari** variRefL_; /** * Constructor for cholesky function. * * Stores varis for A. Instantiates and stores varis for L. * Instantiates and stores dummy vari for upper triangular part of var * result returned in cholesky_decompose function call * * variRefL aren't on the chainable autodiff stack, only used for storage * and computation. Note that varis for L are constructed externally in * cholesky_decompose. * * block_size_ determined using the same calculation Eigen/LLT.h * * @param A matrix * @param L_A matrix, cholesky factor of A */ cholesky_block(const Eigen::Matrix<var, -1, -1>& A, const Eigen::Matrix<double, -1, -1>& L_A) : vari(0.0), M_(A.rows()), variRefA_(ChainableStack::memalloc_.alloc_array<vari*> (A.rows() * (A.rows() + 1) / 2)), variRefL_(ChainableStack::memalloc_.alloc_array<vari*> (A.rows() * (A.rows() + 1) / 2)) { size_t pos = 0; block_size_ = std::max((M_ / 8 / 16) * 16, 8); block_size_ = std::min(block_size_, 128); for (size_type j = 0; j < M_; ++j) { for (size_type i = j; i < M_; ++i) { variRefA_[pos] = A.coeffRef(i, j).vi_; variRefL_[pos] = new vari(L_A.coeffRef(i, j), false); ++pos; } } } /** * Symbolic adjoint calculation for cholesky factor A * * @param L cholesky factor * @param Lbar matrix of adjoints of L */ inline void symbolic_rev(Block_& L, Block_& Lbar) { using Eigen::Lower; using Eigen::Upper; using Eigen::StrictlyUpper; L.transposeInPlace(); Lbar = (L * Lbar.triangularView<Lower>()).eval(); Lbar.triangularView<StrictlyUpper>() = Lbar.adjoint().triangularView<StrictlyUpper>(); L.triangularView<Upper>().solveInPlace(Lbar); L.triangularView<Upper>().solveInPlace(Lbar.transpose()); } /** * Reverse mode differentiation algorithm refernce: * * Iain Murray: Differentiation of the Cholesky decomposition, 2016. * */ virtual void chain() { using Eigen::MatrixXd; using Eigen::Lower; using Eigen::Block; using Eigen::Upper; using Eigen::StrictlyUpper; MatrixXd Lbar(M_, M_); MatrixXd L(M_, M_); Lbar.setZero(); L.setZero(); size_t pos = 0; for (size_type j = 0; j < M_; ++j) { for (size_type i = j; i < M_; ++i) { Lbar.coeffRef(i, j) = variRefL_[pos]->adj_; L.coeffRef(i, j) = variRefL_[pos]->val_; ++pos; } } for (int k = M_; k > 0; k -= block_size_) { int j = std::max(0, k - block_size_); Block_ R = L.block(j, 0, k - j, j); Block_ D = L.block(j, j, k - j, k - j); Block_ B = L.block(k, 0, M_ - k, j); Block_ C = L.block(k, j, M_ - k, k - j); Block_ Rbar = Lbar.block(j, 0, k - j, j); Block_ Dbar = Lbar.block(j, j, k - j, k - j); Block_ Bbar = Lbar.block(k, 0, M_ - k, j); Block_ Cbar = Lbar.block(k, j, M_ - k, k - j); if (Cbar.size() > 0) { Cbar = D.transpose().triangularView<Upper>() .solve(Cbar.transpose()).transpose(); Bbar.noalias() -= Cbar * R; Dbar.noalias() -= Cbar.transpose() * C; } symbolic_rev(D, Dbar); Rbar.noalias() -= Cbar.transpose() * B; Rbar.noalias() -= Dbar.selfadjointView<Lower>() * R; Dbar.diagonal() *= 0.5; Dbar.triangularView<StrictlyUpper>().setZero(); } pos = 0; for (size_type j = 0; j < M_; ++j) for (size_type i = j; i < M_; ++i) variRefA_[pos++]->adj_ += Lbar.coeffRef(i, j); } }; class cholesky_scalar : public vari { public: int M_; vari** variRefA_; vari** variRefL_; /** * Constructor for cholesky function. * * Stores varis for A Instantiates and stores varis for L Instantiates * and stores dummy vari for upper triangular part of var result returned * in cholesky_decompose function call * * variRefL aren't on the chainable autodiff stack, only used for storage * and computation. Note that varis for L are constructed externally in * cholesky_decompose. * * @param A matrix * @param L_A matrix, cholesky factor of A */ cholesky_scalar(const Eigen::Matrix<var, -1, -1>& A, const Eigen::Matrix<double, -1, -1>& L_A) : vari(0.0), M_(A.rows()), variRefA_(ChainableStack::memalloc_.alloc_array<vari*> (A.rows() * (A.rows() + 1) / 2)), variRefL_(ChainableStack::memalloc_.alloc_array<vari*> (A.rows() * (A.rows() + 1) / 2)) { size_t accum = 0; size_t accum_i = accum; for (size_type j = 0; j < M_; ++j) { for (size_type i = j; i < M_; ++i) { accum_i += i; size_t pos = j + accum_i; variRefA_[pos] = A.coeffRef(i, j).vi_; variRefL_[pos] = new vari(L_A.coeffRef(i, j), false); } accum += j; accum_i = accum; } } /** * Reverse mode differentiation algorithm refernce: * * Mike Giles. An extended collection of matrix derivative results for * forward and reverse mode AD. Jan. 2008. * * Note algorithm as laid out in Giles is row-major, so Eigen::Matrices * are explicitly storage order RowMajor, whereas Eigen defaults to * ColumnMajor. Also note algorithm starts by calculating the adjoint for * A(M_ - 1, M_ - 1), hence pos on line 94 is decremented to start at pos * = M_ * (M_ + 1) / 2. */ virtual void chain() { using Eigen::Matrix; using Eigen::RowMajor; Matrix<double, -1, -1, RowMajor> adjL(M_, M_); Matrix<double, -1, -1, RowMajor> LA(M_, M_); Matrix<double, -1, -1, RowMajor> adjA(M_, M_); size_t pos = 0; for (size_type i = 0; i < M_; ++i) { for (size_type j = 0; j <= i; ++j) { adjL.coeffRef(i, j) = variRefL_[pos]->adj_; LA.coeffRef(i, j) = variRefL_[pos]->val_; ++pos; } } --pos; for (int i = M_ - 1; i >= 0; --i) { for (int j = i; j >= 0; --j) { if (i == j) { adjA.coeffRef(i, j) = 0.5 * adjL.coeff(i, j) / LA.coeff(i, j); } else { adjA.coeffRef(i, j) = adjL.coeff(i, j) / LA.coeff(j, j); adjL.coeffRef(j, j) -= adjL.coeff(i, j) * LA.coeff(i, j) / LA.coeff(j, j); } for (int k = j - 1; k >=0; --k) { adjL.coeffRef(i, k) -= adjA.coeff(i, j) * LA.coeff(j, k); adjL.coeffRef(j, k) -= adjA.coeff(i, j) * LA.coeff(i, k); } variRefA_[pos--]->adj_ += adjA.coeffRef(i, j); } } } }; /** * Reverse mode specialization of cholesky decomposition * * Internally calls llt rather than using cholesky_decompose in order to * use selfadjointView<Lower> optimization. * * Note chainable stack varis are created below in Matrix<var, -1, -1> * * @param A Matrix * @return L cholesky factor of A */ inline Eigen::Matrix<var, -1, -1> cholesky_decompose(const Eigen::Matrix<var, -1, -1> &A) { check_square("cholesky_decompose", "A", A); check_symmetric("cholesky_decompose", "A", A); Eigen::Matrix<double, -1, -1> L_A(value_of_rec(A)); Eigen::LLT<Eigen::Ref<Eigen::MatrixXd> > L_factor(L_A); check_pos_definite("cholesky_decompose", "m", L_factor); // Memory allocated in arena. // cholesky_scalar gradient faster for small matrices compared to // cholesky_block vari* dummy = new vari(0.0, false); Eigen::Matrix<var, -1, -1> L(A.rows(), A.cols()); if (L_A.rows() <= 35) { cholesky_scalar *baseVari = new cholesky_scalar(A, L_A); size_t accum = 0; size_t accum_i = accum; for (size_type j = 0; j < L.cols(); ++j) { for (size_type i = j; i < L.cols(); ++i) { accum_i += i; size_t pos = j + accum_i; L.coeffRef(i, j).vi_ = baseVari->variRefL_[pos]; } for (size_type k = 0; k < j; ++k) L.coeffRef(k, j).vi_ = dummy; accum += j; accum_i = accum; } } else { cholesky_block *baseVari = new cholesky_block(A, L_A); size_t pos = 0; for (size_type j = 0; j < L.cols(); ++j) { for (size_type i = j; i < L.cols(); ++i) { L.coeffRef(i, j).vi_ = baseVari->variRefL_[pos++]; } for (size_type k = 0; k < j; ++k) L.coeffRef(k, j).vi_ = dummy; } } return L; } } } #endif <|endoftext|>
<commit_before>/* * Copyright 2015 Aldebaran * * 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 "driver_helpers.hpp" namespace naoqi { namespace helpers { namespace driver { /** Function that returns the type of a robot */ static naoqi_bridge_msgs::RobotInfo& getRobotInfoLocal( const qi::SessionPtr& session) { static naoqi_bridge_msgs::RobotInfo info; static qi::Url robot_url; if (robot_url == session->url()) { return info; } robot_url = session->url(); // Get the robot type std::cout << "Receiving information about robot model" << std::endl; qi::AnyObject p_memory = session->service("ALMemory"); std::string robot = p_memory.call<std::string>("getData", "RobotConfig/Body/Type" ); std::string version = p_memory.call<std::string>("getData", "RobotConfig/Body/BaseVersion" ); std::transform(robot.begin(), robot.end(), robot.begin(), ::tolower); if (std::string(robot) == "nao") { info.type = naoqi_bridge_msgs::RobotInfo::NAO; std::cout << BOLDYELLOW << "Robot detected: " << BOLDCYAN << "NAO " << version << RESETCOLOR << std::endl; } if (std::string(robot) == "pepper" || std::string(robot) == "juliette" ) { info.type = naoqi_bridge_msgs::RobotInfo::PEPPER; std::cout << BOLDYELLOW << "Robot detected: " << BOLDCYAN << "Pepper " << version << RESETCOLOR << std::endl; } if (std::string(robot) == "romeo" ) { info.type = naoqi_bridge_msgs::RobotInfo::ROMEO; std::cout << BOLDYELLOW << "Robot detected: " << BOLDCYAN << "Romeo " << version << RESETCOLOR << std::endl; } // Get the data from RobotConfig qi::AnyObject p_motion = session->service("ALMotion"); std::vector<std::vector<qi::AnyValue> > config = p_motion.call<std::vector<std::vector<qi::AnyValue> > >("getRobotConfig"); // TODO, fill with the proper string matches from http://doc.aldebaran.com/2-1/naoqi/motion/tools-general-api.html#ALMotionProxy::getRobotConfig for (size_t i=0; i<config[0].size();++i) { if (config[0][i].as<std::string>() == "Model Type") { try{ info.model = config[1][i].as<std::string>(); } catch(const std::exception& e) { std::cout << "Error in robot config variable " << (config[0][i]).as<std::string>() << std::endl; } } if (config[0][i].as<std::string>() == "Head Version") { try{ info.head_version = config[1][i].as<std::string>(); } catch(const std::exception& e) { std::cout << "Error in robot config variable " << (config[0][i]).as<std::string>() << std::endl; } } if (config[0][i].as<std::string>() == "Body Version") { try{ info.body_version = config[1][i].as<std::string>(); } catch(const std::exception& e) { std::cout << "Error in robot config variable " << (config[0][i]).as<std::string>() << std::endl; } } if (config[0][i].as<std::string>() == "Arm Version") { try{ info.arm_version = config[1][i].as<std::string>(); } catch(const std::exception& e) { std::cout << "Error in robot config variable " << (config[0][i]).as<std::string>() << std::endl; } } if (config[0][i].as<std::string>() == "Laser") { try{ info.has_laser = config[1][i].as<bool>(); } catch(const std::exception& e) { std::cout << "Error in robot config variable " << (config[0][i]).as<std::string>() << std::endl; } } if (config[0][i].as<std::string>() == "Extended Arms") { try{ info.has_extended_arms = config[1][i].as<bool>(); } catch(const std::exception& e) { std::cout << "Error in robot config variable " << (config[0][i]).as<std::string>() << std::endl; } } if (config[0][i].as<std::string>() == "Number of Legs") { try{ info.number_of_legs = config[1][i].as<int>(); } catch(const std::exception& e) { std::cout << "Error in robot config variable " << (config[0][i]).as<std::string>() << std::endl; } } if (config[0][i].as<std::string>() == "Number of Arms") { try{ info.number_of_arms = config[1][i].as<int>(); } catch(const std::exception& e) { std::cout << "Error in robot config variable " << (config[0][i]).as<std::string>() << std::endl; } } if (config[0][i].as<std::string>() == "Number of Hands") { try{ info.number_of_hands = config[1][i].as<int>(); } catch(const std::exception& e) { std::cout << "Error in robot config variable " << (config[0][i]).as<std::string>() << std::endl; } } } return info; } const robot::Robot& getRobot( const qi::SessionPtr& session ) { static robot::Robot robot = robot::UNIDENTIFIED; if ( getRobotInfo(session).type == naoqi_bridge_msgs::RobotInfo::NAO ) { robot = robot::NAO; } if ( getRobotInfo(session).type == naoqi_bridge_msgs::RobotInfo::PEPPER ) { robot = robot::PEPPER; } if ( getRobotInfo(session).type == naoqi_bridge_msgs::RobotInfo::ROMEO ) { robot = robot::ROMEO; } return robot; } const naoqi_bridge_msgs::RobotInfo& getRobotInfo( const qi::SessionPtr& session ) { static naoqi_bridge_msgs::RobotInfo robot_info = getRobotInfoLocal(session); return robot_info; } /** Function that sets language for a robot */ bool& setLanguage( const qi::SessionPtr& session, naoqi_bridge_msgs::SetStringRequest req) { static bool success; std::cout << "Receiving service call of setting speech language" << std::endl; try{ qi::AnyObject p_text_to_speech = session->service("ALTextToSpeech"); p_text_to_speech.call<void>("setLanguage", req.data); success = true; return success; } catch(const std::exception& e){ success = false; return success; } } /** Function that gets language set to a robot */ std::string& getLanguage( const qi::SessionPtr& session ) { static std::string language; std::cout << "Receiving service call of getting speech language" << std::endl; qi::AnyObject p_text_to_speech = session->service("ALTextToSpeech"); language = p_text_to_speech.call<std::string>("getLanguage"); return language; } /** * Function that detects if the robot is using stereo cameras to compute depth */ bool isDepthStereo(const qi::SessionPtr &session) { std::vector<std::string> sensor_names; try { qi::AnyObject p_motion = session->service("ALMotion"); sensor_names = p_motion.call<std::vector<std::string>>("getSensorNames"); if (std::find(sensor_names.begin(), sensor_names.end(), "CameraStereo") != sensor_names.end()) { return true; } else { return false; } } catch (const std::exception &e) { std::cerr << e.what() << std::endl; return false; } } } // driver } // helpers } // naoqi <commit_msg>Fix compilation error for indigo<commit_after>/* * Copyright 2015 Aldebaran * * 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 "driver_helpers.hpp" namespace naoqi { namespace helpers { namespace driver { /** Function that returns the type of a robot */ static naoqi_bridge_msgs::RobotInfo& getRobotInfoLocal( const qi::SessionPtr& session) { static naoqi_bridge_msgs::RobotInfo info; static qi::Url robot_url; if (robot_url == session->url()) { return info; } robot_url = session->url(); // Get the robot type std::cout << "Receiving information about robot model" << std::endl; qi::AnyObject p_memory = session->service("ALMemory"); std::string robot = p_memory.call<std::string>("getData", "RobotConfig/Body/Type" ); std::string version = p_memory.call<std::string>("getData", "RobotConfig/Body/BaseVersion" ); std::transform(robot.begin(), robot.end(), robot.begin(), ::tolower); if (std::string(robot) == "nao") { info.type = naoqi_bridge_msgs::RobotInfo::NAO; std::cout << BOLDYELLOW << "Robot detected: " << BOLDCYAN << "NAO " << version << RESETCOLOR << std::endl; } if (std::string(robot) == "pepper" || std::string(robot) == "juliette" ) { info.type = naoqi_bridge_msgs::RobotInfo::PEPPER; std::cout << BOLDYELLOW << "Robot detected: " << BOLDCYAN << "Pepper " << version << RESETCOLOR << std::endl; } if (std::string(robot) == "romeo" ) { info.type = naoqi_bridge_msgs::RobotInfo::ROMEO; std::cout << BOLDYELLOW << "Robot detected: " << BOLDCYAN << "Romeo " << version << RESETCOLOR << std::endl; } // Get the data from RobotConfig qi::AnyObject p_motion = session->service("ALMotion"); std::vector<std::vector<qi::AnyValue> > config = p_motion.call<std::vector<std::vector<qi::AnyValue> > >("getRobotConfig"); // TODO, fill with the proper string matches from http://doc.aldebaran.com/2-1/naoqi/motion/tools-general-api.html#ALMotionProxy::getRobotConfig for (size_t i=0; i<config[0].size();++i) { if (config[0][i].as<std::string>() == "Model Type") { try{ info.model = config[1][i].as<std::string>(); } catch(const std::exception& e) { std::cout << "Error in robot config variable " << (config[0][i]).as<std::string>() << std::endl; } } if (config[0][i].as<std::string>() == "Head Version") { try{ info.head_version = config[1][i].as<std::string>(); } catch(const std::exception& e) { std::cout << "Error in robot config variable " << (config[0][i]).as<std::string>() << std::endl; } } if (config[0][i].as<std::string>() == "Body Version") { try{ info.body_version = config[1][i].as<std::string>(); } catch(const std::exception& e) { std::cout << "Error in robot config variable " << (config[0][i]).as<std::string>() << std::endl; } } if (config[0][i].as<std::string>() == "Arm Version") { try{ info.arm_version = config[1][i].as<std::string>(); } catch(const std::exception& e) { std::cout << "Error in robot config variable " << (config[0][i]).as<std::string>() << std::endl; } } if (config[0][i].as<std::string>() == "Laser") { try{ info.has_laser = config[1][i].as<bool>(); } catch(const std::exception& e) { std::cout << "Error in robot config variable " << (config[0][i]).as<std::string>() << std::endl; } } if (config[0][i].as<std::string>() == "Extended Arms") { try{ info.has_extended_arms = config[1][i].as<bool>(); } catch(const std::exception& e) { std::cout << "Error in robot config variable " << (config[0][i]).as<std::string>() << std::endl; } } if (config[0][i].as<std::string>() == "Number of Legs") { try{ info.number_of_legs = config[1][i].as<int>(); } catch(const std::exception& e) { std::cout << "Error in robot config variable " << (config[0][i]).as<std::string>() << std::endl; } } if (config[0][i].as<std::string>() == "Number of Arms") { try{ info.number_of_arms = config[1][i].as<int>(); } catch(const std::exception& e) { std::cout << "Error in robot config variable " << (config[0][i]).as<std::string>() << std::endl; } } if (config[0][i].as<std::string>() == "Number of Hands") { try{ info.number_of_hands = config[1][i].as<int>(); } catch(const std::exception& e) { std::cout << "Error in robot config variable " << (config[0][i]).as<std::string>() << std::endl; } } } return info; } const robot::Robot& getRobot( const qi::SessionPtr& session ) { static robot::Robot robot = robot::UNIDENTIFIED; if ( getRobotInfo(session).type == naoqi_bridge_msgs::RobotInfo::NAO ) { robot = robot::NAO; } if ( getRobotInfo(session).type == naoqi_bridge_msgs::RobotInfo::PEPPER ) { robot = robot::PEPPER; } if ( getRobotInfo(session).type == naoqi_bridge_msgs::RobotInfo::ROMEO ) { robot = robot::ROMEO; } return robot; } const naoqi_bridge_msgs::RobotInfo& getRobotInfo( const qi::SessionPtr& session ) { static naoqi_bridge_msgs::RobotInfo robot_info = getRobotInfoLocal(session); return robot_info; } /** Function that sets language for a robot */ bool& setLanguage( const qi::SessionPtr& session, naoqi_bridge_msgs::SetStringRequest req) { static bool success; std::cout << "Receiving service call of setting speech language" << std::endl; try{ qi::AnyObject p_text_to_speech = session->service("ALTextToSpeech"); p_text_to_speech.call<void>("setLanguage", req.data); success = true; return success; } catch(const std::exception& e){ success = false; return success; } } /** Function that gets language set to a robot */ std::string& getLanguage( const qi::SessionPtr& session ) { static std::string language; std::cout << "Receiving service call of getting speech language" << std::endl; qi::AnyObject p_text_to_speech = session->service("ALTextToSpeech"); language = p_text_to_speech.call<std::string>("getLanguage"); return language; } /** * Function that detects if the robot is using stereo cameras to compute depth */ bool isDepthStereo(const qi::SessionPtr &session) { std::vector<std::string> sensor_names; try { qi::AnyObject p_motion = session->service("ALMotion"); sensor_names = p_motion.call<std::vector<std::string> >("getSensorNames"); if (std::find(sensor_names.begin(), sensor_names.end(), "CameraStereo") != sensor_names.end()) { return true; } else { return false; } } catch (const std::exception &e) { std::cerr << e.what() << std::endl; return false; } } } // driver } // helpers } // naoqi <|endoftext|>
<commit_before>#include "ConnectedComps.h" #include <stdlib.h> #include <math.h> #include <iostream> namespace avg { int Run::s_LastLabel= 0; Run::Run(int row, int start_col, int end_col, int color){ m_Row = row; assert(end_col>=start_col); m_StartCol = start_col; m_EndCol = end_col; m_Color = color; s_LastLabel++; m_Label = s_LastLabel; } int Run::length(){ return m_EndCol-m_StartCol+1; } DPoint Run::center(){ DPoint d = DPoint((m_StartCol + m_EndCol)/2., m_Row); return d; } Blob::Blob(Run run) { m_pRuns = new RunList(); m_pRuns->push_back(run); m_pParent = BlobPtr(); } Blob::~Blob() { delete m_pRuns; } RunList *Blob::getList(){ return m_pRuns; } void Blob::merge(BlobPtr other) { assert(other); RunList *other_runs=other->getList(); for(RunList::iterator it=other_runs->begin();it!=other_runs->end();++it){ m_pRuns->push_back(*it); } //m_pRuns->splice(m_pRuns->end(), *(other->getList())); } DPoint Blob::center() { DPoint d = DPoint(0,0); int c = 0; for(RunList::iterator r=m_pRuns->begin();r!=m_pRuns->end();++r){ d+=r->center(); c++; } return d/double(c); } IntRect Blob::bbox(){ int x1=__INT_MAX__,y1=__INT_MAX__,x2=0,y2=0; for(RunList::iterator r=m_pRuns->begin();r!=m_pRuns->end();++r){ x1 = std::min(x1, r->m_StartCol); y1 = std::min(y1, r->m_Row); x2 = std::max(x2, r->m_EndCol); y2 = std::max(y2, r->m_Row); } return IntRect(x1,y1,x2+1,y2+1); } int Blob::area(){ int res = 0; for(RunList::iterator r=m_pRuns->begin();r!=m_pRuns->end();++r){ res+= r->length(); } return res; } int Blob::getLabel(){ if(!m_pRuns->empty()){ return (m_pRuns->begin())->m_Label; }else{ return 0;//actually invalid } } void render(Bitmap *target, BlobPtr blob, unsigned char col){ //assert I8 unsigned char *ptr; for(RunList::iterator r=blob->getList()->begin();r!=blob->getList()->end();++r){ ptr = target->getPixels()+r->m_Row*target->getStride(); int x_pos = r->m_StartCol; ptr+= x_pos; while(x_pos<=r->m_EndCol){ *(ptr++)=col; x_pos++; } } } BlobInfoPtr Blob::getInfo(){ /* more useful numbers that can be calculated from c see e.g. <http://www.cs.cf.ac.uk/Dave/Vision_lecture/node36.html#SECTION00173000000000000000> Orientation = tan−1(2(c_xy)/(c_xx − c_yy)) /2 Inertia = c_xx + c_yy Eccentricity = ... */ double c_xx = 0, c_yy =0, c_xy = 0, ll=0; BlobInfoPtr res = BlobInfoPtr(new BlobInfo()); DPoint c = res->m_Center = center(); res->m_BoundingBox = bbox(); double A = res->m_Area = area(); double l1, l2; double tmp_x, tmp_y, mag; for(RunList::iterator r=m_pRuns->begin();r!=m_pRuns->end();++r){ //This is the evaluated expression for the variance when using runs... ll = r->length(); c_yy += ll* (r->m_Row- c.y)*(r->m_Row- c.y); c_xx += ( r->m_EndCol * (r->m_EndCol+1) * (2*r->m_EndCol+1) - (r->m_StartCol-1) * r->m_StartCol * (2*r->m_StartCol -1))/6. - c.x * ( r->m_EndCol*(r->m_EndCol+1) - (r->m_StartCol-1)*r->m_StartCol ) + ll* c.x*c.x; c_xy += (r->m_Row-c.y)*0.5*( r->m_EndCol*(r->m_EndCol+1) - (r->m_StartCol-1)*r->m_StartCol) + ll *(c.x*c.y - c.x*r->m_Row); } c_xx/=A;c_yy/=A;c_xy/=A; res->m_Inertia = c_xx + c_yy; double T = sqrt( (c_xx - c_yy) * (c_xx - c_yy) + 4*c_xy*c_xy); res->m_Eccentricity = ((c_xx + c_yy) + T)/((c_xx+c_yy) - T); res->m_Orientation = 0.5*atan2(2*c_xy,c_xx-c_yy); //the l_i are variances (unit L^2) so to arrive at numbers that //correspond to lengths in the picture we use sqrt if (fabs(c_xy) > 1e-30) { //FIXME. check l1!=0 l2!=0. li=0 happens for line-like components l1 = 0.5 * ( (c_xx+c_yy) + sqrt( (c_xx+c_yy)*(c_xx+c_yy) - 4 * (c_xx*c_yy-c_xy*c_xy) ) ); l2 = 0.5 * ( (c_xx+c_yy) - sqrt( (c_xx+c_yy)*(c_xx+c_yy) - 4 * (c_xx*c_yy-c_xy*c_xy) ) ); tmp_x = c_xy/l1 - c_xx*c_yy/(c_xy*l1)+ (c_xx/c_xy); tmp_y = 1.; mag = sqrt(tmp_x*tmp_x + tmp_y*tmp_y); res->m_EigenVectors[0].x = tmp_x/mag; res->m_EigenVectors[0].y = tmp_y/mag; res->m_EigenValues.x = l1; tmp_x = c_xy/l2 - c_xx*c_yy/(c_xy*l2)+ (c_xx/c_xy); tmp_y = 1.; mag = sqrt(tmp_x*tmp_x + tmp_y*tmp_y); res->m_EigenVectors[1].x = tmp_x/mag; res->m_EigenVectors[1].y = tmp_y/mag; res->m_EigenValues.y = l2; }else{ //matrix already diagonal if (c_xx > c_yy) { res->m_EigenVectors[0].x = 1; res->m_EigenVectors[0].y = 0; res->m_EigenVectors[1].x = 0; res->m_EigenVectors[1].y = 1; res->m_EigenValues.x = c_xx; res->m_EigenValues.y = c_yy; } else { res->m_EigenVectors[0].x = 0; res->m_EigenVectors[0].y = 1; res->m_EigenVectors[1].x = 1; res->m_EigenVectors[1].y = 0; res->m_EigenValues.x = c_yy; res->m_EigenValues.y = c_xx; } } res->m_ScaledBasis[0].x = res->m_EigenVectors[0].x*sqrt(res->m_EigenValues.x); res->m_ScaledBasis[0].y = res->m_EigenVectors[0].y*sqrt(res->m_EigenValues.x); res->m_ScaledBasis[1].x = res->m_EigenVectors[1].x*sqrt(res->m_EigenValues.y); res->m_ScaledBasis[1].y = res->m_EigenVectors[1].y*sqrt(res->m_EigenValues.y); return res; } /* double Blob::stddev(){ DPoint c = center(); double res = 0; for(RunList::iterator r=m_pRuns->begin();r!=m_pRuns->end();r++){ //This is the evaluated expression for the variance when using runs... res += (*r)->length()*( ((*r)->m_Row - c.y) *((*r)->m_Row - c.y)) + ( (*r)->m_EndCol*((*r)->m_EndCol+1)*(2*(*r)->m_EndCol+1)-((*r)->m_StartCol-1)*((*r)->m_StartCol)*(2*(*r)->m_StartCol-1))/6. + (*r)->length() * c.x*c.x - c.x *((*r)->m_EndCol*((*r)->m_EndCol+1) - ((*r)->m_StartCol-1)* ((*r)->m_StartCol)); } return sqrt(res/area()); } */ int connected(Run &r1, Run &r2){ int res=0; if (abs(r2.m_Row - r1.m_Row) != 1) return 0; if (r1.m_StartCol > r2.m_StartCol){ //use > here to do 8-connectivity res = r2.m_EndCol >= r1.m_StartCol; }else{ res = r1.m_EndCol >= r2.m_StartCol; } return res; } void store_runs(CompsMap *comps, RunList *runs1, RunList *runs2){ BlobPtr p_blob; BlobPtr c_blob; for (RunList::iterator run1_it = runs1->begin(); run1_it!=runs1->end(); ++run1_it){ for (RunList::iterator run2_it = runs2->begin(); run2_it!=runs2->end(); ++run2_it){ if ( (run1_it->m_Color == run2_it->m_Color) && connected(*run1_it, *run2_it)){ p_blob = comps->find(run1_it->m_Label)->second; c_blob = comps->find(run2_it->m_Label)->second; while (p_blob->m_pParent){ p_blob = p_blob->m_pParent; } while (c_blob->m_pParent){ c_blob = c_blob->m_pParent; } if (c_blob==p_blob){ //pass ; }else{ p_blob->merge(c_blob); //destroys c_blobs runs_list c_blob->m_pParent = p_blob; } } } } } Run new_run(CompsMap *comps, int row, int col1, int col2, int color) { Run run = Run(row, col1, col2, color); BlobPtr b = BlobPtr(new Blob(run)); //std::cerr<<"creating new run"<<"row="<<row<<" c1="<<col1<<" c2="<<col2<<" color="<<color<<std::endl;; (*comps)[run.m_Label] = b; return run; } BlobListPtr connected_components(BitmapPtr image, int object_threshold){ assert(image->getPixelFormat() == I8); CompsMap *comps = new CompsMap(); const unsigned char *pixels = image->getPixels(); int stride = image->getStride(); IntPoint size = image->getSize(); RunList *runs1=new RunList(); RunList *runs2=new RunList(); RunList *tmp; int run_start=0, run_stop=0; unsigned char cur=(pixels[0]>object_threshold)?1:0, p=0; //std::cerr<<"w="<<size.x<<" h="<<size.y<<std::endl; //First line for(int x=0; x<size.x ;x++){ p = (pixels[x]>object_threshold)?1:0; if (cur!=p) { run_stop = x - 1; if (cur){ runs1->push_back ( new_run(comps, 0, run_start, run_stop, cur) ); } run_start = x; cur = p; } } if (cur){ runs1->push_back( new_run(comps, 0, run_start, size.x-1, cur) ); } //All other lines for(int y=1; y<size.y; y++){ run_start = 0;run_stop = 0; cur = (pixels[stride*y+0]>object_threshold)?1:0; for(int x=0; x<size.x ;x++){ p = (pixels[y*stride+x]>object_threshold)?1:0; //std::cerr<<"("<<x<<","<<y<<"):"<<(int)p<<std::endl; if (cur!=p) { run_stop = x - 1; if (cur){ runs2->push_back( new_run(comps, y, run_start, run_stop, cur) ); } run_start = x; cur = p; } } { if (cur){ runs2->push_back( new_run(comps,y, run_start, size.x-1, cur) ); } store_runs(comps, runs1, runs2); tmp = runs1; runs1 = runs2; runs2 = tmp; runs2->clear(); } } BlobList *result = new BlobList(); for (CompsMap::iterator b=comps->begin();b!=comps->end();++b){ if (! b->second->m_pParent){ result->push_back(b->second); } } //delete comps! comps->clear(); delete comps; delete runs1; delete runs2; return BlobListPtr(result); } } <commit_msg>Connected components optimization.<commit_after>#include "ConnectedComps.h" #include <stdlib.h> #include <math.h> #include <iostream> namespace avg { int Run::s_LastLabel= 0; Run::Run(int row, int start_col, int end_col, int color){ m_Row = row; assert(end_col>=start_col); m_StartCol = start_col; m_EndCol = end_col; m_Color = color; s_LastLabel++; m_Label = s_LastLabel; } int Run::length(){ return m_EndCol-m_StartCol+1; } DPoint Run::center(){ DPoint d = DPoint((m_StartCol + m_EndCol)/2., m_Row); return d; } Blob::Blob(Run run) { m_pRuns = new RunList(); m_pRuns->push_back(run); m_pParent = BlobPtr(); } Blob::~Blob() { delete m_pRuns; } RunList *Blob::getList(){ return m_pRuns; } void Blob::merge(BlobPtr other) { assert(other); RunList *other_runs=other->getList(); for(RunList::iterator it=other_runs->begin();it!=other_runs->end();++it){ m_pRuns->push_back(*it); } //m_pRuns->splice(m_pRuns->end(), *(other->getList())); } DPoint Blob::center() { DPoint d = DPoint(0,0); int c = 0; for(RunList::iterator r=m_pRuns->begin();r!=m_pRuns->end();++r){ d+=r->center(); c++; } return d/double(c); } IntRect Blob::bbox(){ int x1=__INT_MAX__,y1=__INT_MAX__,x2=0,y2=0; for(RunList::iterator r=m_pRuns->begin();r!=m_pRuns->end();++r){ x1 = std::min(x1, r->m_StartCol); y1 = std::min(y1, r->m_Row); x2 = std::max(x2, r->m_EndCol); y2 = std::max(y2, r->m_Row); } return IntRect(x1,y1,x2+1,y2+1); } int Blob::area(){ int res = 0; for(RunList::iterator r=m_pRuns->begin();r!=m_pRuns->end();++r){ res+= r->length(); } return res; } int Blob::getLabel(){ if(!m_pRuns->empty()){ return (m_pRuns->begin())->m_Label; }else{ return 0;//actually invalid } } void render(Bitmap *target, BlobPtr blob, unsigned char col){ //assert I8 unsigned char *ptr; for(RunList::iterator r=blob->getList()->begin();r!=blob->getList()->end();++r){ ptr = target->getPixels()+r->m_Row*target->getStride(); int x_pos = r->m_StartCol; ptr+= x_pos; while(x_pos<=r->m_EndCol){ *(ptr++)=col; x_pos++; } } } BlobInfoPtr Blob::getInfo(){ /* more useful numbers that can be calculated from c see e.g. <http://www.cs.cf.ac.uk/Dave/Vision_lecture/node36.html#SECTION00173000000000000000> Orientation = tan−1(2(c_xy)/(c_xx − c_yy)) /2 Inertia = c_xx + c_yy Eccentricity = ... */ double c_xx = 0, c_yy =0, c_xy = 0, ll=0; BlobInfoPtr res = BlobInfoPtr(new BlobInfo()); DPoint c = res->m_Center = center(); res->m_BoundingBox = bbox(); double A = res->m_Area = area(); double l1, l2; double tmp_x, tmp_y, mag; for(RunList::iterator r=m_pRuns->begin();r!=m_pRuns->end();++r){ //This is the evaluated expression for the variance when using runs... ll = r->length(); c_yy += ll* (r->m_Row- c.y)*(r->m_Row- c.y); c_xx += ( r->m_EndCol * (r->m_EndCol+1) * (2*r->m_EndCol+1) - (r->m_StartCol-1) * r->m_StartCol * (2*r->m_StartCol -1))/6. - c.x * ( r->m_EndCol*(r->m_EndCol+1) - (r->m_StartCol-1)*r->m_StartCol ) + ll* c.x*c.x; c_xy += (r->m_Row-c.y)*0.5*( r->m_EndCol*(r->m_EndCol+1) - (r->m_StartCol-1)*r->m_StartCol) + ll *(c.x*c.y - c.x*r->m_Row); } c_xx/=A;c_yy/=A;c_xy/=A; res->m_Inertia = c_xx + c_yy; double T = sqrt( (c_xx - c_yy) * (c_xx - c_yy) + 4*c_xy*c_xy); res->m_Eccentricity = ((c_xx + c_yy) + T)/((c_xx+c_yy) - T); res->m_Orientation = 0.5*atan2(2*c_xy,c_xx-c_yy); //the l_i are variances (unit L^2) so to arrive at numbers that //correspond to lengths in the picture we use sqrt if (fabs(c_xy) > 1e-30) { //FIXME. check l1!=0 l2!=0. li=0 happens for line-like components l1 = 0.5 * ( (c_xx+c_yy) + sqrt( (c_xx+c_yy)*(c_xx+c_yy) - 4 * (c_xx*c_yy-c_xy*c_xy) ) ); l2 = 0.5 * ( (c_xx+c_yy) - sqrt( (c_xx+c_yy)*(c_xx+c_yy) - 4 * (c_xx*c_yy-c_xy*c_xy) ) ); tmp_x = c_xy/l1 - c_xx*c_yy/(c_xy*l1)+ (c_xx/c_xy); tmp_y = 1.; mag = sqrt(tmp_x*tmp_x + tmp_y*tmp_y); res->m_EigenVectors[0].x = tmp_x/mag; res->m_EigenVectors[0].y = tmp_y/mag; res->m_EigenValues.x = l1; tmp_x = c_xy/l2 - c_xx*c_yy/(c_xy*l2)+ (c_xx/c_xy); tmp_y = 1.; mag = sqrt(tmp_x*tmp_x + tmp_y*tmp_y); res->m_EigenVectors[1].x = tmp_x/mag; res->m_EigenVectors[1].y = tmp_y/mag; res->m_EigenValues.y = l2; }else{ //matrix already diagonal if (c_xx > c_yy) { res->m_EigenVectors[0].x = 1; res->m_EigenVectors[0].y = 0; res->m_EigenVectors[1].x = 0; res->m_EigenVectors[1].y = 1; res->m_EigenValues.x = c_xx; res->m_EigenValues.y = c_yy; } else { res->m_EigenVectors[0].x = 0; res->m_EigenVectors[0].y = 1; res->m_EigenVectors[1].x = 1; res->m_EigenVectors[1].y = 0; res->m_EigenValues.x = c_yy; res->m_EigenValues.y = c_xx; } } res->m_ScaledBasis[0].x = res->m_EigenVectors[0].x*sqrt(res->m_EigenValues.x); res->m_ScaledBasis[0].y = res->m_EigenVectors[0].y*sqrt(res->m_EigenValues.x); res->m_ScaledBasis[1].x = res->m_EigenVectors[1].x*sqrt(res->m_EigenValues.y); res->m_ScaledBasis[1].y = res->m_EigenVectors[1].y*sqrt(res->m_EigenValues.y); return res; } /* double Blob::stddev(){ DPoint c = center(); double res = 0; for(RunList::iterator r=m_pRuns->begin();r!=m_pRuns->end();r++){ //This is the evaluated expression for the variance when using runs... res += (*r)->length()*( ((*r)->m_Row - c.y) *((*r)->m_Row - c.y)) + ( (*r)->m_EndCol*((*r)->m_EndCol+1)*(2*(*r)->m_EndCol+1)-((*r)->m_StartCol-1)*((*r)->m_StartCol)*(2*(*r)->m_StartCol-1))/6. + (*r)->length() * c.x*c.x - c.x *((*r)->m_EndCol*((*r)->m_EndCol+1) - ((*r)->m_StartCol-1)* ((*r)->m_StartCol)); } return sqrt(res/area()); } */ int connected(Run &r1, Run &r2){ int res=0; if (abs(r2.m_Row - r1.m_Row) != 1) return 0; if (r1.m_StartCol > r2.m_StartCol){ //use > here to do 8-connectivity res = r2.m_EndCol >= r1.m_StartCol; }else{ res = r1.m_EndCol >= r2.m_StartCol; } return res; } void store_runs(CompsMap *comps, RunList *runs1, RunList *runs2){ BlobPtr p_blob; BlobPtr c_blob; for (RunList::iterator run1_it = runs1->begin(); run1_it!=runs1->end(); ++run1_it){ for (RunList::iterator run2_it = runs2->begin(); run2_it!=runs2->end(); ++run2_it){ if ( (run1_it->m_Color == run2_it->m_Color) && connected(*run1_it, *run2_it)){ p_blob = comps->find(run1_it->m_Label)->second; c_blob = comps->find(run2_it->m_Label)->second; while (p_blob->m_pParent){ p_blob = p_blob->m_pParent; } while (c_blob->m_pParent){ c_blob = c_blob->m_pParent; } if (c_blob==p_blob){ //pass ; }else{ p_blob->merge(c_blob); //destroys c_blobs runs_list c_blob->m_pParent = p_blob; } } } } } Run new_run(CompsMap *comps, int row, int col1, int col2, int color) { Run run = Run(row, col1, col2, color); BlobPtr b = BlobPtr(new Blob(run)); //std::cerr<<"creating new run"<<"row="<<row<<" c1="<<col1<<" c2="<<col2<<" color="<<color<<std::endl;; (*comps)[run.m_Label] = b; return run; } BlobListPtr connected_components(BitmapPtr image, int object_threshold){ assert(image->getPixelFormat() == I8); CompsMap *comps = new CompsMap(); const unsigned char *pixels = image->getPixels(); int stride = image->getStride(); IntPoint size = image->getSize(); RunList *runs1=new RunList(); RunList *runs2=new RunList(); RunList *tmp; int run_start=0, run_stop=0; unsigned char cur=(pixels[0]>object_threshold)?1:0, p=0; //std::cerr<<"w="<<size.x<<" h="<<size.y<<std::endl; //First line for(int x=0; x<size.x ;x++){ p = (pixels[x]>object_threshold)?1:0; if (cur!=p) { run_stop = x - 1; if (cur && (run_stop-run_start > 0)){ runs1->push_back ( new_run(comps, 0, run_start, run_stop, cur) ); } run_start = x; cur = p; } } if (cur){ runs1->push_back( new_run(comps, 0, run_start, size.x-1, cur) ); } //All other lines for(int y=1; y<size.y; y++){ run_start = 0;run_stop = 0; cur = (pixels[stride*y+0]>object_threshold)?1:0; for(int x=0; x<size.x ;x++){ p = (pixels[y*stride+x]>object_threshold)?1:0; //std::cerr<<"("<<x<<","<<y<<"):"<<(int)p<<std::endl; if (cur!=p) { run_stop = x - 1; if (cur && (run_stop-run_start > 0)){ runs2->push_back( new_run(comps, y, run_start, run_stop, cur) ); } run_start = x; cur = p; } } { if (cur){ runs2->push_back( new_run(comps,y, run_start, size.x-1, cur) ); } store_runs(comps, runs1, runs2); tmp = runs1; runs1 = runs2; runs2 = tmp; runs2->clear(); } } BlobList *result = new BlobList(); for (CompsMap::iterator b=comps->begin();b!=comps->end();++b){ if (! b->second->m_pParent){ result->push_back(b->second); } } //delete comps! comps->clear(); delete comps; delete runs1; delete runs2; return BlobListPtr(result); } } <|endoftext|>
<commit_before>/* MIT License Copyright (c) 2016 Mark Allender 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 <stdio.h> #include "memory.h" #include "video.h" #include "curses.h" #include "debugger/debugger.h" #include "6502/keyboard.h" /* * Screen display mapping table */ static bool key_clear = true; static uint8_t last_key = 0; uint8_t keyboard_read_handler(uint16_t addr) { #if !defined(USE_SDL) if (key_clear) { char c = getch(); if ( c != ERR ) { uint8_t temp_key = c; // check to see if we hit the debugger key. If so, don't // report this as key to the system if (temp_key == 26) { debugger_enter(); return 0; } key_clear = false; if (temp_key == '\n') temp_key = '\r'; else if (temp_key == 127) temp_key = 8; last_key = temp_key | 0x80; } } #else uint8_t temp_key = keyboard_get_key(); if (temp_key > 0) { last_key = temp_key | 0x80; } #endif // #if !defined(USE_SDL) return(last_key); } uint8_t keyboard_clear_handler(uint16_t addr) { key_clear = true; last_key &= 0x7F; return last_key; } // memory constructor memory::memory(int size, void *memory) { m_size = size; m_memory = (uint8_t *)memory; // load up ROM/PROM images load_memory("roms/apple2_plus.rom", 0xd000); load_memory("roms/disk2.rom", 0xc600); for (auto i = 0; i < 256; i++) { m_c000_handlers[i].m_read_handler = nullptr; m_c000_handlers[i].m_write_handler = nullptr; } // register handlers for keyboard -- temporary I think register_c000_handler(0x00, keyboard_read_handler, nullptr); register_c000_handler(0x10, keyboard_clear_handler, nullptr); } void memory::register_c000_handler(uint8_t addr, slot_io_read_function read_function, slot_io_write_function write_function) { m_c000_handlers[addr].m_read_handler = read_function; m_c000_handlers[addr].m_write_handler = write_function; } // register handlers for the I/O slots void memory::register_slot_handler(const uint8_t slot, slot_io_read_function read_function, slot_io_write_function write_function ) { _ASSERT((slot >= 1) && (slot <= MAX_SLOTS)); uint8_t addr = 0x80 + (slot << 4); // add handlers for the slot. There are 16 addresses per slot so set them all to the same // handler as we will deal with all slot operations in the same function for (auto i = 0; i <= 0xf; i++) { m_c000_handlers[addr+i].m_read_handler = read_function; m_c000_handlers[addr+i].m_write_handler = write_function; } } uint8_t memory::operator[](const uint16_t addr) { static uint8_t last_key = 0; // look for memory mapped I/O locations if ((addr & 0xff00) == 0xc000) { uint8_t mapped_addr = addr & 0xff; if (m_c000_handlers[mapped_addr].m_read_handler != nullptr ) { return m_c000_handlers[mapped_addr].m_read_handler(addr); } } return m_memory[addr]; } // function to write value to memory. Trapped here in order to // faciliate memory mapped I/O and other similar things void memory::write(const uint16_t addr, uint8_t val) { if (addr >= 0xd000) { return; } if ((addr & 0xff00) == 0xc000) { uint8_t mapped_addr = addr & 0xff; if (m_c000_handlers[mapped_addr].m_write_handler != nullptr ) { m_c000_handlers[mapped_addr].m_write_handler(addr, val); return; } } m_memory[addr] = val; } bool memory::load_memory(const char *filename, uint16_t location) { FILE *fp = fopen(filename, "rb"); if (fp == nullptr) { return false; } fseek(fp, 0, SEEK_END); uint32_t buffer_size = ftell(fp); fseek(fp, 0, SEEK_SET); // allocate the memory buffer fread(&m_memory[location], 1, buffer_size, fp); fclose(fp); return true; } bool memory::load_memory(uint8_t *buffer, uint16_t size, uint16_t location) { memcpy(&(m_memory[location]), buffer, size); return true; } <commit_msg>change handling functionality<commit_after>/* MIT License Copyright (c) 2016 Mark Allender 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 <stdio.h> #include <iomanip> #include "memory.h" #include "video.h" #include "curses.h" #include "debugger/debugger.h" #include "6502/keyboard.h" /* * Screen display mapping table */ static uint8_t last_key = 0; uint8_t keyboard_read_handler(uint16_t addr) { uint8_t temp_key = keyboard_get_key(); if (temp_key > 0) { last_key = temp_key | 0x80; } return(last_key); } uint8_t keyboard_clear_read_handler(uint16_t addr) { last_key &= 0x7F; return last_key; } void keyboard_clear_write_handler(uint16_t addr, uint8_t val) { keyboard_clear_read_handler(addr); } // memory constructor memory::memory(int size, void *memory) { m_size = size; m_memory = (uint8_t *)memory; // load up ROM/PROM images load_memory("roms/apple2_plus.rom", 0xd000); load_memory("roms/disk2.rom", 0xc600); for (auto i = 0; i < 256; i++) { m_c000_handlers[i].m_read_handler = nullptr; m_c000_handlers[i].m_write_handler = nullptr; } // register handlers for keyboard. There is only a read handler here // since we need to read memory to get a key back from the system for (auto i = 0; i < 0xf; i++ ) { register_c000_handler(0x00, keyboard_read_handler, nullptr); } // clear keyboard strobe -- this can be a read or write handler register_c000_handler(0x10, keyboard_clear_read_handler, keyboard_clear_write_handler); } void memory::register_c000_handler(uint8_t addr, slot_io_read_function read_function, slot_io_write_function write_function) { m_c000_handlers[addr].m_read_handler = read_function; m_c000_handlers[addr].m_write_handler = write_function; } // register handlers for the I/O slots void memory::register_slot_handler(const uint8_t slot, slot_io_read_function read_function, slot_io_write_function write_function ) { _ASSERT((slot >= 1) && (slot <= MAX_SLOTS)); uint8_t addr = 0x80 + (slot << 4); // add handlers for the slot. There are 16 addresses per slot so set them all to the same // handler as we will deal with all slot operations in the same function for (auto i = 0; i <= 0xf; i++) { m_c000_handlers[addr+i].m_read_handler = read_function; m_c000_handlers[addr+i].m_write_handler = write_function; } } uint8_t memory::operator[](const uint16_t addr) { static uint8_t last_key = 0; // look for memory mapped I/O locations if ((addr & 0xff00) == 0xc000) { uint8_t mapped_addr = addr & 0xff; if (m_c000_handlers[mapped_addr].m_read_handler != nullptr ) { return m_c000_handlers[mapped_addr].m_read_handler(addr); } else { LOG(INFO) << "Reading from $" << std::setbase(16) << addr << " and there is no read handler."; } } return m_memory[addr]; } // function to write value to memory. Trapped here in order to // faciliate memory mapped I/O and other similar things void memory::write(const uint16_t addr, uint8_t val) { if (addr >= 0xd000) { return; } if ((addr & 0xff00) == 0xc000) { uint8_t mapped_addr = addr & 0xff; if (m_c000_handlers[mapped_addr].m_write_handler != nullptr ) { m_c000_handlers[mapped_addr].m_write_handler(addr, val); return; } else { LOG(INFO) << "Writing $" << std::setbase(16) << std::setw(2) << val << " to $" << std::setbase(16) << addr << " and there is no write handler"; } } m_memory[addr] = val; } bool memory::load_memory(const char *filename, uint16_t location) { FILE *fp = fopen(filename, "rb"); if (fp == nullptr) { return false; } fseek(fp, 0, SEEK_END); uint32_t buffer_size = ftell(fp); fseek(fp, 0, SEEK_SET); // allocate the memory buffer fread(&m_memory[location], 1, buffer_size, fp); fclose(fp); return true; } bool memory::load_memory(uint8_t *buffer, uint16_t size, uint16_t location) { memcpy(&(m_memory[location]), buffer, size); return true; } <|endoftext|>
<commit_before>#include "MapManager.h" #include "UnitManager.h" #include "DetectionManager.h" #include "BaseManager.h" //#include <algorithm> BWAPI::TilePosition startPos; Neolib::MapManager mapManager; struct sortLocations { static bool fromStartPos(const BWEM::Base *lhs, const BWEM::Base *rhs) { return lhs->Location().getApproxDistance(startPos) < rhs->Location().getApproxDistance(startPos); } }; namespace Neolib { void MapManager::init() { BWEM::Map::Instance().Initialize(); BWEM::Map::Instance().EnableAutomaticPathAnalysis(); for (auto &a : BWEM::Map::Instance().Areas()) for (auto &b : a.Bases()) allBases.push_back(&b); for (auto &b : allBases) { if (BWAPI::Broodwar->isVisible(b->Location())) { startPos = b->Location(); std::sort(allBases.begin(), allBases.end(), sortLocations::fromStartPos); } } } void MapManager::onFrame() { for (auto it = unexploredBases.begin(); it != unexploredBases.end(); ++it) { if (BWAPI::Broodwar->isVisible((*it)->Location())) { unexploredBases.erase(it); break; } } } const std::vector <const BWEM::Base*> MapManager::getAllBases() const { return allBases; } const std::set <const BWEM::Base*> MapManager::getUnexploredBases() const { return unexploredBases; } const BWAPI::TilePosition MapManager::getNextBasePosition() const { for (auto &b : allBases) { for (auto &ob : baseManager.getAllBases()) if (ob.BWEMBase == b) goto skiplocation; if (!BWAPI::Broodwar->isExplored(b->Location())) detectionManager.requestDetection((BWAPI::Position)b->Location()); if (BWAPI::Broodwar->canBuildHere(b->Location(), BWAPI::UnitTypes::Terran_Command_Center, nullptr, true)) { for (auto &eu : unitManager.getVisibleEnemies()) if (eu.lastPosition.getApproxDistance(BWAPI::Position(b->Location())) < 200) goto skiplocation; for (auto &eu : unitManager.getNonVisibleEnemies()) if (eu.lastPosition.getApproxDistance(BWAPI::Position(b->Location())) < 200) goto skiplocation; return b->Location(); skiplocation:; } } return BWAPI::TilePosition(-1, -1); } } <commit_msg>No more expanding next to enemies<commit_after>#include "MapManager.h" #include "UnitManager.h" #include "DetectionManager.h" #include "BaseManager.h" //#include <algorithm> BWAPI::TilePosition startPos; Neolib::MapManager mapManager; struct sortLocations { static bool fromStartPos(const BWEM::Base *lhs, const BWEM::Base *rhs) { return lhs->Location().getApproxDistance(startPos) < rhs->Location().getApproxDistance(startPos); } }; namespace Neolib { void MapManager::init() { BWEM::Map::Instance().Initialize(); BWEM::Map::Instance().EnableAutomaticPathAnalysis(); for (auto &a : BWEM::Map::Instance().Areas()) for (auto &b : a.Bases()) allBases.push_back(&b); for (auto &b : allBases) { if (BWAPI::Broodwar->isVisible(b->Location())) { startPos = b->Location(); std::sort(allBases.begin(), allBases.end(), sortLocations::fromStartPos); } } } void MapManager::onFrame() { for (auto it = unexploredBases.begin(); it != unexploredBases.end(); ++it) { if (BWAPI::Broodwar->isVisible((*it)->Location())) { unexploredBases.erase(it); break; } } } const std::vector <const BWEM::Base*> MapManager::getAllBases() const { return allBases; } const std::set <const BWEM::Base*> MapManager::getUnexploredBases() const { return unexploredBases; } const BWAPI::TilePosition MapManager::getNextBasePosition() const { for (auto &b : allBases) { for (auto &ob : baseManager.getAllBases()) if (ob.BWEMBase == b) goto skiplocation; if (!BWAPI::Broodwar->isExplored(b->Location())) detectionManager.requestDetection((BWAPI::Position)b->Location()); if (BWAPI::Broodwar->canBuildHere(b->Location(), BWAPI::UnitTypes::Terran_Command_Center, nullptr, true)) { for (auto &eu : unitManager.getVisibleEnemies()) if (eu.lastPosition.getApproxDistance(BWAPI::Position(b->Location())) < 1000) goto skiplocation; for (auto &eu : unitManager.getNonVisibleEnemies()) if (eu.lastPosition.getApproxDistance(BWAPI::Position(b->Location())) < 500) goto skiplocation; return b->Location(); skiplocation:; } } return BWAPI::TilePosition(-1, -1); } } <|endoftext|>
<commit_before>/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2014 ETH Zurich ** 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 the ETH Zurich 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. ** ***********************************************************************************************************************/ #include "JavaDebugger.h" #include "../run_support/java/JavaRunner.h" #include "jdwp/DebugConnector.h" #include "OOModel/src/declarations/Method.h" #include "OOModel/src/declarations/Class.h" namespace OODebug { void JavaDebugger::debugTree(Model::TreeManager* manager, const QString& pathToProjectContainerDirectory) { Model::Node* mainContainer = JavaRunner::runTree(manager, pathToProjectContainerDirectory, true); // Find the class name where the main method is in. OOModel::Class* mainClass = nullptr; while (!mainClass) { auto parent = mainContainer->parent(); mainClass = DCast<OOModel::Class>(parent); mainContainer = parent; if (!mainContainer) break; } Q_ASSERT(mainClass); QString mainClassName = mainClass->name(); debugConnector().connect(mainClassName); } DebugConnector& JavaDebugger::debugConnector() { static DebugConnector debugConnector; return debugConnector; } } /* namespace OODebug */ <commit_msg>Make break at start working for tetris sample<commit_after>/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2014 ETH Zurich ** 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 the ETH Zurich 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. ** ***********************************************************************************************************************/ #include "JavaDebugger.h" #include "../run_support/java/JavaRunner.h" #include "jdwp/DebugConnector.h" #include "OOModel/src/declarations/Method.h" #include "OOModel/src/declarations/Class.h" #include "OOModel/src/declarations/Module.h" namespace OODebug { void JavaDebugger::debugTree(Model::TreeManager* manager, const QString& pathToProjectContainerDirectory) { Model::Node* mainContainer = JavaRunner::runTree(manager, pathToProjectContainerDirectory, true); // Find the class name where the main method is in. OOModel::Class* mainClass = nullptr; while (!mainClass) { auto parent = mainContainer->parent(); mainClass = DCast<OOModel::Class>(parent); mainContainer = parent; if (!mainContainer) break; } OOModel::Module* module = nullptr; while (!module) { auto parent = mainContainer->parent(); module = DCast<OOModel::Module>(parent); mainContainer = parent; if (!mainContainer) break; } Q_ASSERT(mainClass); QString mainClassName = mainClass->name(); // TODO properly support nested packages if (module) mainClassName.prepend(".").prepend(module->name()); debugConnector().connect(mainClassName); } DebugConnector& JavaDebugger::debugConnector() { static DebugConnector debugConnector; return debugConnector; } } /* namespace OODebug */ <|endoftext|>
<commit_before>/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2010-2012, 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. * * $Id$ * */ #ifndef PCL_SURFACE_IMPL_POISSON_H_ #define PCL_SURFACE_IMPL_POISSON_H_ #include <pcl/surface/poisson.h> #include <pcl/common/common.h> #include <pcl/common/vector_average.h> #include <pcl/Vertices.h> #include <pcl/surface/3rdparty/poisson4/octree_poisson.h> #include <pcl/surface/3rdparty/poisson4/sparse_matrix.h> #include <pcl/surface/3rdparty/poisson4/function_data.h> #include <pcl/surface/3rdparty/poisson4/ppolynomial.h> #include <pcl/surface/3rdparty/poisson4/multi_grid_octree_data.h> #include <pcl/surface/3rdparty/poisson4/geometry.h> #define MEMORY_ALLOCATOR_BLOCK_SIZE 1<<12 #include <stdarg.h> #include <string> using namespace pcl; ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointNT> pcl::Poisson<PointNT>::Poisson () : depth_ (8) , min_depth_ (5) , point_weight_ (4) , scale_ (1.1f) , solver_divide_ (8) , iso_divide_ (8) , samples_per_node_ (1.0) , confidence_ (false) , output_polygons_ (false) , no_reset_samples_ (false) , no_clip_tree_ (false) , manifold_ (true) , refine_ (3) , kernel_depth_ (8) , degree_ (2) , min_iterations_ (8) , solver_accuracy_ (1e-3f) , non_adaptive_weights_ (false) { } ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointNT> pcl::Poisson<PointNT>::~Poisson () { } ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointNT> template <int Degree> void pcl::Poisson<PointNT>::execute (poisson::CoredVectorMeshData &mesh, poisson::Point3D<float> &center, float &scale) { pcl::poisson::Real iso_value = 0; poisson::TreeNodeData::UseIndex = 1; poisson::Octree<Degree> tree; /// TODO OPENMP stuff // tree.threads = Threads.value; center.coords[0] = center.coords[1] = center.coords[2] = 0; if (solver_divide_ < min_depth_) { PCL_WARN ("[pcl::Poisson] solver_divide_ must be at least as large as min_depth_: %d >= %d\n", solver_divide_, min_depth_); solver_divide_ = min_depth_; } if (iso_divide_< min_depth_) { PCL_WARN ("[pcl::Poisson] iso_divide_ must be at least as large as min_depth_: %d >= %d\n", iso_divide_, min_depth_); iso_divide_ = min_depth_; } pcl::poisson::TreeOctNode::SetAllocator (MEMORY_ALLOCATOR_BLOCK_SIZE); kernel_depth_ = depth_ - 2; tree.setBSplineData (depth_, pcl::poisson::Real (1.0 / (1 << depth_)), true); tree.maxMemoryUsage = 0; int point_count = tree.setTree (input_, depth_, min_depth_, kernel_depth_, samples_per_node_, scale_, center, scale, confidence_, point_weight_, !non_adaptive_weights_); tree.ClipTree (); tree.finalize (); tree.RefineBoundary (iso_divide_); PCL_DEBUG ("Input Points: %d\n" , point_count ); PCL_DEBUG ("Leaves/Nodes: %d/%d\n" , tree.tree.leaves() , tree.tree.nodes() ); tree.maxMemoryUsage = 0; tree.SetLaplacianConstraints (); tree.maxMemoryUsage = 0; tree.LaplacianMatrixIteration (solver_divide_, show_residual_, min_iterations_, solver_accuracy_); iso_value = tree.GetIsoValue (); tree.GetMCIsoTriangles (iso_value, iso_divide_, &mesh, 0, 1, manifold_, output_polygons_); } ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointNT> void pcl::Poisson<PointNT>::performReconstruction (PolygonMesh &output) { poisson::CoredVectorMeshData mesh; poisson::Point3D<float> center; float scale = 1.0f; switch (degree_) { case 1: { execute<1> (mesh, center, scale); break; } case 2: { execute<2> (mesh, center, scale); break; } case 3: { execute<3> (mesh, center, scale); break; } case 4: { execute<4> (mesh, center, scale); break; } case 5: { execute<5> (mesh, center, scale); break; } default: { PCL_ERROR (stderr, "Degree %d not supported\n", degree_); } } // Write output PolygonMesh pcl::PointCloud<pcl::PointXYZ> cloud; cloud.points.resize (int (mesh.outOfCorePointCount () + mesh.inCorePoints.size ())); poisson::Point3D<float> p; for (int i = 0; i < int (mesh.inCorePoints.size ()); i++) { p = mesh.inCorePoints[i]; cloud.points[i].x = p.coords[0]*scale+center.coords[0]; cloud.points[i].y = p.coords[1]*scale+center.coords[1]; cloud.points[i].z = p.coords[2]*scale+center.coords[2]; } for (int i = int (mesh.inCorePoints.size ()); i < int (mesh.outOfCorePointCount () + mesh.inCorePoints.size ()); i++) { mesh.nextOutOfCorePoint (p); cloud.points[i].x = p.coords[0]*scale+center.coords[0]; cloud.points[i].y = p.coords[1]*scale+center.coords[1]; cloud.points[i].z = p.coords[2]*scale+center.coords[2]; } pcl::toROSMsg (cloud, output.cloud); output.polygons.resize (mesh.polygonCount ()); // Write faces std::vector<poisson::CoredVertexIndex> polygon; for (int p_i = 0; p_i < mesh.polygonCount (); p_i++) { pcl::Vertices v; mesh.nextPolygon (polygon); v.vertices.resize (polygon.size ()); for (int i = 0; i < static_cast<int> (polygon.size ()); ++i) if (polygon[i].inCore ) v.vertices[i] = polygon[i].idx; else v.vertices[i] = polygon[i].idx + int (mesh.inCorePoints.size ()); output.polygons[p_i] = v; } } ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointNT> void pcl::Poisson<PointNT>::performReconstruction (pcl::PointCloud<PointNT> &points, std::vector<pcl::Vertices> &polygons) { poisson::CoredVectorMeshData mesh; poisson::Point3D<float> center; float scale = 1.0f; switch (degree_) { case 1: { execute<1> (mesh, center, scale); break; } case 2: { execute<2> (mesh, center, scale); break; } case 3: { execute<3> (mesh, center, scale); break; } case 4: { execute<4> (mesh, center, scale); break; } case 5: { execute<5> (mesh, center, scale); break; } default: { PCL_ERROR (stderr, "Degree %d not supported\n", degree_); } } // Write output PolygonMesh // Write vertices points.points.resize (int (mesh.outOfCorePointCount () + mesh.inCorePoints.size ())); poisson::Point3D<float> p; for (int i = 0; i < int(mesh.inCorePoints.size ()); i++) { p = mesh.inCorePoints[i]; points.points[i].x = p.coords[0]*scale+center.coords[0]; points.points[i].y = p.coords[1]*scale+center.coords[1]; points.points[i].z = p.coords[2]*scale+center.coords[2]; } for (int i = int(mesh.inCorePoints.size()); i < int (mesh.outOfCorePointCount() + mesh.inCorePoints.size ()); i++) { mesh.nextOutOfCorePoint (p); points.points[i].x = p.coords[0]*scale+center.coords[0]; points.points[i].y = p.coords[1]*scale+center.coords[1]; points.points[i].z = p.coords[2]*scale+center.coords[2]; } polygons.resize (mesh.polygonCount ()); // Write faces std::vector<poisson::CoredVertexIndex> polygon; for (int p_i = 0; p_i < mesh.polygonCount (); p_i++) { pcl::Vertices v; mesh.nextPolygon (polygon); v.vertices.resize (polygon.size ()); for (int i = 0; i < static_cast<int> (polygon.size ()); ++i) if (polygon[i].inCore ) v.vertices[i] = polygon[i].idx; else v.vertices[i] = polygon[i].idx + int (mesh.inCorePoints.size ()); polygons[p_i] = v; } } #define PCL_INSTANTIATE_Poisson(T) template class PCL_EXPORTS pcl::Poisson<T>; #endif // PCL_SURFACE_IMPL_POISSON_H_ <commit_msg>fixed compiler warnings<commit_after>/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2010-2012, 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. * * $Id$ * */ #ifndef PCL_SURFACE_IMPL_POISSON_H_ #define PCL_SURFACE_IMPL_POISSON_H_ #include <pcl/surface/poisson.h> #include <pcl/common/common.h> #include <pcl/common/vector_average.h> #include <pcl/Vertices.h> #include <pcl/surface/3rdparty/poisson4/octree_poisson.h> #include <pcl/surface/3rdparty/poisson4/sparse_matrix.h> #include <pcl/surface/3rdparty/poisson4/function_data.h> #include <pcl/surface/3rdparty/poisson4/ppolynomial.h> #include <pcl/surface/3rdparty/poisson4/multi_grid_octree_data.h> #include <pcl/surface/3rdparty/poisson4/geometry.h> #define MEMORY_ALLOCATOR_BLOCK_SIZE 1<<12 #include <stdarg.h> #include <string> using namespace pcl; ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointNT> pcl::Poisson<PointNT>::Poisson () : depth_ (8) , min_depth_ (5) , point_weight_ (4) , scale_ (1.1f) , solver_divide_ (8) , iso_divide_ (8) , samples_per_node_ (1.0) , confidence_ (false) , output_polygons_ (false) , no_reset_samples_ (false) , no_clip_tree_ (false) , manifold_ (true) , refine_ (3) , kernel_depth_ (8) , degree_ (2) , non_adaptive_weights_ (false) , show_residual_ (false) , min_iterations_ (8) , solver_accuracy_ (1e-3f) { } ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointNT> pcl::Poisson<PointNT>::~Poisson () { } ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointNT> template <int Degree> void pcl::Poisson<PointNT>::execute (poisson::CoredVectorMeshData &mesh, poisson::Point3D<float> &center, float &scale) { pcl::poisson::Real iso_value = 0; poisson::TreeNodeData::UseIndex = 1; poisson::Octree<Degree> tree; /// TODO OPENMP stuff // tree.threads = Threads.value; center.coords[0] = center.coords[1] = center.coords[2] = 0; if (solver_divide_ < min_depth_) { PCL_WARN ("[pcl::Poisson] solver_divide_ must be at least as large as min_depth_: %d >= %d\n", solver_divide_, min_depth_); solver_divide_ = min_depth_; } if (iso_divide_< min_depth_) { PCL_WARN ("[pcl::Poisson] iso_divide_ must be at least as large as min_depth_: %d >= %d\n", iso_divide_, min_depth_); iso_divide_ = min_depth_; } pcl::poisson::TreeOctNode::SetAllocator (MEMORY_ALLOCATOR_BLOCK_SIZE); kernel_depth_ = depth_ - 2; tree.setBSplineData (depth_, pcl::poisson::Real (1.0 / (1 << depth_)), true); tree.maxMemoryUsage = 0; int point_count = tree.setTree (input_, depth_, min_depth_, kernel_depth_, samples_per_node_, scale_, center, scale, confidence_, point_weight_, !non_adaptive_weights_); tree.ClipTree (); tree.finalize (); tree.RefineBoundary (iso_divide_); PCL_DEBUG ("Input Points: %d\n" , point_count ); PCL_DEBUG ("Leaves/Nodes: %d/%d\n" , tree.tree.leaves() , tree.tree.nodes() ); tree.maxMemoryUsage = 0; tree.SetLaplacianConstraints (); tree.maxMemoryUsage = 0; tree.LaplacianMatrixIteration (solver_divide_, show_residual_, min_iterations_, solver_accuracy_); iso_value = tree.GetIsoValue (); tree.GetMCIsoTriangles (iso_value, iso_divide_, &mesh, 0, 1, manifold_, output_polygons_); } ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointNT> void pcl::Poisson<PointNT>::performReconstruction (PolygonMesh &output) { poisson::CoredVectorMeshData mesh; poisson::Point3D<float> center; float scale = 1.0f; switch (degree_) { case 1: { execute<1> (mesh, center, scale); break; } case 2: { execute<2> (mesh, center, scale); break; } case 3: { execute<3> (mesh, center, scale); break; } case 4: { execute<4> (mesh, center, scale); break; } case 5: { execute<5> (mesh, center, scale); break; } default: { PCL_ERROR (stderr, "Degree %d not supported\n", degree_); } } // Write output PolygonMesh pcl::PointCloud<pcl::PointXYZ> cloud; cloud.points.resize (int (mesh.outOfCorePointCount () + mesh.inCorePoints.size ())); poisson::Point3D<float> p; for (int i = 0; i < int (mesh.inCorePoints.size ()); i++) { p = mesh.inCorePoints[i]; cloud.points[i].x = p.coords[0]*scale+center.coords[0]; cloud.points[i].y = p.coords[1]*scale+center.coords[1]; cloud.points[i].z = p.coords[2]*scale+center.coords[2]; } for (int i = int (mesh.inCorePoints.size ()); i < int (mesh.outOfCorePointCount () + mesh.inCorePoints.size ()); i++) { mesh.nextOutOfCorePoint (p); cloud.points[i].x = p.coords[0]*scale+center.coords[0]; cloud.points[i].y = p.coords[1]*scale+center.coords[1]; cloud.points[i].z = p.coords[2]*scale+center.coords[2]; } pcl::toROSMsg (cloud, output.cloud); output.polygons.resize (mesh.polygonCount ()); // Write faces std::vector<poisson::CoredVertexIndex> polygon; for (int p_i = 0; p_i < mesh.polygonCount (); p_i++) { pcl::Vertices v; mesh.nextPolygon (polygon); v.vertices.resize (polygon.size ()); for (int i = 0; i < static_cast<int> (polygon.size ()); ++i) if (polygon[i].inCore ) v.vertices[i] = polygon[i].idx; else v.vertices[i] = polygon[i].idx + int (mesh.inCorePoints.size ()); output.polygons[p_i] = v; } } ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointNT> void pcl::Poisson<PointNT>::performReconstruction (pcl::PointCloud<PointNT> &points, std::vector<pcl::Vertices> &polygons) { poisson::CoredVectorMeshData mesh; poisson::Point3D<float> center; float scale = 1.0f; switch (degree_) { case 1: { execute<1> (mesh, center, scale); break; } case 2: { execute<2> (mesh, center, scale); break; } case 3: { execute<3> (mesh, center, scale); break; } case 4: { execute<4> (mesh, center, scale); break; } case 5: { execute<5> (mesh, center, scale); break; } default: { PCL_ERROR (stderr, "Degree %d not supported\n", degree_); } } // Write output PolygonMesh // Write vertices points.points.resize (int (mesh.outOfCorePointCount () + mesh.inCorePoints.size ())); poisson::Point3D<float> p; for (int i = 0; i < int(mesh.inCorePoints.size ()); i++) { p = mesh.inCorePoints[i]; points.points[i].x = p.coords[0]*scale+center.coords[0]; points.points[i].y = p.coords[1]*scale+center.coords[1]; points.points[i].z = p.coords[2]*scale+center.coords[2]; } for (int i = int(mesh.inCorePoints.size()); i < int (mesh.outOfCorePointCount() + mesh.inCorePoints.size ()); i++) { mesh.nextOutOfCorePoint (p); points.points[i].x = p.coords[0]*scale+center.coords[0]; points.points[i].y = p.coords[1]*scale+center.coords[1]; points.points[i].z = p.coords[2]*scale+center.coords[2]; } polygons.resize (mesh.polygonCount ()); // Write faces std::vector<poisson::CoredVertexIndex> polygon; for (int p_i = 0; p_i < mesh.polygonCount (); p_i++) { pcl::Vertices v; mesh.nextPolygon (polygon); v.vertices.resize (polygon.size ()); for (int i = 0; i < static_cast<int> (polygon.size ()); ++i) if (polygon[i].inCore ) v.vertices[i] = polygon[i].idx; else v.vertices[i] = polygon[i].idx + int (mesh.inCorePoints.size ()); polygons[p_i] = v; } } #define PCL_INSTANTIATE_Poisson(T) template class PCL_EXPORTS pcl::Poisson<T>; #endif // PCL_SURFACE_IMPL_POISSON_H_ <|endoftext|>
<commit_before> /************************************************************************* * * $RCSfile: accselectionhelper.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: mib $ $Date: 2002-08-15 09:29: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): _______________________________________ * * ************************************************************************/ #ifdef PRECOMPILED #include "core_pch.hxx" #endif #pragma hdrstop #ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLESELECTION_HPP_ #include <drafts/com/sun/star/accessibility/XAccessibleSelection.hpp> #endif #ifndef _ACCSELECTIONHELPER_HXX_ #include <accselectionhelper.hxx> #endif #ifndef _ACCCONTEXT_HXX #include <acccontext.hxx> #endif #ifndef _ACCMAP_HXX #include <accmap.hxx> #endif #ifndef _SVX_ACCESSIBILITY_ACCESSIBLE_SHAPE_HXX #include <svx/AccessibleShape.hxx> #endif #ifndef _VIEWSH_HXX #include <viewsh.hxx> #endif #ifndef _FESH_HXX #include "fesh.hxx" #endif #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> // for SolarMutex #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif using namespace ::com::sun::star::uno; using ::com::sun::star::uno::RuntimeException; using ::drafts::com::sun::star::accessibility::XAccessible; using ::drafts::com::sun::star::accessibility::XAccessibleContext; using ::drafts::com::sun::star::accessibility::XAccessibleSelection; using ::com::sun::star::lang::IndexOutOfBoundsException; SwAccessibleSelectionHelper::SwAccessibleSelectionHelper( SwAccessibleContext& rCtxt ) : rContext( rCtxt ) { } SwAccessibleSelectionHelper::~SwAccessibleSelectionHelper() { } SwFEShell* SwAccessibleSelectionHelper::GetFEShell() { DBG_ASSERT( rContext.GetMap() != NULL, "no map?" ); ViewShell* pViewShell = rContext.GetMap()->GetShell(); DBG_ASSERT( pViewShell != NULL, "No view shell? Then what are you looking at?" ); SwFEShell* pFEShell = NULL; if( pViewShell->ISA( SwFEShell ) ) { pFEShell = static_cast<SwFEShell*>( pViewShell ); } return pFEShell; } void SwAccessibleSelectionHelper::throwIndexOutOfBoundsException() throw ( ::com::sun::star::lang::IndexOutOfBoundsException ) { Reference < XAccessibleContext > xThis( &rContext ); Reference < XAccessibleSelection >xSelThis( xThis, UNO_QUERY ); IndexOutOfBoundsException aExcept( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("index out of bounds") ), xSelThis ); \ throw aExcept; } //===== XAccessibleSelection ============================================ void SwAccessibleSelectionHelper::selectAccessibleChild( sal_Int32 nChildIndex ) throw ( IndexOutOfBoundsException, RuntimeException ) { vos::OGuard aGuard(Application::GetSolarMutex()); // Get the respective child as SwFrm (also do index checking), ... const SwFrmOrObj aChild = rContext.GetChild( nChildIndex ); if( !aChild.IsValid() ) throwIndexOutOfBoundsException(); // we can only select fly frames, so we ignore (should: return // false) all other attempts at child selection sal_Bool bRet = sal_False; SwFEShell* pFEShell = GetFEShell(); if( pFEShell != NULL ) { const SdrObject *pObj = aChild.GetSdrObject(); if( pObj ) { bRet = rContext.Select( const_cast< SdrObject *>( pObj ), 0==aChild.GetSwFrm()); } } // no frame shell, or no frame, or no fly frame -> can't select // return bRet; } sal_Bool SwAccessibleSelectionHelper::isAccessibleChildSelected( sal_Int32 nChildIndex ) throw ( IndexOutOfBoundsException, RuntimeException ) { vos::OGuard aGuard(Application::GetSolarMutex()); // Get the respective child as SwFrm (also do index checking), ... const SwFrmOrObj aChild = rContext.GetChild( nChildIndex ); if( !aChild.IsValid() ) throwIndexOutOfBoundsException(); // ... and compare to the currently selected frame sal_Bool bRet = sal_False; SwFEShell* pFEShell = GetFEShell(); if( pFEShell ) { if( aChild.GetSwFrm() != 0 ) { bRet = (pFEShell->GetCurrFlyFrm() == aChild.GetSwFrm()); } else { bRet = pFEShell->IsObjSelected( *aChild.GetSdrObject() ); } } return bRet; } void SwAccessibleSelectionHelper::clearAccessibleSelection( ) throw ( RuntimeException ) { // return sal_False // we can't deselect } void SwAccessibleSelectionHelper::selectAllAccessible( ) throw ( RuntimeException ) { vos::OGuard aGuard(Application::GetSolarMutex()); // We can select only one. So iterate over the children to find // the first we can select, and select it. sal_Int32 nIndex = 0; SwFEShell* pFEShell = GetFEShell(); if( pFEShell ) { ::std::list< SwFrmOrObj > aChildren; rContext.GetChildren( aChildren ); ::std::list< SwFrmOrObj >::const_iterator aIter = aChildren.begin(); ::std::list< SwFrmOrObj >::const_iterator aEndIter = aChildren.end(); while( aIter != aEndIter ) { const SwFrmOrObj& rChild = *aIter; const SdrObject *pObj = rChild.GetSdrObject(); const SwFrm* pFrm = rChild.GetSwFrm(); if( pObj && !(pFrm != 0 && pFEShell->IsObjSelected()) ) { rContext.Select( const_cast< SdrObject *>( pObj ), 0==pFrm ); if( pFrm ) break; } ++aIter; } } } sal_Int32 SwAccessibleSelectionHelper::getSelectedAccessibleChildCount( ) throw ( RuntimeException ) { vos::OGuard aGuard(Application::GetSolarMutex()); sal_Int32 nCount = 0; // Only one frame can be selected at a time, and we only frames // for selectable children. SwFEShell* pFEShell = GetFEShell(); if( pFEShell != 0 ) { const SwFlyFrm *pFlyFrm = pFEShell->GetCurrFlyFrm(); if( pFlyFrm ) { if( rContext.GetParent(pFlyFrm, rContext.IsInPagePreview()) == rContext.GetFrm() ) { nCount = 1; } } else { sal_uInt16 nSelObjs = pFEShell->IsObjSelected(); if( nSelObjs > 0 ) { ::std::list< SwFrmOrObj > aChildren; rContext.GetChildren( aChildren ); ::std::list< SwFrmOrObj >::const_iterator aIter = aChildren.begin(); ::std::list< SwFrmOrObj >::const_iterator aEndIter = aChildren.end(); while( aIter != aEndIter && nCount < nSelObjs ) { const SwFrmOrObj& rChild = *aIter; if( rChild.GetSdrObject() && !rChild.GetSwFrm() && rContext.GetParent(rChild, rContext.IsInPagePreview()) == rContext.GetFrm() && pFEShell->IsObjSelected( *rChild.GetSdrObject() ) ) { nCount++; } ++aIter; } } } } return nCount; } Reference<XAccessible> SwAccessibleSelectionHelper::getSelectedAccessibleChild( sal_Int32 nSelectedChildIndex ) throw ( IndexOutOfBoundsException, RuntimeException) { vos::OGuard aGuard(Application::GetSolarMutex()); // Since the index is relative to the selected children, and since // there can be at most one selected frame child, the index must // be 0, and a selection must exist, otherwise we have to throw an // IndexOutOfBoundsException SwFEShell* pFEShell = GetFEShell(); if( 0 == pFEShell ) throwIndexOutOfBoundsException(); SwFrmOrObj aChild; const SwFlyFrm *pFlyFrm = pFEShell->GetCurrFlyFrm(); if( pFlyFrm ) { if( 0 == nSelectedChildIndex && rContext.GetParent(pFlyFrm, rContext.IsInPagePreview()) == rContext.GetFrm() ) { aChild = pFlyFrm; } } else { sal_uInt16 nSelObjs = pFEShell->IsObjSelected(); if( 0 == nSelObjs || nSelectedChildIndex >= nSelObjs ) throwIndexOutOfBoundsException(); ::std::list< SwFrmOrObj > aChildren; rContext.GetChildren( aChildren ); ::std::list< SwFrmOrObj >::const_iterator aIter = aChildren.begin(); ::std::list< SwFrmOrObj >::const_iterator aEndIter = aChildren.end(); while( aIter != aEndIter && !aChild.IsValid() ) { const SwFrmOrObj& rChild = *aIter; if( rChild.GetSdrObject() && !rChild.GetSwFrm() && rContext.GetParent(rChild, rContext.IsInPagePreview()) == rContext.GetFrm() && pFEShell->IsObjSelected( *rChild.GetSdrObject() ) ) { if( 0 == nSelectedChildIndex ) aChild = rChild; else --nSelectedChildIndex; } ++aIter; } } if( !aChild.IsValid() ) throwIndexOutOfBoundsException(); DBG_ASSERT( rContext.GetMap() != NULL, "We need the map." ); Reference< XAccessible > xChild; if( aChild.GetSwFrm() ) { ::vos::ORef < SwAccessibleContext > xChildImpl( rContext.GetMap()->GetContextImpl( aChild.GetSwFrm(), sal_True ) ); if( xChildImpl.isValid() ) { xChildImpl->SetParent( &rContext ); xChild = xChildImpl.getBodyPtr(); } } else { ::vos::ORef < ::accessibility::AccessibleShape > xChildImpl( rContext.GetMap()->GetContextImpl( aChild.GetSdrObject(), &rContext, sal_True ) ); if( xChildImpl.isValid() ) xChild = xChildImpl.getBodyPtr(); } return xChild; } void SwAccessibleSelectionHelper::deselectSelectedAccessibleChild( sal_Int32 nSelectedChildIndex ) throw ( IndexOutOfBoundsException, RuntimeException ) { // return sal_False // we can't deselect if( nSelectedChildIndex < 0 || nSelectedChildIndex >= getSelectedAccessibleChildCount() ) throwIndexOutOfBoundsException(); } <commit_msg>INTEGRATION: CWS os8 (1.5.144); FILE MERGED 2003/04/03 07:09:25 os 1.5.144.1: #108583# precompiled headers removed<commit_after> /************************************************************************* * * $RCSfile: accselectionhelper.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: vg $ $Date: 2003-04-17 13:38:12 $ * * 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): _______________________________________ * * ************************************************************************/ #pragma hdrstop #ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLESELECTION_HPP_ #include <drafts/com/sun/star/accessibility/XAccessibleSelection.hpp> #endif #ifndef _ACCSELECTIONHELPER_HXX_ #include <accselectionhelper.hxx> #endif #ifndef _ACCCONTEXT_HXX #include <acccontext.hxx> #endif #ifndef _ACCMAP_HXX #include <accmap.hxx> #endif #ifndef _SVX_ACCESSIBILITY_ACCESSIBLE_SHAPE_HXX #include <svx/AccessibleShape.hxx> #endif #ifndef _VIEWSH_HXX #include <viewsh.hxx> #endif #ifndef _FESH_HXX #include "fesh.hxx" #endif #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> // for SolarMutex #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif using namespace ::com::sun::star::uno; using ::com::sun::star::uno::RuntimeException; using ::drafts::com::sun::star::accessibility::XAccessible; using ::drafts::com::sun::star::accessibility::XAccessibleContext; using ::drafts::com::sun::star::accessibility::XAccessibleSelection; using ::com::sun::star::lang::IndexOutOfBoundsException; SwAccessibleSelectionHelper::SwAccessibleSelectionHelper( SwAccessibleContext& rCtxt ) : rContext( rCtxt ) { } SwAccessibleSelectionHelper::~SwAccessibleSelectionHelper() { } SwFEShell* SwAccessibleSelectionHelper::GetFEShell() { DBG_ASSERT( rContext.GetMap() != NULL, "no map?" ); ViewShell* pViewShell = rContext.GetMap()->GetShell(); DBG_ASSERT( pViewShell != NULL, "No view shell? Then what are you looking at?" ); SwFEShell* pFEShell = NULL; if( pViewShell->ISA( SwFEShell ) ) { pFEShell = static_cast<SwFEShell*>( pViewShell ); } return pFEShell; } void SwAccessibleSelectionHelper::throwIndexOutOfBoundsException() throw ( ::com::sun::star::lang::IndexOutOfBoundsException ) { Reference < XAccessibleContext > xThis( &rContext ); Reference < XAccessibleSelection >xSelThis( xThis, UNO_QUERY ); IndexOutOfBoundsException aExcept( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("index out of bounds") ), xSelThis ); \ throw aExcept; } //===== XAccessibleSelection ============================================ void SwAccessibleSelectionHelper::selectAccessibleChild( sal_Int32 nChildIndex ) throw ( IndexOutOfBoundsException, RuntimeException ) { vos::OGuard aGuard(Application::GetSolarMutex()); // Get the respective child as SwFrm (also do index checking), ... const SwFrmOrObj aChild = rContext.GetChild( nChildIndex ); if( !aChild.IsValid() ) throwIndexOutOfBoundsException(); // we can only select fly frames, so we ignore (should: return // false) all other attempts at child selection sal_Bool bRet = sal_False; SwFEShell* pFEShell = GetFEShell(); if( pFEShell != NULL ) { const SdrObject *pObj = aChild.GetSdrObject(); if( pObj ) { bRet = rContext.Select( const_cast< SdrObject *>( pObj ), 0==aChild.GetSwFrm()); } } // no frame shell, or no frame, or no fly frame -> can't select // return bRet; } sal_Bool SwAccessibleSelectionHelper::isAccessibleChildSelected( sal_Int32 nChildIndex ) throw ( IndexOutOfBoundsException, RuntimeException ) { vos::OGuard aGuard(Application::GetSolarMutex()); // Get the respective child as SwFrm (also do index checking), ... const SwFrmOrObj aChild = rContext.GetChild( nChildIndex ); if( !aChild.IsValid() ) throwIndexOutOfBoundsException(); // ... and compare to the currently selected frame sal_Bool bRet = sal_False; SwFEShell* pFEShell = GetFEShell(); if( pFEShell ) { if( aChild.GetSwFrm() != 0 ) { bRet = (pFEShell->GetCurrFlyFrm() == aChild.GetSwFrm()); } else { bRet = pFEShell->IsObjSelected( *aChild.GetSdrObject() ); } } return bRet; } void SwAccessibleSelectionHelper::clearAccessibleSelection( ) throw ( RuntimeException ) { // return sal_False // we can't deselect } void SwAccessibleSelectionHelper::selectAllAccessible( ) throw ( RuntimeException ) { vos::OGuard aGuard(Application::GetSolarMutex()); // We can select only one. So iterate over the children to find // the first we can select, and select it. sal_Int32 nIndex = 0; SwFEShell* pFEShell = GetFEShell(); if( pFEShell ) { ::std::list< SwFrmOrObj > aChildren; rContext.GetChildren( aChildren ); ::std::list< SwFrmOrObj >::const_iterator aIter = aChildren.begin(); ::std::list< SwFrmOrObj >::const_iterator aEndIter = aChildren.end(); while( aIter != aEndIter ) { const SwFrmOrObj& rChild = *aIter; const SdrObject *pObj = rChild.GetSdrObject(); const SwFrm* pFrm = rChild.GetSwFrm(); if( pObj && !(pFrm != 0 && pFEShell->IsObjSelected()) ) { rContext.Select( const_cast< SdrObject *>( pObj ), 0==pFrm ); if( pFrm ) break; } ++aIter; } } } sal_Int32 SwAccessibleSelectionHelper::getSelectedAccessibleChildCount( ) throw ( RuntimeException ) { vos::OGuard aGuard(Application::GetSolarMutex()); sal_Int32 nCount = 0; // Only one frame can be selected at a time, and we only frames // for selectable children. SwFEShell* pFEShell = GetFEShell(); if( pFEShell != 0 ) { const SwFlyFrm *pFlyFrm = pFEShell->GetCurrFlyFrm(); if( pFlyFrm ) { if( rContext.GetParent(pFlyFrm, rContext.IsInPagePreview()) == rContext.GetFrm() ) { nCount = 1; } } else { sal_uInt16 nSelObjs = pFEShell->IsObjSelected(); if( nSelObjs > 0 ) { ::std::list< SwFrmOrObj > aChildren; rContext.GetChildren( aChildren ); ::std::list< SwFrmOrObj >::const_iterator aIter = aChildren.begin(); ::std::list< SwFrmOrObj >::const_iterator aEndIter = aChildren.end(); while( aIter != aEndIter && nCount < nSelObjs ) { const SwFrmOrObj& rChild = *aIter; if( rChild.GetSdrObject() && !rChild.GetSwFrm() && rContext.GetParent(rChild, rContext.IsInPagePreview()) == rContext.GetFrm() && pFEShell->IsObjSelected( *rChild.GetSdrObject() ) ) { nCount++; } ++aIter; } } } } return nCount; } Reference<XAccessible> SwAccessibleSelectionHelper::getSelectedAccessibleChild( sal_Int32 nSelectedChildIndex ) throw ( IndexOutOfBoundsException, RuntimeException) { vos::OGuard aGuard(Application::GetSolarMutex()); // Since the index is relative to the selected children, and since // there can be at most one selected frame child, the index must // be 0, and a selection must exist, otherwise we have to throw an // IndexOutOfBoundsException SwFEShell* pFEShell = GetFEShell(); if( 0 == pFEShell ) throwIndexOutOfBoundsException(); SwFrmOrObj aChild; const SwFlyFrm *pFlyFrm = pFEShell->GetCurrFlyFrm(); if( pFlyFrm ) { if( 0 == nSelectedChildIndex && rContext.GetParent(pFlyFrm, rContext.IsInPagePreview()) == rContext.GetFrm() ) { aChild = pFlyFrm; } } else { sal_uInt16 nSelObjs = pFEShell->IsObjSelected(); if( 0 == nSelObjs || nSelectedChildIndex >= nSelObjs ) throwIndexOutOfBoundsException(); ::std::list< SwFrmOrObj > aChildren; rContext.GetChildren( aChildren ); ::std::list< SwFrmOrObj >::const_iterator aIter = aChildren.begin(); ::std::list< SwFrmOrObj >::const_iterator aEndIter = aChildren.end(); while( aIter != aEndIter && !aChild.IsValid() ) { const SwFrmOrObj& rChild = *aIter; if( rChild.GetSdrObject() && !rChild.GetSwFrm() && rContext.GetParent(rChild, rContext.IsInPagePreview()) == rContext.GetFrm() && pFEShell->IsObjSelected( *rChild.GetSdrObject() ) ) { if( 0 == nSelectedChildIndex ) aChild = rChild; else --nSelectedChildIndex; } ++aIter; } } if( !aChild.IsValid() ) throwIndexOutOfBoundsException(); DBG_ASSERT( rContext.GetMap() != NULL, "We need the map." ); Reference< XAccessible > xChild; if( aChild.GetSwFrm() ) { ::vos::ORef < SwAccessibleContext > xChildImpl( rContext.GetMap()->GetContextImpl( aChild.GetSwFrm(), sal_True ) ); if( xChildImpl.isValid() ) { xChildImpl->SetParent( &rContext ); xChild = xChildImpl.getBodyPtr(); } } else { ::vos::ORef < ::accessibility::AccessibleShape > xChildImpl( rContext.GetMap()->GetContextImpl( aChild.GetSdrObject(), &rContext, sal_True ) ); if( xChildImpl.isValid() ) xChild = xChildImpl.getBodyPtr(); } return xChild; } void SwAccessibleSelectionHelper::deselectSelectedAccessibleChild( sal_Int32 nSelectedChildIndex ) throw ( IndexOutOfBoundsException, RuntimeException ) { // return sal_False // we can't deselect if( nSelectedChildIndex < 0 || nSelectedChildIndex >= getSelectedAccessibleChildCount() ) throwIndexOutOfBoundsException(); } <|endoftext|>
<commit_before>// strip chart example // Author: Rene Brun void seism() { TStopwatch sw; sw.Start(); //set time offset TDatime dtime; gStyle->SetTimeOffset(dtime.Convert()); TCanvas *c1 = new TCanvas("c1","Time on axis",10,10,1000,500); c1->SetFillColor(42); c1->SetFrameFillColor(33); c1->SetGrid(); Float_t bintime = 1; //one bin = 1 second. change it to set the time scale TH1F *ht = new TH1F("ht","The ROOT seism",10,0,10*bintime); Float_t signal = 1000; ht->SetMaximum( signal); ht->SetMinimum(-signal); ht->SetStats(0); ht->SetLineColor(2); ht->GetXaxis()->SetTimeDisplay(1); ht->GetYaxis()->SetNdivisions(520); ht->Draw(); for (Int_t i=1;i<2300;i++) { //======= Build a signal : noisy damped sine ====== Float_t noise = gRandom->Gaus(0,120); if (i > 700) noise += signal*sin((i-700.)*6.28/30)*exp((700.-i)/300.); ht->SetBinContent(i,noise); c1->Modified(); c1->Update(); gSystem->ProcessEvents(); //canvas can be edited during the loop } printf("Real Time = %8.3fs, Cput Time = %8.3fs\n",sw.RealTime(),sw.CpuTime()); } <commit_msg>Fix typo in format<commit_after>// strip chart example // Author: Rene Brun void seism() { TStopwatch sw; sw.Start(); //set time offset TDatime dtime; gStyle->SetTimeOffset(dtime.Convert()); TCanvas *c1 = new TCanvas("c1","Time on axis",10,10,1000,500); c1->SetFillColor(42); c1->SetFrameFillColor(33); c1->SetGrid(); Float_t bintime = 1; //one bin = 1 second. change it to set the time scale TH1F *ht = new TH1F("ht","The ROOT seism",10,0,10*bintime); Float_t signal = 1000; ht->SetMaximum( signal); ht->SetMinimum(-signal); ht->SetStats(0); ht->SetLineColor(2); ht->GetXaxis()->SetTimeDisplay(1); ht->GetYaxis()->SetNdivisions(520); ht->Draw(); for (Int_t i=1;i<2300;i++) { //======= Build a signal : noisy damped sine ====== Float_t noise = gRandom->Gaus(0,120); if (i > 700) noise += signal*sin((i-700.)*6.28/30)*exp((700.-i)/300.); ht->SetBinContent(i,noise); c1->Modified(); c1->Update(); gSystem->ProcessEvents(); //canvas can be edited during the loop } printf("Real Time = %8.3fs, Cpu Time = %8.3fs\n",sw.RealTime(),sw.CpuTime()); } <|endoftext|>
<commit_before>// example of macro to read data from an ascii file and // create a root file with a Tree. // see also a variant in cernbuild.C // Author: Rene Brun void staff() { struct staff_t { Int_t Category; UInt_t Flag; Int_t Age; Int_t Service; Int_t Children; Int_t Grade; Int_t Step; Int_t Hrweek; Int_t Cost; Char_t Division[4]; Char_t Nation[3]; }; staff_t staff; //The input file cern.dat is a copy of the CERN staff data base //from 1988 FILE *fp = fopen("cernstaff.dat","r"); char line[80]; TFile *f = new TFile("staff.root","RECREATE"); TTree *tree = new TTree("T","staff data from ascii file"); tree->Branch("staff",&staff.Category,"Category/I:Flag:Age:Service:Children:Grade:Step:Hrweek:Cost"); tree->Branch("Division",staff.Division,"Division/C"); tree->Branch("Nation",staff.Nation,"Nation/C"); //note that the branches Division and Nation cannot be on the first branch while (fgets(&line,80,fp)) { sscanf(&line[0],"%d %d %d %d %d",&staff.Category,&staff.Flag,&staff.Age,&staff.Service,&staff.Children); sscanf(&line[32],"%d %d %d %d %s %s",&staff.Grade,&staff.Step,&staff.Hrweek,&staff.Cost,staff.Division,staff.Nation); tree->Fill(); } tree->Print(); tree->Write(); fclose(fp); } <commit_msg>Close the tree and the file before leaving teh script.<commit_after>// example of macro to read data from an ascii file and // create a root file with a Tree. // see also a variant in cernbuild.C // Author: Rene Brun void staff() { struct staff_t { Int_t Category; UInt_t Flag; Int_t Age; Int_t Service; Int_t Children; Int_t Grade; Int_t Step; Int_t Hrweek; Int_t Cost; Char_t Division[4]; Char_t Nation[3]; }; staff_t staff; //The input file cern.dat is a copy of the CERN staff data base //from 1988 FILE *fp = fopen("cernstaff.dat","r"); char line[80]; TFile *f = new TFile("staff.root","RECREATE"); TTree *tree = new TTree("T","staff data from ascii file"); tree->Branch("staff",&staff.Category,"Category/I:Flag:Age:Service:Children:Grade:Step:Hrweek:Cost"); tree->Branch("Division",staff.Division,"Division/C"); tree->Branch("Nation",staff.Nation,"Nation/C"); //note that the branches Division and Nation cannot be on the first branch while (fgets(&line,80,fp)) { sscanf(&line[0],"%d %d %d %d %d",&staff.Category,&staff.Flag,&staff.Age,&staff.Service,&staff.Children); sscanf(&line[32],"%d %d %d %d %s %s",&staff.Grade,&staff.Step,&staff.Hrweek,&staff.Cost,staff.Division,staff.Nation); tree->Fill(); } tree->Print(); tree->Write(); fclose(fp); delete tree; delete f; } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkOBJImporterInternals.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 "vtkSmartPointer.h" #include "vtkOBJImporter.h" #include "vtkOBJImporterInternals.h" #include "vtkJPEGReader.h" #include "vtkPNGReader.h" #include "vtkPolyDataMapper.h" #include "vtkProperty.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtksys/SystemTools.hxx" #include <iostream> #include <cstdlib> #include <cstdio> #include <cstring> #include <map> #if defined(_WIN32) #pragma warning(disable : 4267) #pragma warning(disable : 4800) #endif const int OBJ_LINE_SIZE = 4096; namespace { char strequal(const char *s1, const char *s2) { if(strcmp(s1, s2) == 0) { return 1; } return 0; } int localVerbosity = 0; } void obj_set_material_defaults(vtkOBJImportedMaterial* mtl) { mtl->amb[0] = 0.2; mtl->amb[1] = 0.2; mtl->amb[2] = 0.2; mtl->diff[0] = 0.8; mtl->diff[1] = 0.8; mtl->diff[2] = 0.8; mtl->spec[0] = 1.0; mtl->spec[1] = 1.0; mtl->spec[2] = 1.0; mtl->reflect = 0.0; mtl->trans = 1; mtl->glossy = 98; mtl->shiny = 0; mtl->refract_index = 1; mtl->texture_filename[0] = '\0'; if( localVerbosity > 0 ) { vtkGenericWarningMacro("Created a default vtkOBJImportedMaterial, texture filename is " << std::string(mtl->texture_filename)); } } std::vector<vtkOBJImportedMaterial*> vtkOBJPolyDataProcessor::ParseOBJandMTL( std::string Filename, int& result_code) { std::vector<vtkOBJImportedMaterial*> listOfMaterials; result_code = 0; const char* filename = Filename.c_str(); int line_number = 0; char *current_token; char current_line[OBJ_LINE_SIZE]; char material_open = 0; vtkOBJImportedMaterial* current_mtl = NULL; FILE *mtl_file_stream; // open scene mtl_file_stream = fopen( filename, "r"); if(mtl_file_stream == 0) { vtkErrorMacro("Error reading file: " << filename); result_code = -1; return listOfMaterials; } while( fgets(current_line, OBJ_LINE_SIZE, mtl_file_stream) ) { current_token = strtok( current_line, " \t\n\r"); line_number++; //skip comments if( current_token == NULL || strequal(current_token, "//") || strequal(current_token, "#")) { continue; } //start material else if( strequal(current_token, "newmtl")) { material_open = 1; current_mtl = (new vtkOBJImportedMaterial); listOfMaterials.push_back(current_mtl); obj_set_material_defaults(current_mtl); // material names can have spaces in them // get the name strncpy(current_mtl->name, strtok(NULL, "\t\n\r"), MATERIAL_NAME_SIZE); // be safe with strncpy if (current_mtl->name[MATERIAL_NAME_SIZE-1] != '\0') { current_mtl->name[MATERIAL_NAME_SIZE-1] = '\0'; vtkErrorMacro("material name too long, truncated"); } } //ambient else if( strequal(current_token, "Ka") && material_open) { // But this is ... right? no? current_mtl->amb[0] = atof( strtok(NULL, " \t")); current_mtl->amb[1] = atof( strtok(NULL, " \t")); current_mtl->amb[2] = atof( strtok(NULL, " \t")); } //diff else if( strequal(current_token, "Kd") && material_open) { current_mtl->diff[0] = atof( strtok(NULL, " \t")); current_mtl->diff[1] = atof( strtok(NULL, " \t")); current_mtl->diff[2] = atof( strtok(NULL, " \t")); } //specular else if( strequal(current_token, "Ks") && material_open) { current_mtl->spec[0] = atof( strtok(NULL, " \t")); current_mtl->spec[1] = atof( strtok(NULL, " \t")); current_mtl->spec[2] = atof( strtok(NULL, " \t")); } //shiny else if( strequal(current_token, "Ns") && material_open) { current_mtl->shiny = atof( strtok(NULL, " \t")); } //transparent else if( strequal(current_token, "d") && material_open) { current_mtl->trans = atof( strtok(NULL, " \t")); } //reflection else if( strequal(current_token, "r") && material_open) { current_mtl->reflect = atof( strtok(NULL, " \t")); } //glossy else if( strequal(current_token, "sharpness") && material_open) { current_mtl->glossy = atof( strtok(NULL, " \t")); } //refract index else if( strequal(current_token, "Ni") && material_open) { current_mtl->refract_index = atof( strtok(NULL, " \t")); } // illumination type else if( strequal(current_token, "illum") && material_open) { } // texture map else if( (strequal(current_token, "map_kd") || strequal(current_token, "map_Kd")) && material_open) { /** (pk note: why was this map_Ka initially? should map_Ka be supported? ) */ // tmap may be null so we test first before doing a strncpy char *tmap = strtok(NULL, " \t\n\r"); if (tmap) { strncpy(current_mtl->texture_filename, tmap, OBJ_FILENAME_LENGTH); // be safe with strncpy if (current_mtl->texture_filename[OBJ_FILENAME_LENGTH-1] != '\0') { current_mtl->texture_filename[OBJ_FILENAME_LENGTH-1] = '\0'; vtkErrorMacro("texture name too long, truncated"); } bool bFileExistsNoPath = vtksys::SystemTools::FileExists(current_mtl->texture_filename); std::vector<std::string> path_and_file(2); path_and_file[0] = this->GetTexturePath(); path_and_file[1] = std::string(current_mtl->texture_filename); std::string joined = vtksys::SystemTools::JoinPath(path_and_file); bool bFileExistsInPath = vtksys::SystemTools::FileExists( joined.c_str() ); if(! (bFileExistsNoPath || bFileExistsInPath ) ) { vtkGenericWarningMacro( << "mtl file " << current_mtl->name << "requests texture file that appears not to exist: " << current_mtl->texture_filename << "; texture path: " <<this->TexturePath<<"\n"); } } } else { // just skip it; got an unsupported feature or a comment in file. vtkDebugMacro("Unknown command " << current_token << " in material file " << filename << " at line " << line_number << ":\n\t" << current_line); } } fclose(mtl_file_stream); return listOfMaterials; } void bindTexturedPolydataToRenderWindow( vtkRenderWindow* renderWindow, vtkRenderer* renderer, vtkOBJPolyDataProcessor* reader ) { if( NULL == (renderWindow) ) { vtkErrorWithObjectMacro(reader, "RenderWindow is null, failure!"); return; } if( NULL == (renderer) ) { vtkErrorWithObjectMacro(reader, "Renderer is null, failure!"); return; } if( NULL == (reader) ) { vtkErrorWithObjectMacro(reader, "vtkOBJPolyDataProcessor is null, failure!"); return; } reader->actor_list.clear(); reader->actor_list.reserve( reader->GetNumberOfOutputPorts() ); for( int port_idx=0; port_idx < reader->GetNumberOfOutputPorts(); port_idx++) { vtkPolyData* objPoly = reader->GetOutput(port_idx); vtkSmartPointer<vtkPolyDataMapper> mapper = vtkSmartPointer<vtkPolyDataMapper>::New(); mapper->SetInput(objPoly); vtkDebugWithObjectMacro(reader, "Grabbed objPoly " << objPoly << ", port index " << port_idx << "\n" << "numPolys = " << objPoly->GetNumberOfPolys() << " numPoints = " << objPoly->GetNumberOfPoints()); // For each named material, load and bind the texture, add it to the renderer vtkSmartPointer<vtkTexture> vtk_texture = vtkSmartPointer<vtkTexture>::New(); std::string textureFilename = reader->GetTextureFilename(port_idx); vtkSmartPointer<vtkJPEGReader> tex_jpg_Loader = vtkSmartPointer<vtkJPEGReader>::New(); vtkSmartPointer<vtkPNGReader> tex_png_Loader = vtkSmartPointer<vtkPNGReader>::New(); int bIsReadableJPEG = tex_jpg_Loader->CanReadFile( textureFilename.c_str() ); int bIsReadablePNG = tex_png_Loader->CanReadFile( textureFilename.c_str() ); bool haveTexture = false; if (!textureFilename.empty()) { if( bIsReadableJPEG ) { tex_jpg_Loader->SetFileName( textureFilename.c_str() ); tex_jpg_Loader->Update(); vtk_texture->AddInputConnection( tex_jpg_Loader->GetOutputPort() ); haveTexture = true; } else if( bIsReadablePNG ) { tex_png_Loader->SetFileName( textureFilename.c_str() ); tex_png_Loader->Update(); vtk_texture->AddInputConnection( tex_png_Loader->GetOutputPort() ); haveTexture = true; } else { if(!textureFilename.empty()) // OK to have no texture image, but if its not empty it ought to exist. { vtkErrorWithObjectMacro(reader, "Nonexistent texture image type!? imagefile: " <<textureFilename); } } vtk_texture->InterpolateOff(); // Faster?? (yes clearly faster for largish texture) } vtkSmartPointer<vtkActor> actor = vtkSmartPointer<vtkActor>::New(); actor->SetMapper(mapper); if (haveTexture) { actor->SetTexture(vtk_texture); } vtkSmartPointer<vtkProperty> properties = vtkSmartPointer<vtkProperty>::New(); vtkOBJImportedMaterial* raw_mtl_data = reader->GetMaterial(port_idx); properties->SetDiffuseColor(raw_mtl_data->diff); properties->SetSpecularColor(raw_mtl_data->spec); properties->SetAmbientColor(raw_mtl_data->amb); properties->SetOpacity(raw_mtl_data->trans); properties->SetInterpolationToPhong(); properties->SetLighting(true); properties->SetSpecular( raw_mtl_data->get_spec_coeff() ); properties->SetAmbient( raw_mtl_data->get_amb_coeff() ); properties->SetDiffuse( raw_mtl_data->get_diff_coeff() ); actor->SetProperty(properties); renderer->AddActor(actor); //properties->ShadingOn(); // use ShadingOn() if loading vtkMaterial from xml // available in mtl parser are: // double amb[3]; // double diff[3]; // double spec[3]; // double reflect; // double refract; // double trans; // double shiny; // double glossy; // double refract_index; reader->actor_list.push_back(actor); // keep a handle on actors to animate later } /** post-condition of this function: the renderer has had a bunch of actors added to it */ } vtkOBJImportedMaterial::vtkOBJImportedMaterial() { name[0] = 'x'; name[1] = '\0'; obj_set_material_defaults(this); } <commit_msg>don't print an error if the mtl filename has not been set<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkOBJImporterInternals.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 "vtkSmartPointer.h" #include "vtkOBJImporter.h" #include "vtkOBJImporterInternals.h" #include "vtkJPEGReader.h" #include "vtkPNGReader.h" #include "vtkPolyDataMapper.h" #include "vtkProperty.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtksys/SystemTools.hxx" #include <iostream> #include <cstdlib> #include <cstdio> #include <cstring> #include <map> #if defined(_WIN32) #pragma warning(disable : 4267) #pragma warning(disable : 4800) #endif const int OBJ_LINE_SIZE = 4096; namespace { char strequal(const char *s1, const char *s2) { if(strcmp(s1, s2) == 0) { return 1; } return 0; } int localVerbosity = 0; } void obj_set_material_defaults(vtkOBJImportedMaterial* mtl) { mtl->amb[0] = 0.2; mtl->amb[1] = 0.2; mtl->amb[2] = 0.2; mtl->diff[0] = 0.8; mtl->diff[1] = 0.8; mtl->diff[2] = 0.8; mtl->spec[0] = 1.0; mtl->spec[1] = 1.0; mtl->spec[2] = 1.0; mtl->reflect = 0.0; mtl->trans = 1; mtl->glossy = 98; mtl->shiny = 0; mtl->refract_index = 1; mtl->texture_filename[0] = '\0'; if( localVerbosity > 0 ) { vtkGenericWarningMacro("Created a default vtkOBJImportedMaterial, texture filename is " << std::string(mtl->texture_filename)); } } std::vector<vtkOBJImportedMaterial*> vtkOBJPolyDataProcessor::ParseOBJandMTL( std::string Filename, int& result_code) { std::vector<vtkOBJImportedMaterial*> listOfMaterials; result_code = 0; if (Filename.empty()) { return listOfMaterials; } const char* filename = Filename.c_str(); int line_number = 0; char *current_token; char current_line[OBJ_LINE_SIZE]; char material_open = 0; vtkOBJImportedMaterial* current_mtl = NULL; FILE *mtl_file_stream; // open scene mtl_file_stream = fopen( filename, "r"); if(mtl_file_stream == 0) { vtkErrorMacro("Error reading file: " << filename); result_code = -1; return listOfMaterials; } while( fgets(current_line, OBJ_LINE_SIZE, mtl_file_stream) ) { current_token = strtok( current_line, " \t\n\r"); line_number++; //skip comments if( current_token == NULL || strequal(current_token, "//") || strequal(current_token, "#")) { continue; } //start material else if( strequal(current_token, "newmtl")) { material_open = 1; current_mtl = (new vtkOBJImportedMaterial); listOfMaterials.push_back(current_mtl); obj_set_material_defaults(current_mtl); // material names can have spaces in them // get the name strncpy(current_mtl->name, strtok(NULL, "\t\n\r"), MATERIAL_NAME_SIZE); // be safe with strncpy if (current_mtl->name[MATERIAL_NAME_SIZE-1] != '\0') { current_mtl->name[MATERIAL_NAME_SIZE-1] = '\0'; vtkErrorMacro("material name too long, truncated"); } } //ambient else if( strequal(current_token, "Ka") && material_open) { // But this is ... right? no? current_mtl->amb[0] = atof( strtok(NULL, " \t")); current_mtl->amb[1] = atof( strtok(NULL, " \t")); current_mtl->amb[2] = atof( strtok(NULL, " \t")); } //diff else if( strequal(current_token, "Kd") && material_open) { current_mtl->diff[0] = atof( strtok(NULL, " \t")); current_mtl->diff[1] = atof( strtok(NULL, " \t")); current_mtl->diff[2] = atof( strtok(NULL, " \t")); } //specular else if( strequal(current_token, "Ks") && material_open) { current_mtl->spec[0] = atof( strtok(NULL, " \t")); current_mtl->spec[1] = atof( strtok(NULL, " \t")); current_mtl->spec[2] = atof( strtok(NULL, " \t")); } //shiny else if( strequal(current_token, "Ns") && material_open) { current_mtl->shiny = atof( strtok(NULL, " \t")); } //transparent else if( strequal(current_token, "d") && material_open) { current_mtl->trans = atof( strtok(NULL, " \t")); } //reflection else if( strequal(current_token, "r") && material_open) { current_mtl->reflect = atof( strtok(NULL, " \t")); } //glossy else if( strequal(current_token, "sharpness") && material_open) { current_mtl->glossy = atof( strtok(NULL, " \t")); } //refract index else if( strequal(current_token, "Ni") && material_open) { current_mtl->refract_index = atof( strtok(NULL, " \t")); } // illumination type else if( strequal(current_token, "illum") && material_open) { } // texture map else if( (strequal(current_token, "map_kd") || strequal(current_token, "map_Kd")) && material_open) { /** (pk note: why was this map_Ka initially? should map_Ka be supported? ) */ // tmap may be null so we test first before doing a strncpy char *tmap = strtok(NULL, " \t\n\r"); if (tmap) { strncpy(current_mtl->texture_filename, tmap, OBJ_FILENAME_LENGTH); // be safe with strncpy if (current_mtl->texture_filename[OBJ_FILENAME_LENGTH-1] != '\0') { current_mtl->texture_filename[OBJ_FILENAME_LENGTH-1] = '\0'; vtkErrorMacro("texture name too long, truncated"); } bool bFileExistsNoPath = vtksys::SystemTools::FileExists(current_mtl->texture_filename); std::vector<std::string> path_and_file(2); path_and_file[0] = this->GetTexturePath(); path_and_file[1] = std::string(current_mtl->texture_filename); std::string joined = vtksys::SystemTools::JoinPath(path_and_file); bool bFileExistsInPath = vtksys::SystemTools::FileExists( joined.c_str() ); if(! (bFileExistsNoPath || bFileExistsInPath ) ) { vtkGenericWarningMacro( << "mtl file " << current_mtl->name << "requests texture file that appears not to exist: " << current_mtl->texture_filename << "; texture path: " <<this->TexturePath<<"\n"); } } } else { // just skip it; got an unsupported feature or a comment in file. vtkDebugMacro("Unknown command " << current_token << " in material file " << filename << " at line " << line_number << ":\n\t" << current_line); } } fclose(mtl_file_stream); return listOfMaterials; } void bindTexturedPolydataToRenderWindow( vtkRenderWindow* renderWindow, vtkRenderer* renderer, vtkOBJPolyDataProcessor* reader ) { if( NULL == (renderWindow) ) { vtkErrorWithObjectMacro(reader, "RenderWindow is null, failure!"); return; } if( NULL == (renderer) ) { vtkErrorWithObjectMacro(reader, "Renderer is null, failure!"); return; } if( NULL == (reader) ) { vtkErrorWithObjectMacro(reader, "vtkOBJPolyDataProcessor is null, failure!"); return; } reader->actor_list.clear(); reader->actor_list.reserve( reader->GetNumberOfOutputPorts() ); for( int port_idx=0; port_idx < reader->GetNumberOfOutputPorts(); port_idx++) { vtkPolyData* objPoly = reader->GetOutput(port_idx); vtkSmartPointer<vtkPolyDataMapper> mapper = vtkSmartPointer<vtkPolyDataMapper>::New(); mapper->SetInput(objPoly); vtkDebugWithObjectMacro(reader, "Grabbed objPoly " << objPoly << ", port index " << port_idx << "\n" << "numPolys = " << objPoly->GetNumberOfPolys() << " numPoints = " << objPoly->GetNumberOfPoints()); // For each named material, load and bind the texture, add it to the renderer vtkSmartPointer<vtkTexture> vtk_texture = vtkSmartPointer<vtkTexture>::New(); std::string textureFilename = reader->GetTextureFilename(port_idx); vtkSmartPointer<vtkJPEGReader> tex_jpg_Loader = vtkSmartPointer<vtkJPEGReader>::New(); vtkSmartPointer<vtkPNGReader> tex_png_Loader = vtkSmartPointer<vtkPNGReader>::New(); int bIsReadableJPEG = tex_jpg_Loader->CanReadFile( textureFilename.c_str() ); int bIsReadablePNG = tex_png_Loader->CanReadFile( textureFilename.c_str() ); bool haveTexture = false; if (!textureFilename.empty()) { if( bIsReadableJPEG ) { tex_jpg_Loader->SetFileName( textureFilename.c_str() ); tex_jpg_Loader->Update(); vtk_texture->AddInputConnection( tex_jpg_Loader->GetOutputPort() ); haveTexture = true; } else if( bIsReadablePNG ) { tex_png_Loader->SetFileName( textureFilename.c_str() ); tex_png_Loader->Update(); vtk_texture->AddInputConnection( tex_png_Loader->GetOutputPort() ); haveTexture = true; } else { if(!textureFilename.empty()) // OK to have no texture image, but if its not empty it ought to exist. { vtkErrorWithObjectMacro(reader, "Nonexistent texture image type!? imagefile: " <<textureFilename); } } vtk_texture->InterpolateOff(); // Faster?? (yes clearly faster for largish texture) } vtkSmartPointer<vtkActor> actor = vtkSmartPointer<vtkActor>::New(); actor->SetMapper(mapper); if (haveTexture) { actor->SetTexture(vtk_texture); } vtkSmartPointer<vtkProperty> properties = vtkSmartPointer<vtkProperty>::New(); vtkOBJImportedMaterial* raw_mtl_data = reader->GetMaterial(port_idx); properties->SetDiffuseColor(raw_mtl_data->diff); properties->SetSpecularColor(raw_mtl_data->spec); properties->SetAmbientColor(raw_mtl_data->amb); properties->SetOpacity(raw_mtl_data->trans); properties->SetInterpolationToPhong(); properties->SetLighting(true); properties->SetSpecular( raw_mtl_data->get_spec_coeff() ); properties->SetAmbient( raw_mtl_data->get_amb_coeff() ); properties->SetDiffuse( raw_mtl_data->get_diff_coeff() ); actor->SetProperty(properties); renderer->AddActor(actor); //properties->ShadingOn(); // use ShadingOn() if loading vtkMaterial from xml // available in mtl parser are: // double amb[3]; // double diff[3]; // double spec[3]; // double reflect; // double refract; // double trans; // double shiny; // double glossy; // double refract_index; reader->actor_list.push_back(actor); // keep a handle on actors to animate later } /** post-condition of this function: the renderer has had a bunch of actors added to it */ } vtkOBJImportedMaterial::vtkOBJImportedMaterial() { name[0] = 'x'; name[1] = '\0'; obj_set_material_defaults(this); } <|endoftext|>
<commit_before>// Steer TRD QA train for Reconstruction (Clusterizer, Tracking and PID). // // Usage: // run.C(optList, files, nev, first, runNo, ocdb_uri, grp_uri) // // optList : "ALL" [default] or one/more of the following: // "EFF" : TRD Tracking Efficiency // "EFFC" : TRD Tracking Efficiency Combined (barrel + stand alone) - only in case of simulations // "MULT" : TRD single track selection // "RES" : TRD tracking Resolution // "CLRES": clusters Resolution // "CAL" : TRD calibration // "ALGN" : TRD alignment // "PID" : TRD PID - pion efficiency // "PIDR" : TRD PID - reference data // "V0" : monitor V0 performance for use in TRD PID calibration // "DET" : Basic TRD Detector checks // ****** SPECIAL OPTIONS ********** // "NOFR" : Data set does not have AliESDfriends.root // "NOMC" : Data set does not have Monte Carlo Informations (default have MC), // // files : the list of ESD files to be processed [default AliESds.root from cwd] // nev : number of events to be processed [default all] // first : first event to process [default 0] // runNo : run number [default 0] // ocdb_uri : OCDB location [default local, $ALICE_ROOT]. In case of AliEn the syntax should be of the form // alien://folder=/alice/data/2010/OCDB?user=username?cacheF=yourDirectory?cacheS=yourSize // grp_uri : GRP/GRP/Data location [default cwd]. In case of AliEn the syntax should be of the form // alien://folder=/alice/data/2010/OCDB?user=username?cacheF=yourDirectory?cacheS=yourSize // In compiled mode : // Don't forget to load first the libraries // gSystem->Load("libMemStat.so") // gSystem->Load("libMemStatGui.so") // gSystem->Load("libANALYSIS.so") // gSystem->Load("libANALYSISalice.so") // gSystem->Load("libTENDER.so"); // gSystem->Load("libPWG1.so"); // gSystem->Load("libNetx.so") ; // gSystem->Load("libRAliEn.so"); // // Authors: // Alex Bercuci (A.Bercuci@gsi.de) // Markus Fasel (m.Fasel@gsi.de) #if ! defined (__CINT__) || defined (__MAKECINT__) //#ifndef __CINT__ #include <Riostream.h> #include "TStopwatch.h" #include "TMemStat.h" #include "TMemStatViewerGUI.h" #include "TROOT.h" #include "TClass.h" #include "TSystem.h" #include "TError.h" #include "TChain.h" #include "TGrid.h" #include "TAlienCollection.h" #include "TGridCollection.h" #include "TGridResult.h" #include "TGeoGlobalMagField.h" #include "AliMagF.h" #include "AliTracker.h" #include "AliLog.h" #include "AliCDBManager.h" #include "AliGRPManager.h" #include "AliGeomManager.h" #include "AliAnalysisManager.h" #include "AliAnalysisDataContainer.h" #include "AliMCEventHandler.h" #include "AliESDInputHandler.h" #include "TRD/AliTRDtrackerV1.h" #include "TRD/AliTRDcalibDB.h" #include "PWG1/TRD/macros/AddTRDcheckESD.C" #include "PWG1/TRD/macros/AddTRDinfoGen.C" #include "PWG1/TRD/macros/AddTRDcheckDET.C" #include "PWG1/TRD/macros/AddTRDefficiency.C" #include "PWG1/TRD/macros/AddTRDresolution.C" #include "PWG1/TRD/macros/AddTRDcheckPID.C" #endif Bool_t MEM = kFALSE; TChain* MakeChainLST(const char* filename = NULL); TChain* MakeChainXML(const char* filename = NULL); Bool_t UseMC(Char_t *opt); Bool_t UseFriends(Char_t *opt); void run(Char_t *optList="ALL", const Char_t *files=NULL, Long64_t nev=1234567890, Long64_t first = 0) { TMemStat *mem = NULL; if(MEM){ if(gSystem->Load("libMemStat.so")<0) return; if(gSystem->Load("libMemStatGui.so")<0) return; mem = new TMemStat("new, gnubuildin"); mem->AddStamp("Start"); } TStopwatch timer; timer.Start(); // VERY GENERAL SETTINGS //AliLog::SetGlobalLogLevel(AliLog::kError); if(gSystem->Load("libANALYSIS.so")<0) return; if(gSystem->Load("libANALYSISalice.so")<0) return; if(gSystem->Load("libTENDER.so")<0) return; if(gSystem->Load("libPWG1.so")<0) return; Bool_t fHasMCdata = UseMC(optList); Bool_t fHasFriends = UseFriends(optList); // DEFINE DATA CHAIN TChain *chain = NULL; if(!files) chain = MakeChainLST(); else{ TString fn(files); if(fn.EndsWith("xml")) chain = MakeChainXML(files); else chain = MakeChainLST(files); } if(!chain) return; chain->Lookup(); chain->GetListOfFiles()->Print(); Int_t nfound=(Int_t)chain->GetEntries(); printf("\tENTRIES FOUND [%d] REQUESTED [%d]\n", nfound, nev>nfound?nfound:nev); // BUILD ANALYSIS MANAGER AliAnalysisManager *mgr = new AliAnalysisManager("TRD Reconstruction Performance & Calibration"); AliESDInputHandlerRP *esdH(NULL); mgr->SetInputEventHandler(esdH = new AliESDInputHandlerRP); if(fHasFriends){ esdH->SetReadFriends(kTRUE); esdH->SetActiveBranches("ESDfriend"); } AliMCEventHandler *mcH(NULL); if(fHasMCdata) mgr->SetMCtruthEventHandler(mcH = new AliMCEventHandler()); //mgr->SetDebugLevel(10); mgr->SetSkipTerminate(kTRUE); gROOT->LoadMacro("$ALICE_ROOT/PWG1/macros/AddTrainPerformanceTRD.C"); if(!AddTrainPerformanceTRD(optList)) { Error("run.C", "Error loading TRD train."); return; } if (!mgr->InitAnalysis()) return; // verbosity printf("\tRUNNING TRAIN FOR TASKS:\n"); TObjArray *taskList=mgr->GetTasks(); for(Int_t itask=0; itask<taskList->GetEntries(); itask++){ AliAnalysisTask *task=(AliAnalysisTask*)taskList->At(itask); printf(" %s [%s]\n", task->GetName(), task->GetTitle()); } //mgr->PrintStatus(); mgr->StartAnalysis("local", chain, nev, first); timer.Stop(); timer.Print(); // verbosity printf("\tCLEANING TASK LIST:\n"); mgr->GetTasks()->Delete(); if(mcH) delete mcH; delete esdH; delete chain; if(MEM) delete mem; if(MEM) TMemStatViewerGUI::ShowGUI(); } //____________________________________________ TChain* MakeChainLST(const char* filename) { // Create the chain TChain* chain = new TChain("esdTree"); if(!filename){ chain->Add(Form("%s/AliESDs.root", gSystem->pwd())); return chain; } // read ESD files from the input list. ifstream in; in.open(filename); TString esdfile; while(in.good()) { in >> esdfile; if (!esdfile.Contains("root")) continue; // protection chain->Add(esdfile.Data()); } in.close(); return chain; } //____________________________________________ TChain* MakeChainXML(const char* xmlfile) { if (!TFile::Open(xmlfile)) { Error("MakeChainXML", Form("No file %s was found", xmlfile)); return NULL; } if(gSystem->Load("libNetx.so")<0) return NULL; if(gSystem->Load("libRAliEn.so")<0) return NULL; TGrid::Connect("alien://") ; TGridCollection *collection = (TGridCollection*) TAlienCollection::Open(xmlfile); if (!collection) { Error("MakeChainXML", Form("No collection found in %s", xmlfile)) ; return NULL; } //collection->CheckIfOnline(); TGridResult* result = collection->GetGridResult("",0 ,0); if(!result->GetEntries()){ Error("MakeChainXML", Form("No entries found in %s", xmlfile)) ; return NULL; } // Makes the ESD chain TChain* chain = new TChain("esdTree"); for (Int_t idx = 0; idx < result->GetEntries(); idx++) { chain->Add(result->GetKey(idx, "turl")); } return chain; } //______________________________________________________ Bool_t UseMC(Char_t *opt){ return !(Bool_t)strstr(opt, "NOMC"); } //____________________________________________ Bool_t UseFriends(Char_t *opt){ return !(Bool_t)strstr(opt, "NOFR"); } <commit_msg>using AliCDBConnect task in test train of TRD<commit_after>// Steer TRD QA train for Reconstruction (Clusterizer, Tracking and PID). // // Usage: // run.C(optList, files, nev, first, runNo, ocdb_uri, grp_uri) // // optList : "ALL" [default] or one/more of the following: // "EFF" : TRD Tracking Efficiency // "EFFC" : TRD Tracking Efficiency Combined (barrel + stand alone) - only in case of simulations // "MULT" : TRD single track selection // "RES" : TRD tracking Resolution // "CLRES": clusters Resolution // "CAL" : TRD calibration // "ALGN" : TRD alignment // "PID" : TRD PID - pion efficiency // "PIDR" : TRD PID - reference data // "V0" : monitor V0 performance for use in TRD PID calibration // "DET" : Basic TRD Detector checks // ****** SPECIAL OPTIONS ********** // "NOFR" : Data set does not have AliESDfriends.root // "NOMC" : Data set does not have Monte Carlo Informations (default have MC), // // files : the list of ESD files to be processed [default AliESds.root from cwd] // nev : number of events to be processed [default all] // first : first event to process [default 0] // runNo : run number [default 0] // ocdb_uri : OCDB location [default local, $ALICE_ROOT]. In case of AliEn the syntax should be of the form // alien://folder=/alice/data/2010/OCDB?user=username?cacheF=yourDirectory?cacheS=yourSize // grp_uri : GRP/GRP/Data location [default cwd]. In case of AliEn the syntax should be of the form // alien://folder=/alice/data/2010/OCDB?user=username?cacheF=yourDirectory?cacheS=yourSize // In compiled mode : // Don't forget to load first the libraries // gSystem->Load("libMemStat.so") // gSystem->Load("libMemStatGui.so") // gSystem->Load("libANALYSIS.so") // gSystem->Load("libANALYSISalice.so") // gSystem->Load("libTENDER.so"); // gSystem->Load("libPWG1.so"); // gSystem->Load("libNetx.so") ; // gSystem->Load("libRAliEn.so"); // // Authors: // Alex Bercuci (A.Bercuci@gsi.de) // Markus Fasel (m.Fasel@gsi.de) #if ! defined (__CINT__) || defined (__MAKECINT__) //#ifndef __CINT__ #include <Riostream.h> #include "TStopwatch.h" #include "TMemStat.h" #include "TMemStatViewerGUI.h" #include "TROOT.h" #include "TClass.h" #include "TSystem.h" #include "TError.h" #include "TChain.h" #include "TGrid.h" #include "TAlienCollection.h" #include "TGridCollection.h" #include "TGridResult.h" #include "TGeoGlobalMagField.h" #include "AliMagF.h" #include "AliTracker.h" #include "AliLog.h" #include "AliCDBManager.h" #include "AliGRPManager.h" #include "AliGeomManager.h" #include "AliAnalysisManager.h" #include "AliAnalysisDataContainer.h" #include "AliMCEventHandler.h" #include "AliESDInputHandler.h" #include "TRD/AliTRDtrackerV1.h" #include "TRD/AliTRDcalibDB.h" #include "PWG1/TRD/macros/AddTRDcheckESD.C" #include "PWG1/TRD/macros/AddTRDinfoGen.C" #include "PWG1/TRD/macros/AddTRDcheckDET.C" #include "PWG1/TRD/macros/AddTRDefficiency.C" #include "PWG1/TRD/macros/AddTRDresolution.C" #include "PWG1/TRD/macros/AddTRDcheckPID.C" #endif Bool_t MEM = kFALSE; TChain* MakeChainLST(const char* filename = NULL); TChain* MakeChainXML(const char* filename = NULL); Bool_t UseMC(Char_t *opt); Bool_t UseFriends(Char_t *opt); void run(Char_t *optList="ALL", Int_t run, const Char_t *files=NULL, Long64_t nev=1234567890, Long64_t first = 0) { TMemStat *mem = NULL; if(MEM){ if(gSystem->Load("libMemStat.so")<0) return; if(gSystem->Load("libMemStatGui.so")<0) return; mem = new TMemStat("new, gnubuildin"); mem->AddStamp("Start"); } TStopwatch timer; timer.Start(); // VERY GENERAL SETTINGS //AliLog::SetGlobalLogLevel(AliLog::kError); if(gSystem->Load("libANALYSIS.so")<0) return; if(gSystem->Load("libANALYSISalice.so")<0) return; if(gSystem->Load("libTENDER.so")<0) return; if(gSystem->Load("libPWG1.so")<0) return; Bool_t fHasMCdata = UseMC(optList); Bool_t fHasFriends = UseFriends(optList); // DEFINE DATA CHAIN TChain *chain = NULL; if(!files) chain = MakeChainLST(); else{ TString fn(files); if(fn.EndsWith("xml")) chain = MakeChainXML(files); else chain = MakeChainLST(files); } if(!chain) return; chain->Lookup(); chain->GetListOfFiles()->Print(); Int_t nfound=(Int_t)chain->GetEntries(); printf("\tENTRIES FOUND [%d] REQUESTED [%d]\n", nfound, nev>nfound?nfound:nev); // BUILD ANALYSIS MANAGER AliAnalysisManager *mgr = new AliAnalysisManager("TRD Reconstruction Performance & Calibration"); AliESDInputHandlerRP *esdH(NULL); mgr->SetInputEventHandler(esdH = new AliESDInputHandlerRP); if(fHasFriends){ esdH->SetReadFriends(kTRUE); esdH->SetActiveBranches("ESDfriend"); } AliMCEventHandler *mcH(NULL); if(fHasMCdata) mgr->SetMCtruthEventHandler(mcH = new AliMCEventHandler()); //mgr->SetDebugLevel(10); mgr->SetSkipTerminate(kTRUE); // add CDB task gROOT->LoadMacro("$ALICE_ROOT/PWG1/PilotTrain/AddTaskCDBconnect.C"); AliTaskCDBconnect *taskCDB = AddTaskCDBconnect(); if (!taskCDB) return; taskCDB->SetRunNumber(run); gROOT->LoadMacro("$ALICE_ROOT/PWG1/macros/AddTrainPerformanceTRD.C"); if(!AddTrainPerformanceTRD(optList)) { Error("run.C", "Error loading TRD train."); return; } if (!mgr->InitAnalysis()) return; // verbosity printf("\tRUNNING TRAIN FOR TASKS:\n"); TObjArray *taskList=mgr->GetTasks(); for(Int_t itask=0; itask<taskList->GetEntries(); itask++){ AliAnalysisTask *task=(AliAnalysisTask*)taskList->At(itask); printf(" %s [%s]\n", task->GetName(), task->GetTitle()); } //mgr->PrintStatus(); mgr->StartAnalysis("local", chain, nev, first); timer.Stop(); timer.Print(); // verbosity printf("\tCLEANING TASK LIST:\n"); mgr->GetTasks()->Delete(); if(mcH) delete mcH; delete esdH; delete chain; if(MEM) delete mem; if(MEM) TMemStatViewerGUI::ShowGUI(); } //____________________________________________ TChain* MakeChainLST(const char* filename) { // Create the chain TChain* chain = new TChain("esdTree"); if(!filename){ chain->Add(Form("%s/AliESDs.root", gSystem->pwd())); return chain; } // read ESD files from the input list. ifstream in; in.open(filename); TString esdfile; while(in.good()) { in >> esdfile; if (!esdfile.Contains("root")) continue; // protection chain->Add(esdfile.Data()); } in.close(); return chain; } //____________________________________________ TChain* MakeChainXML(const char* xmlfile) { if (!TFile::Open(xmlfile)) { Error("MakeChainXML", Form("No file %s was found", xmlfile)); return NULL; } if(gSystem->Load("libNetx.so")<0) return NULL; if(gSystem->Load("libRAliEn.so")<0) return NULL; TGrid::Connect("alien://") ; TGridCollection *collection = (TGridCollection*) TAlienCollection::Open(xmlfile); if (!collection) { Error("MakeChainXML", Form("No collection found in %s", xmlfile)) ; return NULL; } //collection->CheckIfOnline(); TGridResult* result = collection->GetGridResult("",0 ,0); if(!result->GetEntries()){ Error("MakeChainXML", Form("No entries found in %s", xmlfile)) ; return NULL; } // Makes the ESD chain TChain* chain = new TChain("esdTree"); for (Int_t idx = 0; idx < result->GetEntries(); idx++) { chain->Add(result->GetKey(idx, "turl")); } return chain; } //______________________________________________________ Bool_t UseMC(Char_t *opt){ return !(Bool_t)strstr(opt, "NOMC"); } //____________________________________________ Bool_t UseFriends(Char_t *opt){ return !(Bool_t)strstr(opt, "NOFR"); } <|endoftext|>
<commit_before>#include "Lua.h" #include "Common/Common.h" #include <sstream> #include <assert.h> namespace Lua { //----------------------------------------------------------------------------------------- // Class: State // Lua state wrapper // // Creates a new state State::State() { // Create a new Lua state this->L = luaL_newstate(); // Check if an error occured if (!this->L) throw std::exception("can't create new lua state."); // Load the Lua libraries into the state luaL_openlibs(this->L); } // Destroys the state State::~State() { // Destroy the Lua state lua_close(this->L); } void State::DoFile(const char* file) { if (luaL_dofile(this->L, file)) { std::string error = lua_tostring(this->L, -1); lua_pop(this->L, 1); throw std::exception(error.c_str()); } } // Loads and runs a string void State::DoString(const char* str) { if (luaL_dostring(this->L, str)) { std::string error = lua_tostring(this->L, -1); lua_pop(this->L, 1); throw std::exception(error.c_str()); } } std::unique_ptr<MObjTable> State::peek_table(int indx) { std::unique_ptr<MObjTable> table(new MObjTable()); lua_pushnil(L); // so we get first key while(lua_next(L, indx - 1)) { auto value = pop(); auto key = peek(); table->insert(std::pair<MObject::unique_ptr, MObject::unique_ptr> (std::move(key->release_object()), std::move(value->release_object()))); } return table; } std::unique_ptr<LuaObject> State::peek(int indx) { std::unique_ptr<LuaObject> object; LuaType type = (LuaType)lua_type(L, indx); switch (type) { case Type_Boolean: { bool value = lua_toboolean(L, indx) == 1; object.reset(new LuaObject(value)); } break; case Type_Number: { double value = lua_tonumber(L, indx); object.reset(new LuaObject(value)); } break; case Type_String: { const char* value = lua_tostring(L, indx); object.reset(new LuaObject(value)); } break; case Type_Table: { object.reset(new LuaObject(peek_table(indx))); } break; case Type_Nil: { object.reset(new LuaObject()); } break; default: { lua_pushvalue(L, indx); // luaL_ref pops so copy it int ref = luaL_ref(L, LUA_REGISTRYINDEX); // this pops // can't handle the value so store its ref object.reset(new UnhandledObject(*this, ref, type)); } break; } return std::move(object); } std::unique_ptr<LuaObject> State::pop() { std::unique_ptr<LuaObject> object = peek(); lua_pop(L, 1); return object; } void State::push(const MObject& object) { switch (object.GetType()) { case Common::TYPE_BOOL: { const MObjBool& b = static_cast<const MObjBool&>(object); lua_pushboolean(L, b.GetValue()); } break; case Common::TYPE_NUMBER: { const MObjNumber& n = static_cast<const MObjNumber&>(object); lua_pushnumber(L, n.GetValue()); } break; case Common::TYPE_STRING: { const MObjString& s = static_cast<const MObjString&>(object); lua_pushstring(L, s.GetValue()); } break; case Common::TYPE_TABLE: { const MObjTable& table = static_cast<const MObjTable&>(object); lua_createtable(L, table.size(), table.size()); for (auto itr = table.begin(); itr != table.end(); ++itr) { push(*itr->first.get());//key push(*itr->second.get());//value lua_settable(L, -3); } } break; case Common::TYPE_NIL: default: { lua_pushnil(L); } break; } } // Create a new named function void State::RegisterFunction(const Manager::ScriptCallback* cb) { std::unique_ptr<CFunction> function(new CFunction(*this, cb)); set_global(cb->name, *function); registeredFunctions.push_back(std::move(function)); } void State::set_global(const char* name, LuaObject& obj) { obj.push(*this); lua_setglobal(L, name); } std::unique_ptr<LuaObject> State::get_global(const char* name) { lua_getglobal(L, name); return pop(); } // Checks if the specified Lua function is defined in the script bool State::HasFunction(const char* name) { return get_global(name)->get_type() == Type_Function; } // Calls a Lua function from C MObject::unique_deque State::Call(const char* name, const MObject::unique_list& args, int timeout) { auto func = get_global(name); if (func->get_type() != Type_Function) throw std::exception("lua: Attempted function call on non-function entity."); func->push(*this); // Push the arguments on the stack for (auto itr = args.begin(); itr != args.end(); ++itr) push(**itr); // Call the Lua function if (lua_pcall_t(L, args.size(), LUA_MULTRET, 0, timeout)) { std::string error = lua_tostring(L, -1); lua_pop(L, -1); throw std::exception(error.c_str()); } MObject::unique_deque results; // Pop the results off the stack int n = lua_gettop(L); for (int i = 0; i < n; i++) { if (lua_type(L, i) == Type_Nil) continue; results.push_front(pop()->release_object()); } return results; } // Calls a function // Caller is responsible for memory management of return vector MObject::unique_deque State::Call(const char* name, int timeout) { static const MObject::unique_list args; return this->Call(name, args, timeout); } // ------------------------------------------------------------------- // Used by CFunction for invoking C functions. class LuaCallHandler : public Manager::CallHandler { private: int cur_arg; Lua::State& luaState; protected: void __NO_RET RaiseError(const std::string& err) override { lua_State* L = luaState.GetState(); return (void)luaL_error(L, err.c_str()); } // Get the next argument for the function, if it's not of the // expected type an error should be described and raised through // RaiseError. std::unique_ptr<MObject> GetArgument(Common::obj_type expected) override { lua_State* L = luaState.GetState(); int indx_from_top = (-1 * lua_gettop(L)) + cur_arg; int indx = ++cur_arg; std::unique_ptr<MObject> obj; switch (expected) { case Common::TYPE_BOOL: { int b; // phasor_legacy: this "fix" is specific to Phasor // old versions accepted 0 as boolean false but Lua treats // it as boolean true. if (lua_type(L, indx) == Type_Number && lua_tonumber(L, indx) == 0) b = 0; else b = lua_toboolean(L, indx); obj.reset(new MObjBool(b != 0)); } break; case Common::TYPE_NUMBER: { // if it can't be converted luaL_checknumber raises an error lua_Number n = luaL_checknumber(L, indx); obj.reset(new MObjNumber(n)); } break; case Common::TYPE_STRING: { // checkstring converts stack value and raises an error // if no conversion exists luaL_checkstring(L, indx); obj.reset(new MObjString(lua_tostring(L, indx))); } break; case Common::TYPE_TABLE: { if (lua_type(L, indx) != Type_Table) { std::stringstream ss; ss << "bad argument #" << cur_arg << " to '" << cb->name << "' (table expected, got " << lua_typename(L, indx) << ")"; RaiseError(ss.str()); } obj.reset(luaState.peek_table(indx_from_top).release()); } break; case Common::TYPE_ANY: { obj = luaState.peek(indx_from_top)->release_object(); } break; } return obj; } public: LuaCallHandler(State& state, const Manager::ScriptCallback* cb, int nargs) : CallHandler(state, cb, nargs), cur_arg(0), luaState(state) { } }; // -------------------------------------------------------------------- // LuaObject::LuaObject() : type(Type_Nil), object(new MObject()) { } LuaObject::LuaObject(bool value) : type(Type_Boolean), object(new MObjBool(value)) { } LuaObject::LuaObject(double value) : type(Type_Number), object(new MObjNumber(value)) { } LuaObject::LuaObject(const std::string& value) : type(Type_String), object(new MObjString(value)) { } LuaObject::LuaObject(const char* value) : type(Type_String), object(new MObjString(value)) { } LuaObject::LuaObject(LuaType type) : type(type), object(new MObject()) { } LuaObject::LuaObject(std::unique_ptr<MObjTable> table) : type(Type_Table), object(std::move(table)) { } LuaObject::~LuaObject() {} void LuaObject::push(State& state) { return state.push(*object); } std::unique_ptr<MObject> LuaObject::release_object() { return std::move(object); } // -------------------------------------------------------------------- // UnhandledObject::UnhandledObject(State& state, int ref, LuaType type) : LuaObject(type), state(state), ref(ref) { } UnhandledObject::~UnhandledObject() { luaL_unref(state.GetState(), LUA_REGISTRYINDEX, ref); } void UnhandledObject::push(State& state) { if (&state != &this->state) throw std::logic_error("each UnhandledObject can only be bound to one state."); lua_rawgeti(state.GetState(), LUA_REGISTRYINDEX, ref); } // -------------------------------------------------------------------- // CFunction::CFunction(State& state, const Manager::ScriptCallback* cb) : LuaObject(Type_Function), state(state), cb(cb) { } void CFunction::push(State& state) { if (&state != &this->state) throw std::logic_error("each CFunction can only be bound to one state."); lua_State* L = state.GetState(); lua_pushlightuserdata(L, (void*)this); lua_pushcclosure(L, CFunction::LuaCall, 1); } int CFunction::LuaCall(lua_State* L) { // Get the CFunction class from upvalue CFunction* function = (CFunction*)lua_touserdata(L, lua_upvalueindex(1)); int nargs = lua_gettop(L); // number of args received LuaCallHandler call(function->state, function->cb, nargs); // build the argument list + call the func MObject::unique_list results = call.Call(); lua_pop(L, nargs); // done with args now // Push the results on the stack for (auto itr = results.begin(); itr != results.end(); ++itr) function->state.push(*(*itr)); int nresults = results.size(); return nresults; } }<commit_msg>fixed #11 and actually fixed #3<commit_after>#include "Lua.h" #include "Common/Common.h" #include <sstream> #include <assert.h> namespace Lua { //----------------------------------------------------------------------------------------- // Class: State // Lua state wrapper // // Creates a new state State::State() { // Create a new Lua state this->L = luaL_newstate(); // Check if an error occured if (!this->L) throw std::exception("can't create new lua state."); // Load the Lua libraries into the state luaL_openlibs(this->L); } // Destroys the state State::~State() { // Destroy the Lua state lua_close(this->L); } void State::DoFile(const char* file) { if (luaL_dofile(this->L, file)) { std::string error = lua_tostring(this->L, -1); lua_pop(this->L, 1); throw std::exception(error.c_str()); } } // Loads and runs a string void State::DoString(const char* str) { if (luaL_dostring(this->L, str)) { std::string error = lua_tostring(this->L, -1); lua_pop(this->L, 1); throw std::exception(error.c_str()); } } std::unique_ptr<MObjTable> State::peek_table(int indx) { std::unique_ptr<MObjTable> table(new MObjTable()); lua_pushnil(L); // so we get first key while(lua_next(L, indx - 1)) { auto value = pop(); auto key = peek(); table->insert(std::pair<MObject::unique_ptr, MObject::unique_ptr> (std::move(key->release_object()), std::move(value->release_object()))); } return table; } std::unique_ptr<LuaObject> State::peek(int indx) { std::unique_ptr<LuaObject> object; LuaType type = (LuaType)lua_type(L, indx); switch (type) { case Type_Boolean: { bool value = lua_toboolean(L, indx) == 1; object.reset(new LuaObject(value)); } break; case Type_Number: { double value = lua_tonumber(L, indx); object.reset(new LuaObject(value)); } break; case Type_String: { const char* value = lua_tostring(L, indx); object.reset(new LuaObject(value)); } break; case Type_Table: { object.reset(new LuaObject(peek_table(indx))); } break; case Type_Nil: { object.reset(new LuaObject()); } break; default: { lua_pushvalue(L, indx); // luaL_ref pops so copy it int ref = luaL_ref(L, LUA_REGISTRYINDEX); // this pops // can't handle the value so store its ref object.reset(new UnhandledObject(*this, ref, type)); } break; } return std::move(object); } std::unique_ptr<LuaObject> State::pop() { std::unique_ptr<LuaObject> object = peek(); lua_pop(L, 1); return object; } void State::push(const MObject& object) { switch (object.GetType()) { case Common::TYPE_BOOL: { const MObjBool& b = static_cast<const MObjBool&>(object); lua_pushboolean(L, b.GetValue()); } break; case Common::TYPE_NUMBER: { const MObjNumber& n = static_cast<const MObjNumber&>(object); lua_pushnumber(L, n.GetValue()); } break; case Common::TYPE_STRING: { const MObjString& s = static_cast<const MObjString&>(object); lua_pushstring(L, s.GetValue()); } break; case Common::TYPE_TABLE: { const MObjTable& table = static_cast<const MObjTable&>(object); lua_createtable(L, table.size(), table.size()); for (auto itr = table.begin(); itr != table.end(); ++itr) { push(*itr->first.get());//key push(*itr->second.get());//value lua_settable(L, -3); } } break; case Common::TYPE_NIL: default: { lua_pushnil(L); } break; } } // Create a new named function void State::RegisterFunction(const Manager::ScriptCallback* cb) { std::unique_ptr<CFunction> function(new CFunction(*this, cb)); set_global(cb->name, *function); registeredFunctions.push_back(std::move(function)); } void State::set_global(const char* name, LuaObject& obj) { obj.push(*this); lua_setglobal(L, name); } std::unique_ptr<LuaObject> State::get_global(const char* name) { lua_getglobal(L, name); return pop(); } // Checks if the specified Lua function is defined in the script bool State::HasFunction(const char* name) { return get_global(name)->get_type() == Type_Function; } // Calls a Lua function from C MObject::unique_deque State::Call(const char* name, const MObject::unique_list& args, int timeout) { auto func = get_global(name); if (func->get_type() != Type_Function) throw std::exception("lua: Attempted function call on non-function entity."); func->push(*this); // Push the arguments on the stack for (auto itr = args.begin(); itr != args.end(); ++itr) push(**itr); // Call the Lua function if (lua_pcall_t(L, args.size(), LUA_MULTRET, 0, timeout)) { std::string error = lua_tostring(L, -1); lua_pop(L, -1); throw std::exception(error.c_str()); } MObject::unique_deque results; // Pop the results off the stack int n = lua_gettop(L); for (int i = 0, indx = -1; i < n; i++, indx--) { if (lua_type(L, indx) == Type_Nil) continue; results.push_front(pop()->release_object()); } return results; } // Calls a function // Caller is responsible for memory management of return vector MObject::unique_deque State::Call(const char* name, int timeout) { static const MObject::unique_list args; return this->Call(name, args, timeout); } // ------------------------------------------------------------------- // Used by CFunction for invoking C functions. class LuaCallHandler : public Manager::CallHandler { private: int cur_arg; Lua::State& luaState; protected: void __NO_RET RaiseError(const std::string& err) override { lua_State* L = luaState.GetState(); return (void)luaL_error(L, err.c_str()); } // Get the next argument for the function, if it's not of the // expected type an error should be described and raised through // RaiseError. std::unique_ptr<MObject> GetArgument(Common::obj_type expected) override { lua_State* L = luaState.GetState(); int indx_from_top = (-1 * lua_gettop(L)) + cur_arg; int indx = ++cur_arg; std::unique_ptr<MObject> obj; switch (expected) { case Common::TYPE_BOOL: { int b; // phasor_legacy: this "fix" is specific to Phasor // old versions accepted 0 as boolean false but Lua treats // it as boolean true. if (lua_type(L, indx) == Type_Number && lua_tonumber(L, indx) == 0) b = 0; else b = lua_toboolean(L, indx); obj.reset(new MObjBool(b != 0)); } break; case Common::TYPE_NUMBER: { // if it can't be converted luaL_checknumber raises an error lua_Number n = luaL_checknumber(L, indx); obj.reset(new MObjNumber(n)); } break; case Common::TYPE_STRING: { // checkstring converts stack value and raises an error // if no conversion exists luaL_checkstring(L, indx); obj.reset(new MObjString(lua_tostring(L, indx))); } break; case Common::TYPE_TABLE: { if (lua_type(L, indx) != Type_Table) { std::stringstream ss; ss << "bad argument #" << cur_arg << " to '" << cb->name << "' (table expected, got " << lua_typename(L, indx) << ")"; RaiseError(ss.str()); } obj.reset(luaState.peek_table(indx_from_top).release()); } break; case Common::TYPE_ANY: { obj = luaState.peek(indx_from_top)->release_object(); } break; } return obj; } public: LuaCallHandler(State& state, const Manager::ScriptCallback* cb, int nargs) : CallHandler(state, cb, nargs), cur_arg(0), luaState(state) { } }; // -------------------------------------------------------------------- // LuaObject::LuaObject() : type(Type_Nil), object(new MObject()) { } LuaObject::LuaObject(bool value) : type(Type_Boolean), object(new MObjBool(value)) { } LuaObject::LuaObject(double value) : type(Type_Number), object(new MObjNumber(value)) { } LuaObject::LuaObject(const std::string& value) : type(Type_String), object(new MObjString(value)) { } LuaObject::LuaObject(const char* value) : type(Type_String), object(new MObjString(value)) { } LuaObject::LuaObject(LuaType type) : type(type), object(new MObject()) { } LuaObject::LuaObject(std::unique_ptr<MObjTable> table) : type(Type_Table), object(std::move(table)) { } LuaObject::~LuaObject() {} void LuaObject::push(State& state) { return state.push(*object); } std::unique_ptr<MObject> LuaObject::release_object() { return std::move(object); } // -------------------------------------------------------------------- // UnhandledObject::UnhandledObject(State& state, int ref, LuaType type) : LuaObject(type), state(state), ref(ref) { } UnhandledObject::~UnhandledObject() { luaL_unref(state.GetState(), LUA_REGISTRYINDEX, ref); } void UnhandledObject::push(State& state) { if (&state != &this->state) throw std::logic_error("each UnhandledObject can only be bound to one state."); lua_rawgeti(state.GetState(), LUA_REGISTRYINDEX, ref); } // -------------------------------------------------------------------- // CFunction::CFunction(State& state, const Manager::ScriptCallback* cb) : LuaObject(Type_Function), state(state), cb(cb) { } void CFunction::push(State& state) { if (&state != &this->state) throw std::logic_error("each CFunction can only be bound to one state."); lua_State* L = state.GetState(); lua_pushlightuserdata(L, (void*)this); lua_pushcclosure(L, CFunction::LuaCall, 1); } int CFunction::LuaCall(lua_State* L) { // Get the CFunction class from upvalue CFunction* function = (CFunction*)lua_touserdata(L, lua_upvalueindex(1)); int nargs = lua_gettop(L); // number of args received LuaCallHandler call(function->state, function->cb, nargs); // build the argument list + call the func MObject::unique_list results = call.Call(); lua_pop(L, nargs); // done with args now // Push the results on the stack for (auto itr = results.begin(); itr != results.end(); ++itr) function->state.push(*(*itr)); int nresults = results.size(); return nresults; } }<|endoftext|>
<commit_before>// Convert folder with binary data to cpp data #include <stdio.h> #include <string> #include <algorithm> #include <direct.h> #include <vector> #include <limits.h> #include <stdlib.h> #include <assert.h> #include "tinydir.h" #include "lz4.h" void ReplaceAll(std::string& str, const std::string& from, const std::string& to) { if (from.empty()) return; size_t start_pos = 0; while ((start_pos = str.find(from, start_pos)) != std::string::npos) { str.replace(start_pos, from.length(), to); start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx' } } std::vector<std::string> split(const std::string& s, char seperator) { std::vector<std::string> output; std::string::size_type prev_pos = 0, pos = 0; while ((pos = s.find(seperator, pos)) != std::string::npos) { std::string substring(s.substr(prev_pos, pos - prev_pos)); output.push_back(substring); prev_pos = ++pos; } output.push_back(s.substr(prev_pos, pos - prev_pos)); // Last word return output; } void PrintRow(FILE* dst, const unsigned char* buf, unsigned count) { fprintf(dst, "\n "); while (count > 1) { fprintf(dst, "0x%02X,", *buf); ++buf; --count; } if (count > 0) fprintf(dst, "0x%02X", *buf); } void ExportFile(const char* pName, const char* pInputFilename, const char* pOutputFilename, const char* pRelativePath, bool bCompress) { printf("Converting file %s\n", pInputFilename); FILE* pOriginFile = fopen(pInputFilename, "rb"); assert(NULL != pOriginFile); unsigned int iOriginSize; unsigned int iCompressedSize = 0; fseek(pOriginFile, 0, SEEK_END); iOriginSize = (unsigned int)ftell(pOriginFile); fseek(pOriginFile, 0, SEEK_SET); char* pData = (char*)malloc(iOriginSize); fread(pData, 1, iOriginSize, pOriginFile); fclose(pOriginFile); if (iOriginSize == 0) { free(pData); return; } if (bCompress) { int iCompressBound = LZ4_compressBound(iOriginSize); if (iCompressBound > 0) { char* pCompressed = (char*)malloc(iCompressBound); iCompressedSize = LZ4_compress_default(pData, pCompressed, iOriginSize, iCompressBound); if (iCompressedSize >= iOriginSize) { printf("Useless compression for this file\n"); free(pCompressed); bCompress = false; } else { free(pData); pData = pCompressed; } } } std::string sHeaderFilename = pOutputFilename + std::string(".h"); std::string sSourceFilename = pOutputFilename + std::string(".cpp"); ReplaceAll(sHeaderFilename, "/", "\\"); ReplaceAll(sSourceFilename, "/", "\\"); FILE* pHeaderFile = fopen(sHeaderFilename.c_str(), "w+"); FILE* pSourceFile = fopen(sSourceFilename.c_str(), "w+"); assert(NULL != pHeaderFile); assert(NULL != pSourceFile); std::string sRelativePath = "Resources"; if (NULL != pRelativePath) { sRelativePath += "/"; sRelativePath += pRelativePath; } std::vector<std::string> oNamespaces = split(sRelativePath, '/'); int iIndent = oNamespaces.size(); std::string sIndent(iIndent, '\t'); std::string sIndentP(iIndent + 1, '\t'); std::string sIndentPP(iIndent + 2, '\t'); std::string sName = pName; ReplaceAll(sName, ".", "_"); ReplaceAll(sName, " ", "_"); std::string sDefine = "__RESOURCES_"; if (NULL != pRelativePath) { sDefine += pRelativePath; sDefine += "_"; } sDefine += sName; sDefine += "_H__"; std::transform(sDefine.begin(), sDefine.end(), sDefine.begin(), ::toupper); ReplaceAll(sDefine, ".", "_"); ReplaceAll(sDefine, " ", "_"); ReplaceAll(sDefine, "/", "_"); fprintf(pHeaderFile, "#ifndef %s\n", sDefine.c_str()); fprintf(pHeaderFile, "#define %s\n\n", sDefine.c_str()); fprintf(pSourceFile, "#include \"%s.h\"\n", sName.c_str()); for (int iNamespace = 0; iNamespace < oNamespaces.size(); ++iNamespace) { std::string sNamespace = oNamespaces[iNamespace]; ReplaceAll(sDefine, ".", "_"); ReplaceAll(sDefine, " ", "_"); std::string sNamespaceIndent(iNamespace, '\t'); fprintf(pHeaderFile, "%snamespace %s \n%s{\n", sNamespaceIndent.c_str(), sNamespace.c_str(), sNamespaceIndent.c_str()); fprintf(pSourceFile, "%snamespace %s \n%s{\n", sNamespaceIndent.c_str(), sNamespace.c_str(), sNamespaceIndent.c_str()); } fprintf(pHeaderFile, "%snamespace %s \n%s{\n", sIndent.c_str(), sName.c_str(), sIndent.c_str()); fprintf(pSourceFile, "%snamespace %s \n%s{\n", sIndent.c_str(), sName.c_str(), sIndent.c_str()); if (bCompress) { fprintf(pSourceFile, "%s// Compressed with LZ4_compress_default\n", sIndentP.c_str()); fprintf(pHeaderFile, "%s extern const unsigned int Size;\n", sIndentP.c_str()); fprintf(pHeaderFile, "%s extern const unsigned int CompressedSize;\n", sIndentP.c_str()); fprintf(pHeaderFile, "%s extern const char CompressedData[];\n", sIndentP.c_str()); fprintf(pSourceFile, "%sconst unsigned int Size = %d;\n", sIndentP.c_str(), iOriginSize); fprintf(pSourceFile, "%sconst unsigned int CompressedSize = %d;\n", sIndentP.c_str(), iCompressedSize); fprintf(pSourceFile, "%sconst char CompressedData[] = {", sIndentP.c_str()); } else { fprintf(pHeaderFile, "%s extern const unsigned int Size;\n", sIndentP.c_str()); fprintf(pHeaderFile, "%s extern const char Data[];\n", sIndentP.c_str()); fprintf(pSourceFile, "%sconst unsigned int Size = %d;\n", sIndentP.c_str(), iOriginSize); fprintf(pSourceFile, "%sconst char Data[] = {", sIndentP.c_str()); } unsigned int iSize = bCompress ? iCompressedSize : iOriginSize; for (int iPos = 0; iPos < iSize; ++iPos) { if (iPos % 16 == 0) { fprintf(pSourceFile, "\n%s", sIndentPP.c_str()); } fprintf(pSourceFile, "0x%02X", (unsigned char)*(pData + iPos)); if (iPos < (iSize - 1)) fprintf(pSourceFile, ","); } fprintf(pSourceFile, "\n%s};\n", sIndentP.c_str()); //Closing namespaces fprintf(pHeaderFile, "%s}\n", sIndent.c_str()); fprintf(pSourceFile, "%s}\n", sIndent.c_str()); for (int iNamespace = oNamespaces.size()-1; iNamespace >= 0; --iNamespace) { std::string sNamespaceIndent(iNamespace, '\t'); fprintf(pHeaderFile, "%s}\n", sNamespaceIndent.c_str()); fprintf(pSourceFile, "%s}\n", sNamespaceIndent.c_str()); } fprintf(pHeaderFile, "#endif // %s", sDefine.c_str()); fclose(pHeaderFile); fclose(pSourceFile); free(pData); } void ScanFolder(const char* pInputFolder, const char* pOutputFolderBase, const char* pOutputRelative, bool bCompress) { printf("Scanning folder %s\n", pInputFolder); std::string sFolder = pOutputFolderBase; if (NULL != pOutputRelative) { sFolder += "/"; sFolder += pOutputRelative; } mkdir(sFolder.c_str()); tinydir_dir dir; tinydir_open(&dir, pInputFolder); while (dir.has_next) { tinydir_file file; tinydir_readfile(&dir, &file); if (file.is_dir) { if (file.name != std::string(".") && file.name != std::string("..")) { std::string sOutRelative = ""; if (NULL != pOutputRelative) { sOutRelative += pOutputRelative; sOutRelative += "/"; } sOutRelative += file.name; ScanFolder(file.path, pOutputFolderBase, sOutRelative.c_str(), bCompress); } } else { std::string sOutPath = pOutputFolderBase; if (NULL != pOutputRelative) { sOutPath += "/"; sOutPath += pOutputRelative; } sOutPath += "/"; std::string sName = file.name; ReplaceAll(sName, ".", "_"); ReplaceAll(sName, " ", "_"); sOutPath += sName; ExportFile(file.name, file.path, sOutPath.c_str(), pOutputRelative, bCompress); } tinydir_next(&dir); } tinydir_close(&dir); } void main(int argn, char** argv) { const char* pInputFolder = NULL; const char* pOutputFolder = NULL; bool bCompress = false; int iArg = 1; while (iArg < argn) { if (strcmp(argv[iArg], "-c") == 0) { bCompress = true; } else if (pInputFolder == NULL) { pInputFolder = argv[iArg]; } else if (pOutputFolder == NULL) { pOutputFolder = argv[iArg]; } else { //Ignore other arguments } ++iArg; } if (pInputFolder != NULL && pOutputFolder != NULL) { ScanFolder(pInputFolder, pOutputFolder, NULL, bCompress); } else { printf("Usage: ResourceEmbedder <input resource folder> <output cpp folder>\n"); } }<commit_msg>Fix warnings for ResourceEmbedder<commit_after>// Convert folder with binary data to cpp data #include <stdio.h> #include <string> #include <algorithm> #include <direct.h> #include <vector> #include <limits.h> #include <stdlib.h> #include <assert.h> #include "tinydir.h" #include "lz4.h" void ReplaceAll(std::string& str, const std::string& from, const std::string& to) { if (from.empty()) return; size_t start_pos = 0; while ((start_pos = str.find(from, start_pos)) != std::string::npos) { str.replace(start_pos, from.length(), to); start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx' } } std::vector<std::string> split(const std::string& s, char seperator) { std::vector<std::string> output; std::string::size_type prev_pos = 0, pos = 0; while ((pos = s.find(seperator, pos)) != std::string::npos) { std::string substring(s.substr(prev_pos, pos - prev_pos)); output.push_back(substring); prev_pos = ++pos; } output.push_back(s.substr(prev_pos, pos - prev_pos)); // Last word return output; } void PrintRow(FILE* dst, const unsigned char* buf, unsigned count) { fprintf(dst, "\n "); while (count > 1) { fprintf(dst, "0x%02X,", *buf); ++buf; --count; } if (count > 0) fprintf(dst, "0x%02X", *buf); } void ExportFile(const char* pName, const char* pInputFilename, const char* pOutputFilename, const char* pRelativePath, bool bCompress) { printf("Converting file %s\n", pInputFilename); FILE* pOriginFile = fopen(pInputFilename, "rb"); assert(NULL != pOriginFile); unsigned int iOriginSize; unsigned int iCompressedSize = 0; fseek(pOriginFile, 0, SEEK_END); iOriginSize = (unsigned int)ftell(pOriginFile); fseek(pOriginFile, 0, SEEK_SET); char* pData = (char*)malloc(iOriginSize); fread(pData, 1, iOriginSize, pOriginFile); fclose(pOriginFile); if (iOriginSize == 0) { free(pData); return; } if (bCompress) { int iCompressBound = LZ4_compressBound(iOriginSize); if (iCompressBound > 0) { char* pCompressed = (char*)malloc(iCompressBound); iCompressedSize = LZ4_compress_default(pData, pCompressed, iOriginSize, iCompressBound); if (iCompressedSize >= iOriginSize) { printf("Useless compression for this file\n"); free(pCompressed); bCompress = false; } else { free(pData); pData = pCompressed; } } } std::string sHeaderFilename = pOutputFilename + std::string(".h"); std::string sSourceFilename = pOutputFilename + std::string(".cpp"); ReplaceAll(sHeaderFilename, "/", "\\"); ReplaceAll(sSourceFilename, "/", "\\"); FILE* pHeaderFile = fopen(sHeaderFilename.c_str(), "w+"); FILE* pSourceFile = fopen(sSourceFilename.c_str(), "w+"); assert(NULL != pHeaderFile); assert(NULL != pSourceFile); std::string sRelativePath = "Resources"; if (NULL != pRelativePath) { sRelativePath += "/"; sRelativePath += pRelativePath; } std::vector<std::string> oNamespaces = split(sRelativePath, '/'); size_t iIndent = oNamespaces.size(); std::string sIndent(iIndent, '\t'); std::string sIndentP(iIndent + 1, '\t'); std::string sIndentPP(iIndent + 2, '\t'); std::string sName = pName; ReplaceAll(sName, ".", "_"); ReplaceAll(sName, " ", "_"); std::string sDefine = "__RESOURCES_"; if (NULL != pRelativePath) { sDefine += pRelativePath; sDefine += "_"; } sDefine += sName; sDefine += "_H__"; std::transform(sDefine.begin(), sDefine.end(), sDefine.begin(), ::toupper); ReplaceAll(sDefine, ".", "_"); ReplaceAll(sDefine, " ", "_"); ReplaceAll(sDefine, "/", "_"); fprintf(pHeaderFile, "#ifndef %s\n", sDefine.c_str()); fprintf(pHeaderFile, "#define %s\n\n", sDefine.c_str()); fprintf(pSourceFile, "#include \"%s.h\"\n", sName.c_str()); for (int iNamespace = 0; iNamespace < oNamespaces.size(); ++iNamespace) { std::string sNamespace = oNamespaces[iNamespace]; ReplaceAll(sDefine, ".", "_"); ReplaceAll(sDefine, " ", "_"); std::string sNamespaceIndent(iNamespace, '\t'); fprintf(pHeaderFile, "%snamespace %s \n%s{\n", sNamespaceIndent.c_str(), sNamespace.c_str(), sNamespaceIndent.c_str()); fprintf(pSourceFile, "%snamespace %s \n%s{\n", sNamespaceIndent.c_str(), sNamespace.c_str(), sNamespaceIndent.c_str()); } fprintf(pHeaderFile, "%snamespace %s \n%s{\n", sIndent.c_str(), sName.c_str(), sIndent.c_str()); fprintf(pSourceFile, "%snamespace %s \n%s{\n", sIndent.c_str(), sName.c_str(), sIndent.c_str()); if (bCompress) { fprintf(pSourceFile, "%s// Compressed with LZ4_compress_default\n", sIndentP.c_str()); fprintf(pHeaderFile, "%s extern const unsigned int Size;\n", sIndentP.c_str()); fprintf(pHeaderFile, "%s extern const unsigned int CompressedSize;\n", sIndentP.c_str()); fprintf(pHeaderFile, "%s extern const char CompressedData[];\n", sIndentP.c_str()); fprintf(pSourceFile, "%sconst unsigned int Size = %d;\n", sIndentP.c_str(), iOriginSize); fprintf(pSourceFile, "%sconst unsigned int CompressedSize = %d;\n", sIndentP.c_str(), iCompressedSize); fprintf(pSourceFile, "%sconst char CompressedData[] = {", sIndentP.c_str()); } else { fprintf(pHeaderFile, "%s extern const unsigned int Size;\n", sIndentP.c_str()); fprintf(pHeaderFile, "%s extern const char Data[];\n", sIndentP.c_str()); fprintf(pSourceFile, "%sconst unsigned int Size = %d;\n", sIndentP.c_str(), iOriginSize); fprintf(pSourceFile, "%sconst char Data[] = {", sIndentP.c_str()); } unsigned int iSize = bCompress ? iCompressedSize : iOriginSize; for (size_t iPos = 0; iPos < iSize; ++iPos) { if (iPos % 16 == 0) { fprintf(pSourceFile, "\n%s", sIndentPP.c_str()); } fprintf(pSourceFile, "0x%02X", (unsigned char)*(pData + iPos)); if (iPos < (iSize - 1)) fprintf(pSourceFile, ","); } fprintf(pSourceFile, "\n%s};\n", sIndentP.c_str()); //Closing namespaces fprintf(pHeaderFile, "%s}\n", sIndent.c_str()); fprintf(pSourceFile, "%s}\n", sIndent.c_str()); for (size_t iNamespace = oNamespaces.size()-1; iNamespace >= 0; --iNamespace) { std::string sNamespaceIndent(iNamespace, '\t'); fprintf(pHeaderFile, "%s}\n", sNamespaceIndent.c_str()); fprintf(pSourceFile, "%s}\n", sNamespaceIndent.c_str()); } fprintf(pHeaderFile, "#endif // %s", sDefine.c_str()); fclose(pHeaderFile); fclose(pSourceFile); free(pData); } void ScanFolder(const char* pInputFolder, const char* pOutputFolderBase, const char* pOutputRelative, bool bCompress) { printf("Scanning folder %s\n", pInputFolder); std::string sFolder = pOutputFolderBase; if (NULL != pOutputRelative) { sFolder += "/"; sFolder += pOutputRelative; } _mkdir(sFolder.c_str()); tinydir_dir dir; tinydir_open(&dir, pInputFolder); while (dir.has_next) { tinydir_file file; tinydir_readfile(&dir, &file); if (file.is_dir) { if (file.name != std::string(".") && file.name != std::string("..")) { std::string sOutRelative = ""; if (NULL != pOutputRelative) { sOutRelative += pOutputRelative; sOutRelative += "/"; } sOutRelative += file.name; ScanFolder(file.path, pOutputFolderBase, sOutRelative.c_str(), bCompress); } } else { std::string sOutPath = pOutputFolderBase; if (NULL != pOutputRelative) { sOutPath += "/"; sOutPath += pOutputRelative; } sOutPath += "/"; std::string sName = file.name; ReplaceAll(sName, ".", "_"); ReplaceAll(sName, " ", "_"); sOutPath += sName; ExportFile(file.name, file.path, sOutPath.c_str(), pOutputRelative, bCompress); } tinydir_next(&dir); } tinydir_close(&dir); } void main(int argn, char** argv) { const char* pInputFolder = NULL; const char* pOutputFolder = NULL; bool bCompress = false; int iArg = 1; while (iArg < argn) { if (strcmp(argv[iArg], "-c") == 0) { bCompress = true; } else if (pInputFolder == NULL) { pInputFolder = argv[iArg]; } else if (pOutputFolder == NULL) { pOutputFolder = argv[iArg]; } else { //Ignore other arguments } ++iArg; } if (pInputFolder != NULL && pOutputFolder != NULL) { ScanFolder(pInputFolder, pOutputFolder, NULL, bCompress); } else { printf("Usage: ResourceEmbedder <input resource folder> <output cpp folder>\n"); } }<|endoftext|>
<commit_before>#include "psi_storm.h" namespace AI { class MindControlTargetFinderProc: public scbw::UnitFinderCallbackMatchInterface { private: const CUnit *caster; bool isUnderAttack; public: MindControlTargetFinderProc(const CUnit *caster, bool isUnderAttack) : caster(caster), isUnderAttack(isUnderAttack) {} bool match(const CUnit *target) { if (target == caster) return false; if (!isTargetWorthHitting(target, caster)) return false; if (Unit::BaseProperty[target->id] & UnitProperty::Hero) return false; if (target->id == UnitId::shuttle || target->id == UnitId::dropship) if (target->hasLoadedUnit()) return true; switch (target->id) { case UnitId::shuttle: case UnitId::dropship: if (target->hasLoadedUnit()) return true; break; case UnitId::siege_tank: case UnitId::siege_tank_s: case UnitId::science_vessel: case UnitId::battlecruiser: case UnitId::medic: case UnitId::overlord: case UnitId::ultralisk: case UnitId::queen: case UnitId::defiler: case UnitId::devourer: case UnitId::dark_archon: case UnitId::high_templar: case UnitId::arbiter: case UnitId::carrier: case UnitId::reaver: case UnitId::lurker: return true; default: if (Unit::MineralCost[target->id] >= Unit::MineralCost[UnitId::dark_templar] && Unit::GasCost[target->id] >= Unit::GasCost[UnitId::dark_templar]) return true; break; } return false; } }; CUnit* findBestMindControlTarget(const CUnit *caster, bool isUnderAttack) { int bounds = 32 * 32; return scbw::UnitFinder::getNearest(caster->getX(), caster->getY(), caster->getX() - bounds, caster->getY() - bounds, caster->getX() + bounds, caster->getY() + bounds, MindControlTargetFinderProc(caster, isUnderAttack)); } } //AI <commit_msg>SCT: AI does not attempt to use Mind Control on air units.<commit_after>#include "psi_storm.h" namespace AI { class MindControlTargetFinderProc: public scbw::UnitFinderCallbackMatchInterface { private: const CUnit *caster; bool isUnderAttack; public: MindControlTargetFinderProc(const CUnit *caster, bool isUnderAttack) : caster(caster), isUnderAttack(isUnderAttack) {} bool match(const CUnit *target) { if (target == caster) return false; //Air units cannot be Mind Controlled if (target->status & UnitStatus::InAir) return false; if (!isTargetWorthHitting(target, caster)) return false; if (Unit::BaseProperty[target->id] & UnitProperty::Hero) return false; //if (target->id == UnitId::shuttle || target->id == UnitId::dropship) // if (target->hasLoadedUnit()) // return true; switch (target->id) { //case UnitId::shuttle: //case UnitId::dropship: // if (target->hasLoadedUnit()) // return true; // break; case UnitId::siege_tank: case UnitId::siege_tank_s: //case UnitId::science_vessel: //case UnitId::battlecruiser: case UnitId::medic: case UnitId::ghost: //Added //case UnitId::overlord: case UnitId::ultralisk: //case UnitId::queen: case UnitId::defiler: //case UnitId::devourer: case UnitId::dark_archon: case UnitId::high_templar: //case UnitId::arbiter: //case UnitId::carrier: case UnitId::reaver: case UnitId::lurker: return true; default: if (Unit::MineralCost[target->id] >= Unit::MineralCost[UnitId::dark_templar] && Unit::GasCost[target->id] >= Unit::GasCost[UnitId::dark_templar]) return true; break; } return false; } }; CUnit* findBestMindControlTarget(const CUnit *caster, bool isUnderAttack) { int bounds = 32 * 32; return scbw::UnitFinder::getNearest(caster->getX(), caster->getY(), caster->getX() - bounds, caster->getY() - bounds, caster->getX() + bounds, caster->getY() + bounds, MindControlTargetFinderProc(caster, isUnderAttack)); } } //AI <|endoftext|>
<commit_before>#pragma once //=====================================================================// /*! @file @brief RX64M, RX65x, RX71M, RX72M グループ・CMTW 定義 @author 平松邦仁 (hira@rvf-rc45.net) @copyright Copyright (C) 2018, 2020 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include "common/device.hpp" /// cmtw モジュールが無いデバイスでエラーとする #if defined(SIG_RX24T) || defined(SIG_RX66T) || defined(SIG_RX72T) # error "cmtw.hpp: This module does not exist" #endif namespace device { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief コンペアマッチタイマ W クラス @param[in] base ベース・アドレス @param[in] per ペリフェラル @param[in] ivec 割り込みベクター */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <uint32_t base, peripheral per, ICU::VECTOR ivec> struct cmtw_t { static const auto PERIPHERAL = per; ///< ペリフェラル型 static const auto IVEC = ivec; ///< 割り込みベクター static const uint32_t PCLK = F_PCLKB; ///< PCLK 周波数 //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief タイマスタートレジスタ(CMWSTR) */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// struct cmwstr_t : public rw16_t<base + 0x00> { typedef rw16_t<base + 0x00> io_; using io_::operator =; using io_::operator (); using io_::operator |=; using io_::operator &=; bit_rw_t <io_, bitpos::B0> STR; }; static cmwstr_t CMWSTR; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief タイマコントロールレジスタ(CMWCR) */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// struct cmwcr_t : public rw16_t<base + 0x04> { typedef rw16_t<base + 0x04> io_; using io_::operator =; using io_::operator (); using io_::operator |=; using io_::operator &=; bits_rw_t<io_, bitpos::B0, 2> CKS; bit_rw_t <io_, bitpos::B3> CMWIE; bit_rw_t <io_, bitpos::B4> IC0IE; bit_rw_t <io_, bitpos::B5> IC1IE; bit_rw_t <io_, bitpos::B6> OC0IE; bit_rw_t <io_, bitpos::B7> OC1IE; bit_rw_t <io_, bitpos::B9> CMS; bits_rw_t<io_, bitpos::B13, 3> CCLR; }; static cmwcr_t CMWCR; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief タイマ I/O コントロールレジスタ(CMWIOR) */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// struct cmwior_t : public rw16_t<base + 0x08> { typedef rw16_t<base + 0x08> io_; using io_::operator =; using io_::operator (); using io_::operator |=; using io_::operator &=; bits_rw_t<io_, bitpos::B0, 2> IC0; bits_rw_t<io_, bitpos::B2, 2> IC1; bit_rw_t <io_, bitpos::B4> IC0E; bit_rw_t <io_, bitpos::B5> IC1E; bits_rw_t<io_, bitpos::B8, 2> OC0; bits_rw_t<io_, bitpos::B10, 2> OC1; bit_rw_t <io_, bitpos::B12> OC0E; bit_rw_t <io_, bitpos::B13> OC1E; bit_rw_t <io_, bitpos::B15> CMWE; }; static cmwior_t CMWIOR; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief タイマカウンタ(CMWCNT) */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// static rw32_t<base + 0x10> CMWCNT; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief コンペアマッチコンスタントレジスタ(CMWCOR) */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// static rw32_t<base + 0x14> CMWCOR; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief インプットキャプチャレジスタ 0(CMWICR0) */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// static rw32_t<base + 0x18> CMWICR0; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief インプットキャプチャレジスタ 1(CMWICR1) */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// static rw32_t<base + 0x1C> CMWICR1; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief アウトプットコンペアレジスタ 0(CMWOCR0) */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// static rw32_t<base + 0x20> CMWOCR0; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief アウトプットコンペアレジスタ 1(CMWOCR1) */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// static rw32_t<base + 0x24> CMWOCR1; }; typedef cmtw_t<0x00094200, peripheral::CMTW0, ICU::VECTOR::CMWI0> CMTW0; typedef cmtw_t<0x00094280, peripheral::CMTW1, ICU::VECTOR::CMWI1> CMTW1; } <commit_msg>Update: The reality of the template when it is not optimized<commit_after>#pragma once //=====================================================================// /*! @file @brief RX64M, RX65x, RX71M, RX72M, RX72N グループ・CMTW 定義 @author 平松邦仁 (hira@rvf-rc45.net) @copyright Copyright (C) 2018, 2020 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include "common/device.hpp" /// cmtw モジュールが無いデバイスでエラーとする #if defined(SIG_RX24T) || defined(SIG_RX66T) || defined(SIG_RX72T) # error "cmtw.hpp: This module does not exist" #endif namespace device { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief コンペアマッチタイマ W クラス @param[in] base ベース・アドレス @param[in] per ペリフェラル @param[in] ivec 割り込みベクター */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <uint32_t base, peripheral per, ICU::VECTOR ivec> struct cmtw_t { static const auto PERIPHERAL = per; ///< ペリフェラル型 static const auto IVEC = ivec; ///< 割り込みベクター static const uint32_t PCLK = F_PCLKB; ///< PCLK 周波数 //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief タイマスタートレジスタ(CMWSTR) @param[in] ofs レジスタ・オフセット */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <uint32_t ofs> struct cmwstr_t : public rw16_t<ofs> { typedef rw16_t<ofs> io_; using io_::operator =; using io_::operator (); using io_::operator |=; using io_::operator &=; bit_rw_t <io_, bitpos::B0> STR; }; typedef cmwstr_t<base + 0x00> CMWSTR_; static CMWSTR_ CMWSTR; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief タイマコントロールレジスタ(CMWCR) @param[in] ofs レジスタ・オフセット */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <uint32_t ofs> struct cmwcr_t : public rw16_t<ofs> { typedef rw16_t<ofs> io_; using io_::operator =; using io_::operator (); using io_::operator |=; using io_::operator &=; bits_rw_t<io_, bitpos::B0, 2> CKS; bit_rw_t <io_, bitpos::B3> CMWIE; bit_rw_t <io_, bitpos::B4> IC0IE; bit_rw_t <io_, bitpos::B5> IC1IE; bit_rw_t <io_, bitpos::B6> OC0IE; bit_rw_t <io_, bitpos::B7> OC1IE; bit_rw_t <io_, bitpos::B9> CMS; bits_rw_t<io_, bitpos::B13, 3> CCLR; }; typedef cmwcr_t<base + 0x04> CMWCR_; static CMWCR_ CMWCR; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief タイマ I/O コントロールレジスタ(CMWIOR) @param[in] ofs レジスタ・オフセット */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <uint32_t ofs> struct cmwior_t : public rw16_t<ofs> { typedef rw16_t<ofs> io_; using io_::operator =; using io_::operator (); using io_::operator |=; using io_::operator &=; bits_rw_t<io_, bitpos::B0, 2> IC0; bits_rw_t<io_, bitpos::B2, 2> IC1; bit_rw_t <io_, bitpos::B4> IC0E; bit_rw_t <io_, bitpos::B5> IC1E; bits_rw_t<io_, bitpos::B8, 2> OC0; bits_rw_t<io_, bitpos::B10, 2> OC1; bit_rw_t <io_, bitpos::B12> OC0E; bit_rw_t <io_, bitpos::B13> OC1E; bit_rw_t <io_, bitpos::B15> CMWE; }; typedef cmwior_t<base + 0x08> CMWIOR_; static CMWIOR_ CMWIOR; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief タイマカウンタ(CMWCNT) */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// typedef rw32_t<base + 0x10> CMWCNT_; static CMWCNT_ CMWCNT; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief コンペアマッチコンスタントレジスタ(CMWCOR) */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// typedef rw32_t<base + 0x14> CMWCOR_; static CMWCOR_ CMWCOR; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief インプットキャプチャレジスタ 0(CMWICR0) */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// typedef rw32_t<base + 0x18> CMWICR0_; static CMWICR0_ CMWICR0; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief インプットキャプチャレジスタ 1(CMWICR1) */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// typedef rw32_t<base + 0x1C> CMWICR1_; static CMWICR1_ CMWICR1; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief アウトプットコンペアレジスタ 0(CMWOCR0) */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// typedef rw32_t<base + 0x20> CMWOCR0_; static CMWOCR0_ CMWOCR0; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief アウトプットコンペアレジスタ 1(CMWOCR1) */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// typedef rw32_t<base + 0x24> CMWOCR1_; static CMWOCR1_ CMWOCR1; }; template <uint32_t base, peripheral per, ICU::VECTOR ivec> typename cmtw_t<base, per, ivec>:: CMWSTR_ cmtw_t<base, per, ivec>::CMWSTR; template <uint32_t base, peripheral per, ICU::VECTOR ivec> typename cmtw_t<base, per, ivec>:: CMWCR_ cmtw_t<base, per, ivec>::CMWCR; template <uint32_t base, peripheral per, ICU::VECTOR ivec> typename cmtw_t<base, per, ivec>:: CMWIOR_ cmtw_t<base, per, ivec>::CMWIOR; template <uint32_t base, peripheral per, ICU::VECTOR ivec> typename cmtw_t<base, per, ivec>:: CMWCNT_ cmtw_t<base, per, ivec>::CMWCNT; template <uint32_t base, peripheral per, ICU::VECTOR ivec> typename cmtw_t<base, per, ivec>:: CMWCOR_ cmtw_t<base, per, ivec>::CMWCOR; template <uint32_t base, peripheral per, ICU::VECTOR ivec> typename cmtw_t<base, per, ivec>:: CMWICR0_ cmtw_t<base, per, ivec>::CMWICR0; template <uint32_t base, peripheral per, ICU::VECTOR ivec> typename cmtw_t<base, per, ivec>:: CMWICR1_ cmtw_t<base, per, ivec>::CMWICR1; template <uint32_t base, peripheral per, ICU::VECTOR ivec> typename cmtw_t<base, per, ivec>:: CMWOCR0_ cmtw_t<base, per, ivec>::CMWOCR0; template <uint32_t base, peripheral per, ICU::VECTOR ivec> typename cmtw_t<base, per, ivec>:: CMWOCR1_ cmtw_t<base, per, ivec>::CMWOCR1; typedef cmtw_t<0x00094200, peripheral::CMTW0, ICU::VECTOR::CMWI0> CMTW0; typedef cmtw_t<0x00094280, peripheral::CMTW1, ICU::VECTOR::CMWI1> CMTW1; } <|endoftext|>
<commit_before><commit_msg>a0c8a98e-2e4e-11e5-9284-b827eb9e62be<commit_after><|endoftext|>
<commit_before><commit_msg>b2d07332-2e4e-11e5-9284-b827eb9e62be<commit_after><|endoftext|>
<commit_before>void tarjanRec(AdjacencyList& adj, int u, int& group, vi& node2group, vi& node2lowgroup, vector<bool>& onStack, stack<int>& s, vi& rep){ node2group[u] = group; node2lowgroup[u] = group; group++; s.push_back(u); onStack[u] = true; for(auto p: adj[u]){ int v = p.first; if (node2group[v] == -1) { tarjanRec(adj,v,group,node2group,node2lowgroup,onStack,s,rep); node2lowgroup[u] = min(node2lowgroup[u],node2lowgroup[v]); } else if (onStack[v]) { node2lowgroup[u] = min(node2lowgroup[u],node2group[v]); } } if (node2group[u] == node2lowgroup[u]) { rep.push_back(u); int v = s.back(); while(u != v){ s.pop_back(); onStack[v] = false; v = s.back(); } } } //at end, rep contains one node for each scc void tarjan(AdjacencyList& adj, vi& rep){ int group = 0; vi node2group, node2lowgroup; stack<int> s; vector<bool> onStack; for(int u = 0; u < adj.size(); u++){ node2group.push_back(-1); node2lowgroup.push_back(-1); onStack.push_back(false); } for(int u = 0; u < adj.size(); u++){ if (node2group[u] == -1) { tarjanRec(adj,u,node2group,node2lowgroup,onStack,s,rep); } } } <commit_msg>Used working scc code from NYU codebook<commit_after> //Based on NYU codebook void tarjanRec (AdjacencyList& adj, int i, vi& visited, vi& low, int& t, stack<int>& s, vi& sccNum, int& scc) { if (visited[i]) { return; } t++; visited[i] = low[i] = t; s.push(i); for(auto p: adj[i]){ tarjanRec(adj,p.first,visited,low,t,s,sccNum,scc); low[i] = min(low[i],low[p.first]); } if (low[i] == visited[i]){ while(true){ int k = s.top(); s.pop(); sccNum[k] = scc; low[k] = INT_MAX; if (k == i) { break; } } scc++; } } //returns the number of connected components //sccNum maps node to scc (the "group's number") int tarjan(AdjacencyList& adj, vi& sccNum){ size_t n = adj.size(); int t = 0; int scc = 0; vi visited(n), low(n); stack<int> s; repeat(i,n) { tarjanRec(adj,i,visited,low,t,s,sccNum,scc); } return scc; } <|endoftext|>
<commit_before><commit_msg>Delete 2.cpp<commit_after><|endoftext|>
<commit_before><commit_msg>knn: abstracted the main parts of the program into separate functions in the KNearestNeighbors namespace<commit_after><|endoftext|>
<commit_before>#define CATCH_CONFIG_MAIN #include "catch.hpp" #include "gin/raw_linear_allocator_impl.h" // Nothing here yet, just the entry point <commit_msg>Cleanup bad include<commit_after>#define CATCH_CONFIG_MAIN #include "catch.hpp" // Nothing here yet, just the entry point <|endoftext|>
<commit_before>// Moon Phase Calendar for Arduino, using Pro Trinket 3V/12MHz // Test support #include "arduino.hpp" // Arduino application #include "../arduino/MoonPhaseCalendar/MoonPhaseCalendar.ino" // Test program #include "lest.hpp" #include <iomanip> #include <ostream> using pause_ms = int; template< typename T > T setbit( T const x, int const pos, bool const on ) { return on ? x | bit( pos ) : x & ~bit( pos ); } bool operator==( Date a, Date b ) { return a.year == b.year && a.month == b.month && a.day == b.day; } std::ostream & operator<< ( std::ostream & os, Date const & d ) { return os << "(" << d.year << "," << std::setw(2) << d.month << "," << std::setw(2) << d.day << ")" ; } #define CASE( name ) lest_CASE( specification(), name ) lest::tests & specification() { static lest::tests tests; return tests; } // Test specification namespace { CASE( "Convenience: bit sets proper bit" ) { EXPECT( bit( 0 ) == 0x01 ); EXPECT( bit( 1 ) == 0x02 ); EXPECT( bit( 2 ) == 0x04 ); EXPECT( bit( 3 ) == 0x08 ); EXPECT( bit( 4 ) == 0x10 ); EXPECT( bit( 5 ) == 0x20 ); EXPECT( bit( 6 ) == 0x40 ); EXPECT( bit( 7 ) == 0x80 ); } CASE( "Convenience: bit tests true for set bits" ) { for ( int i = 0; i < 8; ++i ) EXPECT( bitRead( bit(i), i ) ); } CASE( "Convenience: bit tests false for unset bits" ) { for ( int i = 0; i < 8; ++i ) for ( int k = i+1; k < 8; ++k ) EXPECT_NOT( bitRead( bit(i), k ) ); } CASE( "Convenience: setbit manipulates proper bit" ) { for ( int i = 0; i < 16 ; ++i ) { EXPECT( setbit( 0x0000, i, true ) == ( bit(i) ) ); EXPECT( setbit( 0xFFFF, i, false ) == ( bit(i) ^ 0xFFFF ) ); } } CASE( "Electronics: Moon phase display sets pins properly" ) { static int pattern[] = { 0b0000, 0b0001, 0b0011, 0b0111, 0b1111, 0b1110, 0b1100, 0b1000, }; static_assert( dimension_of(pattern) == phase_count, "expecting #pattern == pin_moon_count" ); mock_setup(); for ( int i = 0; i < 8; ++i ) { display_moon_phase( i ); EXPECT( pattern[i] == g_pin_value >> pin_moon_first ); } } CASE( "Electronics: Date display: ... [.]" ) { mock_setup(); EXPECT( !"Implement" ); } CASE( "Electronics: Rotary encoder: ... [.]" ) { mock_setup(); EXPECT( !"Implement" ); } CASE( "Electronics: Button: ... [.]" ) { mock_setup(); EXPECT( !"Implement" ); } CASE( "Algorithm: A leap year if divisible by 400 [leap]" ) { EXPECT( is_leap_year( 1600 ) ); EXPECT( is_leap_year( 2000 ) ); EXPECT( is_leap_year( 2400 ) ); } CASE( "Algorithm: A leap year if divisible by 4 but not by 100 [leap]" ) { EXPECT( is_leap_year( 1996 ) ); EXPECT( is_leap_year( 2008 ) ); EXPECT( is_leap_year( 2016 ) ); } CASE( "Algorithm: Not a leap year if not divisible by 4 [leap]" ) { EXPECT_NOT( is_leap_year( 1998 ) ); EXPECT_NOT( is_leap_year( 1999 ) ); EXPECT_NOT( is_leap_year( 2010 ) ); } CASE( "Algorithm: Not a leap year if divisible by 100 but not by 400 [leap]" ) { EXPECT_NOT( is_leap_year( 1800 ) ); EXPECT_NOT( is_leap_year( 1900 ) ); EXPECT_NOT( is_leap_year( 2100 ) ); } CASE( "Algorithm: 1 Jan 2000 is adjacent to 2 Jan 2000 [date]" ) { EXPECT( next_date( Date{2000, 1, 1} ) == ( Date{2000, 1, 2} ) ); EXPECT( ( Date{2000, 1, 1} ) == prev_date( Date{2000, 1, 2} ) ); } CASE( "Algorithm: 28 Feb 2000 is adjacent to 29 Feb 2000 (leap year) [date]" ) { EXPECT( next_date( Date{2000, 2, 28} ) == ( Date{2000, 2, 29} ) ); EXPECT( ( Date{2000, 2, 28} ) == prev_date( Date{2000, 2, 29} ) ); } CASE( "Algorithm: 28 Feb 2015 is adjacent to 1 Mar 2015 (non leap year) [date]" ) { EXPECT( next_date( Date{2015, 2, 28} ) == ( Date{2015, 3, 1} ) ); EXPECT( ( Date{2015, 2, 28} ) == prev_date( Date{2015, 3, 1} ) ); } CASE( "Algorithm: 31 Dec 2015 is adjacent to 1 Jan 2016 [date]" ) { EXPECT( next_date( Date{2015, 12, 31} ) == ( Date{2016, 1, 1} ) ); EXPECT( ( Date{2015, 12, 31} ) == prev_date( Date{2016, 1, 1} ) ); } CASE( "Algorithm: New moon on 13 Oct 2015 [moon]" ) { EXPECT( moon_phase( {2015, 10, 13} ) == New ); } CASE( "Algorithm: First quarter on 20 Oct 2015 [moon]" ) { EXPECT( moon_phase( {2015, 10, 20} ) == FirstQuarter ); } CASE( "Algorithm: Full moon on 27 Oct 2015 [moon]" ) { EXPECT( moon_phase( {2015, 10, 27} ) == Full ); } CASE( "Algorithm: Last quarter on 3 Nov 2015 [moon]" ) { EXPECT( moon_phase( {2015, 11, 3} ) == ThirdQuarter ); } CASE( "Acceptance: New moon on 13 Oct 2015 [.accept]" ) { mock_setup(); Date next = once( {2015, 10, 13}, pause_ms(0) ); EXPECT( next == ( Date{2015, 10, 14} ) ); EXPECT( 1310 == display.m_value ); EXPECT( 0b0000 == g_pin_value >> pin_moon_first ); } CASE( "Acceptance: First quarter on 20 Oct 2015 [.accept]" ) { mock_setup(); Date next = once( {2015, 10, 20}, pause_ms(0) ); EXPECT( next == ( Date{2015, 10, 21} ) ); EXPECT( 2010 == display.m_value ); EXPECT( 0b0011 == g_pin_value >> pin_moon_first ); } CASE( "Acceptance: Full moon on 27 Oct 2015 [.accept]" ) { mock_setup(); Date next = once( {2015, 10, 27}, pause_ms(0) ); EXPECT( next == ( Date{2015, 10, 28} ) ); EXPECT( 2710 == display.m_value ); EXPECT( 0b1111 == g_pin_value >> pin_moon_first ); } CASE( "Acceptance: Last quarter on 3 Nov 2015 [.accept]" ) { mock_setup(); Date next = once( {2015, 11, 3}, pause_ms(0) ); EXPECT( next == ( Date{2015, 11, 4} ) ); EXPECT( 311 == display.m_value ); EXPECT( 0b1100 == g_pin_value >> pin_moon_first ); } CASE( "App: date-moon phase [.app]" ) { char const * const phase[] = { "....", "...)", "..|)", ".||)", "(||)", "(||.", "(|..", "(...", }; Date day{2015, 11, 1}; for (;;) { day = next_date( day ); std::cout << day << " " << phase[ moon_phase( day ) ] << "\r"; delay( 300 ); } } } int main( int argc, char * argv[] ) { return lest::run( specification(), argc, argv /*, std::cout */ ); } #if 0 cl -W3 -Dlest_FEATURE_AUTO_REGISTER=1 -I. -EHsc test.cpp && test.exe g++ -std=c++11 -Wall -Dlest_FEATURE_AUTO_REGISTER=1 -I. -o test.exe test.cpp && test.exe #endif // 0 <commit_msg>Order tests as items appear in .ino file<commit_after>// Moon Phase Calendar for Arduino, using Pro Trinket 3V/12MHz // Test support #include "arduino.hpp" // Arduino application #include "../arduino/MoonPhaseCalendar/MoonPhaseCalendar.ino" // Test program #include "lest.hpp" #include <iomanip> #include <ostream> using pause_ms = int; template< typename T > T setbit( T const x, int const pos, bool const on ) { return on ? x | bit( pos ) : x & ~bit( pos ); } bool operator==( Date a, Date b ) { return a.year == b.year && a.month == b.month && a.day == b.day; } std::ostream & operator<< ( std::ostream & os, Date const & d ) { return os << "(" << d.year << "," << std::setw(2) << d.month << "," << std::setw(2) << d.day << ")" ; } #define CASE( name ) lest_CASE( specification(), name ) lest::tests & specification() { static lest::tests tests; return tests; } // Test specification namespace { CASE( "Convenience: bit sets proper bit" ) { EXPECT( bit( 0 ) == 0x01 ); EXPECT( bit( 1 ) == 0x02 ); EXPECT( bit( 2 ) == 0x04 ); EXPECT( bit( 3 ) == 0x08 ); EXPECT( bit( 4 ) == 0x10 ); EXPECT( bit( 5 ) == 0x20 ); EXPECT( bit( 6 ) == 0x40 ); EXPECT( bit( 7 ) == 0x80 ); } CASE( "Convenience: bit tests true for set bits" ) { for ( int i = 0; i < 8; ++i ) EXPECT( bitRead( bit(i), i ) ); } CASE( "Convenience: bit tests false for unset bits" ) { for ( int i = 0; i < 8; ++i ) for ( int k = i+1; k < 8; ++k ) EXPECT_NOT( bitRead( bit(i), k ) ); } CASE( "Convenience: setbit manipulates proper bit" ) { for ( int i = 0; i < 16 ; ++i ) { EXPECT( setbit( 0x0000, i, true ) == ( bit(i) ) ); EXPECT( setbit( 0xFFFF, i, false ) == ( bit(i) ^ 0xFFFF ) ); } } CASE( "Electronics: Rotary encoder: ... [.]" ) { mock_setup(); EXPECT( !"Implement" ); } CASE( "Electronics: Button: ... [.]" ) { mock_setup(); EXPECT( !"Implement" ); } CASE( "Electronics: Date display: ... [.]" ) { mock_setup(); EXPECT( !"Implement" ); } CASE( "Electronics: Moon phase display sets pins properly" ) { static int pattern[] = { 0b0000, 0b0001, 0b0011, 0b0111, 0b1111, 0b1110, 0b1100, 0b1000, }; static_assert( dimension_of(pattern) == phase_count, "expecting #pattern == pin_moon_count" ); mock_setup(); for ( int i = 0; i < 8; ++i ) { display_moon_phase( i ); EXPECT( pattern[i] == g_pin_value >> pin_moon_first ); } } CASE( "Algorithm: A leap year if divisible by 400 [leap]" ) { EXPECT( is_leap_year( 1600 ) ); EXPECT( is_leap_year( 2000 ) ); EXPECT( is_leap_year( 2400 ) ); } CASE( "Algorithm: A leap year if divisible by 4 but not by 100 [leap]" ) { EXPECT( is_leap_year( 1996 ) ); EXPECT( is_leap_year( 2008 ) ); EXPECT( is_leap_year( 2016 ) ); } CASE( "Algorithm: Not a leap year if not divisible by 4 [leap]" ) { EXPECT_NOT( is_leap_year( 1998 ) ); EXPECT_NOT( is_leap_year( 1999 ) ); EXPECT_NOT( is_leap_year( 2010 ) ); } CASE( "Algorithm: Not a leap year if divisible by 100 but not by 400 [leap]" ) { EXPECT_NOT( is_leap_year( 1800 ) ); EXPECT_NOT( is_leap_year( 1900 ) ); EXPECT_NOT( is_leap_year( 2100 ) ); } CASE( "Algorithm: 1 Jan 2000 is adjacent to 2 Jan 2000 [date]" ) { EXPECT( next_date( Date{2000, 1, 1} ) == ( Date{2000, 1, 2} ) ); EXPECT( ( Date{2000, 1, 1} ) == prev_date( Date{2000, 1, 2} ) ); } CASE( "Algorithm: 28 Feb 2000 is adjacent to 29 Feb 2000 (leap year) [date]" ) { EXPECT( next_date( Date{2000, 2, 28} ) == ( Date{2000, 2, 29} ) ); EXPECT( ( Date{2000, 2, 28} ) == prev_date( Date{2000, 2, 29} ) ); } CASE( "Algorithm: 28 Feb 2015 is adjacent to 1 Mar 2015 (non leap year) [date]" ) { EXPECT( next_date( Date{2015, 2, 28} ) == ( Date{2015, 3, 1} ) ); EXPECT( ( Date{2015, 2, 28} ) == prev_date( Date{2015, 3, 1} ) ); } CASE( "Algorithm: 31 Dec 2015 is adjacent to 1 Jan 2016 [date]" ) { EXPECT( next_date( Date{2015, 12, 31} ) == ( Date{2016, 1, 1} ) ); EXPECT( ( Date{2015, 12, 31} ) == prev_date( Date{2016, 1, 1} ) ); } CASE( "Algorithm: New moon on 13 Oct 2015 [moon]" ) { EXPECT( moon_phase( {2015, 10, 13} ) == New ); } CASE( "Algorithm: First quarter on 20 Oct 2015 [moon]" ) { EXPECT( moon_phase( {2015, 10, 20} ) == FirstQuarter ); } CASE( "Algorithm: Full moon on 27 Oct 2015 [moon]" ) { EXPECT( moon_phase( {2015, 10, 27} ) == Full ); } CASE( "Algorithm: Last quarter on 3 Nov 2015 [moon]" ) { EXPECT( moon_phase( {2015, 11, 3} ) == ThirdQuarter ); } CASE( "Acceptance: New moon on 13 Oct 2015 [.accept]" ) { mock_setup(); Date next = once( {2015, 10, 13}, pause_ms(0) ); EXPECT( next == ( Date{2015, 10, 14} ) ); EXPECT( 1310 == display.m_value ); EXPECT( 0b0000 == g_pin_value >> pin_moon_first ); } CASE( "Acceptance: First quarter on 20 Oct 2015 [.accept]" ) { mock_setup(); Date next = once( {2015, 10, 20}, pause_ms(0) ); EXPECT( next == ( Date{2015, 10, 21} ) ); EXPECT( 2010 == display.m_value ); EXPECT( 0b0011 == g_pin_value >> pin_moon_first ); } CASE( "Acceptance: Full moon on 27 Oct 2015 [.accept]" ) { mock_setup(); Date next = once( {2015, 10, 27}, pause_ms(0) ); EXPECT( next == ( Date{2015, 10, 28} ) ); EXPECT( 2710 == display.m_value ); EXPECT( 0b1111 == g_pin_value >> pin_moon_first ); } CASE( "Acceptance: Last quarter on 3 Nov 2015 [.accept]" ) { mock_setup(); Date next = once( {2015, 11, 3}, pause_ms(0) ); EXPECT( next == ( Date{2015, 11, 4} ) ); EXPECT( 311 == display.m_value ); EXPECT( 0b1100 == g_pin_value >> pin_moon_first ); } CASE( "App: date-moon phase [.app]" ) { char const * const phase[] = { "....", "...)", "..|)", ".||)", "(||)", "(||.", "(|..", "(...", }; Date day{2015, 11, 1}; for (;;) { day = next_date( day ); std::cout << day << " " << phase[ moon_phase( day ) ] << "\r"; delay( 300 ); } } } int main( int argc, char * argv[] ) { return lest::run( specification(), argc, argv /*, std::cout */ ); } #if 0 cl -W3 -Dlest_FEATURE_AUTO_REGISTER=1 -I. -EHsc test.cpp && test.exe g++ -std=c++11 -Wall -Dlest_FEATURE_AUTO_REGISTER=1 -I. -o test.exe test.cpp && test.exe #endif // 0 <|endoftext|>
<commit_before>#include "GameProcess.h" #include "Object.h" #include "Engine.h" #include "World.h" #include "App.h" #include "ToolsCamera.h" #include "ControlsApp.h" #include "MathLib.h" #include "Game.h" #include "Editor.h" #include "Input.h" #include "BlueRayUtils.h" using namespace MathLib; CGameProcess::CGameProcess(void) { } CGameProcess::~CGameProcess(void) { } int CGameProcess::Init() { g_Engine.pFileSystem->CacheFilesFormExt("char"); g_Engine.pFileSystem->CacheFilesFormExt("node"); g_Engine.pFileSystem->CacheFilesFormExt("smesh"); g_Engine.pFileSystem->CacheFilesFormExt("sanim"); g_Engine.pWorld->LoadWorld("data/scene/terrain/test/test.world"); //g_Engine.pWorld->LoadWorld("data/scene/terrain/cj/cj.world"); g_Engine.pControls->SetKeyPressFunc(KeyPress); g_Engine.pControls->SetKeyReleaseFunc(KeyRelease); m_pRole = new CFPSRoleLocal(); m_pRole->Init(10001, "data/role/hero/FpsRole/fps.char"); //ؽɫԴ m_pRole->SetActorPosition(vec3(0, 0, 0)); //ýɫʼλáŴΪԭ㣬άϵvec3 m_pSkillSystem = new CSkillSystem(this); m_pCameraBase = new CCameraBase(); m_pCameraBase->SetEnabled(1); g_pSysControl->SetMouseGrab(1); m_pStarControl = new CStarControl(); m_pRayControl = new CRayControl(); return 1; } int CGameProcess::ShutDown() //رϷ { delete m_pRole; delete m_pSkillSystem; delete m_pCameraBase; delete m_pStarControl; delete m_pRayControl; DelAllListen(); return 0; } int CGameProcess::Update() { float ifps = g_Engine.pGame->GetIFps(); if (g_Engine.pInput->IsKeyDown('1')) { CAction* pAction = m_pRole->OrceAction("attack02"); if (pAction) { pAction->SetupSkillThrow(vec3_zero, -1.0f, 2.0f); m_pRole->StopMove(); } } else if (g_Engine.pInput->IsKeyDown('2')) { CAction* pAction = m_pRole->OrceAction("skill01"); if (pAction) { m_pRole->StopMove(); } } else if (g_Engine.pInput->IsKeyDown('3')) { CAction* pAction = m_pRole->OrceAction("skill02"); if (pAction) { m_pRole->StopMove(); CRoleBase* pTarget = NULL; for (int i = 0; i < 20; i++) { float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length(); if (l > 5.0f && l < 15.0f) { pTarget = m_vAIList[i]; break; } } if (pTarget) { CVector<int> vTarget; vTarget.Append(pTarget->GetRoleID()); pAction->SetupSkillBulletTarget(vTarget); m_pRole->SetDirection((pTarget->GetPosition() - m_pRole->GetPosition()).normalize(), 1); } } } else if (g_Engine.pInput->IsKeyDown('4'))//෢ӵ { CAction* pAction = m_pRole->OrceAction("skill02"); if (pAction) { m_pRole->StopMove(); } } return 0; } <commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include "GameProcess.h" #include "Object.h" #include "Engine.h" #include "World.h" #include "App.h" #include "ToolsCamera.h" #include "ControlsApp.h" #include "MathLib.h" #include "Game.h" #include "Editor.h" #include "Input.h" #include "BlueRayUtils.h" using namespace MathLib; CGameProcess::CGameProcess(void) { } CGameProcess::~CGameProcess(void) { } int CGameProcess::Init() { g_Engine.pFileSystem->CacheFilesFormExt("char"); g_Engine.pFileSystem->CacheFilesFormExt("node"); g_Engine.pFileSystem->CacheFilesFormExt("smesh"); g_Engine.pFileSystem->CacheFilesFormExt("sanim"); g_Engine.pWorld->LoadWorld("data/scene/terrain/test/test.world"); //g_Engine.pWorld->LoadWorld("data/scene/terrain/cj/cj.world"); g_Engine.pControls->SetKeyPressFunc(KeyPress); g_Engine.pControls->SetKeyReleaseFunc(KeyRelease); m_pRole = new CFPSRoleLocal(); m_pRole->Init(10001, "data/role/hero/FpsRole/fps.char"); //ؽɫԴ m_pRole->SetActorPosition(vec3(0, 0, 0)); //ýɫʼλáŴΪԭ㣬άϵvec3 m_pSkillSystem = new CSkillSystem(this); m_pCameraBase = new CCameraBase(); m_pCameraBase->SetEnabled(1); g_pSysControl->SetMouseGrab(1); m_pStarControl = new CStarControl(); m_pRayControl = new CRayControl(); return 1; } int CGameProcess::ShutDown() //رϷ { delete m_pRole; delete m_pSkillSystem; delete m_pCameraBase; delete m_pStarControl; delete m_pRayControl; DelAllListen(); return 0; } int CGameProcess::Update() { float ifps = g_Engine.pGame->GetIFps(); if (g_Engine.pInput->IsKeyDown('1')) { CAction* pAction = m_pRole->OrceAction("attack02"); if (pAction) { pAction->SetupSkillThrow(vec3_zero, -1.0f, 2.0f); m_pRole->StopMove(); } } else if (g_Engine.pInput->IsKeyDown('2')) { CAction* pAction = m_pRole->OrceAction("skill01"); if (pAction) { m_pRole->StopMove(); } } else if (g_Engine.pInput->IsKeyDown('3')) { CAction* pAction = m_pRole->OrceAction("skill02"); if (pAction) { m_pRole->StopMove(); CRoleBase* pTarget = NULL; for (int i = 0; i < 20; i++) { float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length(); if (l > 5.0f && l < 15.0f) { pTarget = m_vAIList[i]; break; } } if (pTarget) { CVector<int> vTarget; vTarget.Append(pTarget->GetRoleID()); pAction->SetupSkillBulletTarget(vTarget); m_pRole->SetDirection((pTarget->GetPosition() - m_pRole->GetPosition()).normalize(), 1); } } } else if (g_Engine.pInput->IsKeyDown('4'))//෢ӵ { CAction* pAction = m_pRole->OrceAction("skill02"); if (pAction) { m_pRole->StopMove(); CVector<int> vTarget; } } return 0; } <|endoftext|>
<commit_before>#include "GameProcess.h" #include "Object.h" #include "Engine.h" #include "World.h" #include "App.h" #include "ToolsCamera.h" #include "ControlsApp.h" #include "MathLib.h" #include "Game.h" #include "Editor.h" #include "Input.h" #include "BlueRayUtils.h" using namespace MathLib; CGameProcess::CGameProcess(void) { } CGameProcess::~CGameProcess(void) { } int CGameProcess::Init() { g_Engine.pFileSystem->CacheFilesFormExt("char"); g_Engine.pFileSystem->CacheFilesFormExt("node"); g_Engine.pFileSystem->CacheFilesFormExt("smesh"); g_Engine.pFileSystem->CacheFilesFormExt("sanim"); g_Engine.pWorld->LoadWorld("data/scene/terrain/test/test.world"); //g_Engine.pWorld->LoadWorld("data/scene/terrain/cj/cj.world"); g_Engine.pControls->SetKeyPressFunc(KeyPress); g_Engine.pControls->SetKeyReleaseFunc(KeyRelease); m_pRole = new CFPSRoleLocal(); m_pRole->Init(10001, "data/role/hero/FpsRole/fps.char"); //ؽɫԴ m_pRole->SetActorPosition(vec3(0, 0, 0)); //ýɫʼλáŴΪԭ㣬άϵvec3 m_pSkillSystem = new CSkillSystem(this); m_pCameraBase = new CCameraBase(); m_pCameraBase->SetEnabled(1); g_pSysControl->SetMouseGrab(1); m_pStarControl = new CStarControl(); m_pRayControl = new CRayControl(); return 1; } int CGameProcess::ShutDown() //رϷ { delete m_pRole; delete m_pSkillSystem; delete m_pCameraBase; delete m_pStarControl; delete m_pRayControl; DelAllListen(); return 0; } int CGameProcess::Update() { float ifps = g_Engine.pGame->GetIFps(); if (g_Engine.pInput->IsKeyDown('1')) { CAction* pAction = m_pRole->OrceAction("attack02"); if (pAction) { pAction->SetupSkillThrow(vec3_zero, -1.0f, 2.0f); m_pRole->StopMove(); } } else if (g_Engine.pInput->IsKeyDown('2')) { CAction* pAction = m_pRole->OrceAction("skill01"); if (pAction) { m_pRole->StopMove(); } } else if (g_Engine.pInput->IsKeyDown('3')) { CAction* pAction = m_pRole->OrceAction("skill02"); if (pAction) { m_pRole->StopMove(); CRoleBase* pTarget = NULL; } } for (int i = 0; i < 20; i++) { float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length(); if (l > 5.0f && l < 15.0f) { pTarget = m_vAIList[i]; break; } } return 0; } <commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include "GameProcess.h" #include "Object.h" #include "Engine.h" #include "World.h" #include "App.h" #include "ToolsCamera.h" #include "ControlsApp.h" #include "MathLib.h" #include "Game.h" #include "Editor.h" #include "Input.h" #include "BlueRayUtils.h" using namespace MathLib; CGameProcess::CGameProcess(void) { } CGameProcess::~CGameProcess(void) { } int CGameProcess::Init() { g_Engine.pFileSystem->CacheFilesFormExt("char"); g_Engine.pFileSystem->CacheFilesFormExt("node"); g_Engine.pFileSystem->CacheFilesFormExt("smesh"); g_Engine.pFileSystem->CacheFilesFormExt("sanim"); g_Engine.pWorld->LoadWorld("data/scene/terrain/test/test.world"); //g_Engine.pWorld->LoadWorld("data/scene/terrain/cj/cj.world"); g_Engine.pControls->SetKeyPressFunc(KeyPress); g_Engine.pControls->SetKeyReleaseFunc(KeyRelease); m_pRole = new CFPSRoleLocal(); m_pRole->Init(10001, "data/role/hero/FpsRole/fps.char"); //ؽɫԴ m_pRole->SetActorPosition(vec3(0, 0, 0)); //ýɫʼλáŴΪԭ㣬άϵvec3 m_pSkillSystem = new CSkillSystem(this); m_pCameraBase = new CCameraBase(); m_pCameraBase->SetEnabled(1); g_pSysControl->SetMouseGrab(1); m_pStarControl = new CStarControl(); m_pRayControl = new CRayControl(); return 1; } int CGameProcess::ShutDown() //رϷ { delete m_pRole; delete m_pSkillSystem; delete m_pCameraBase; delete m_pStarControl; delete m_pRayControl; DelAllListen(); return 0; } int CGameProcess::Update() { float ifps = g_Engine.pGame->GetIFps(); if (g_Engine.pInput->IsKeyDown('1')) { CAction* pAction = m_pRole->OrceAction("attack02"); if (pAction) { pAction->SetupSkillThrow(vec3_zero, -1.0f, 2.0f); m_pRole->StopMove(); } } else if (g_Engine.pInput->IsKeyDown('2')) { CAction* pAction = m_pRole->OrceAction("skill01"); if (pAction) { m_pRole->StopMove(); } } else if (g_Engine.pInput->IsKeyDown('3')) { CAction* pAction = m_pRole->OrceAction("skill02"); if (pAction) { m_pRole->StopMove(); CRoleBase* pTarget = NULL; } } for (int i = 0; i < 20; i++) { float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length(); if (l > 5.0f && l < 15.0f) { pTarget = m_vAIList[i]; break; } } if (pTarget) { } return 0; } <|endoftext|>
<commit_before>#include <iostream> #include <list> #include <vector> #include <type_traits> #include <algorithm> using namespace std; #define DEF_SIZE 20 template <typename T> class HashMap { public: HashMap(); //Default coonstructor HashMap(int size); //Define size void insert(const T& data); bool search(const T& data); private: int hash(typename std::enable_if<std::is_arithmetic<T>::value, T>::type data); int size; vector<list<T>> v; }; template<typename T> HashMap<T>::HashMap() :size(DEF_SIZE), v(size) { } template<typename T> HashMap<T>::HashMap(int size) :size(size), v(size) { } template<typename T> void HashMap<T>::insert(const T& data) { int idx = hash(data); v[idx].push_back(data); } template<typename T> bool HashMap<T>::search(const T& data) { int idx = hash(data); auto it = find(v[idx].begin(), v[idx].end(), data); return it != v[idx].end(); //check if it is in the list or not and return the result } template<typename T> int HashMap<T>::hash(typename std::enable_if<std::is_arithmetic<T>::value, T>::type data) { return data % size; } int main() { HashMap<int> hm(10); hm.insert(10); hm.insert(20); hm.insert(30); hm.insert(40); hm.insert(50); hm.insert(60); hm.insert(70); hm.insert(80); hm.insert(90); hm.insert(1); hm.insert(2); hm.insert(3); hm.insert(4); hm.insert(5); hm.insert(6); hm.insert(7); hm.insert(8); hm.insert(9); hm.insert(11); hm.insert(22); hm.insert(33); hm.insert(44); hm.insert(55); hm.insert(66); hm.insert(77); hm.insert(88); hm.insert(99); cout<<"Search for 10: "<<hm.search(10)<<endl; cout<<"Search for 19: "<<hm.search(19)<<endl; cout<<"Search for 99: "<<hm.search(99)<<endl; cout<<"Search for 9: "<<hm.search(9)<<endl; cout<<"Search for 20: "<<hm.search(20)<<endl; cout<<"Search for 101: "<<hm.search(101)<<endl; }<commit_msg>Added remove function<commit_after>#include <iostream> #include <list> #include <vector> #include <type_traits> #include <algorithm> using namespace std; #define DEF_SIZE 20 template <typename T> class HashMap { public: HashMap(); //Default coonstructor HashMap(int size); //Define size void insert(const T& data); bool search(const T& data); void remove(const T& data); private: int hash(typename std::enable_if<std::is_arithmetic<T>::value, T>::type data); int size; vector<list<T>> v; }; template<typename T> HashMap<T>::HashMap() :size(DEF_SIZE), v(size) { } template<typename T> HashMap<T>::HashMap(int size) :size(size), v(size) { } template<typename T> void HashMap<T>::insert(const T& data) { int idx = hash(data); v[idx].push_back(data); } template<typename T> void HashMap<T>::remove(const T& data) { int idx = hash(data); v[idx].remove(data); } template<typename T> bool HashMap<T>::search(const T& data) { int idx = hash(data); auto it = find(v[idx].begin(), v[idx].end(), data); return it != v[idx].end(); //check if it is in the list or not and return the result } template<typename T> int HashMap<T>::hash(typename std::enable_if<std::is_arithmetic<T>::value, T>::type data) { return data % size; } int main() { HashMap<int> hm(10); hm.insert(10); hm.insert(20); hm.insert(30); hm.insert(40); hm.insert(50); hm.insert(60); hm.insert(70); hm.insert(80); hm.insert(90); hm.insert(1); hm.insert(2); hm.insert(3); hm.insert(4); hm.insert(5); hm.insert(6); hm.insert(7); hm.insert(8); hm.insert(9); hm.insert(11); hm.insert(22); hm.insert(33); hm.insert(44); hm.insert(55); hm.insert(66); hm.insert(77); hm.insert(88); hm.insert(99); cout<<"Search for 10: "<<hm.search(10)<<endl; cout<<"Search for 19: "<<hm.search(19)<<endl; cout<<"Search for 99: "<<hm.search(99)<<endl; cout<<"Search for 9: "<<hm.search(9)<<endl; cout<<"Search for 20: "<<hm.search(20)<<endl; cout<<"Search for 101: "<<hm.search(101)<<endl; hm.remove(9); cout<<"Search for 9: "<<hm.search(9)<<endl; }<|endoftext|>
<commit_before>/*- * Copyright (c) 2016 Frederic Culot <culot@FreeBSD.org> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer * in this position and unchanged. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``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 AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdexcept> #include <curses.h> #include "tray.h" namespace portal { namespace gfx { Tray::Tray(const Point& center, int nbSlots) : nbSlots_(nbSlots) { Size paneSize; paneSize.setHeight(1); paneSize.setWidth(nbSlots * 2 + 1); Point panePos; panePos.setX(center.x() - paneSize.width() / 2); panePos.setY(center.y() - 1); pane_ = std::unique_ptr<Pane>(new Pane(paneSize, panePos)); pane_->borders(false); pane_->cursorLineHighlight(false); pane_->cursorLineUnderline(false); draw(); } void Tray::draw() const { pane_->clear(); drawSlots(); pane_->draw(); } void Tray::drawSlots() const { for (int i = 0; i < nbSlots_; ++i) { pane_->print(ACS_DIAMOND, (i == selectedSlotNum_ ? 2 : 0)); pane_->print(' '); } } void Tray::selectSlot(int slotNum) { if (slotNum >= nbSlots_ || slotNum < 0) { throw std::out_of_range("Tray::selectSlot(): invalid slotNum [" + std::to_string(slotNum) + "]"); } selectedSlotNum_ = slotNum; draw(); } void Tray::selectNextSlot() { ++selectedSlotNum_; if (selectedSlotNum_ >= nbSlots_) { selectedSlotNum_ = 0; } draw(); } void Tray::selectPreviousSlot() { --selectedSlotNum_; if (selectedSlotNum_ < 0) { selectedSlotNum_ = nbSlots_ - 1; } draw(); } } } <commit_msg>Use enum instead of magic number<commit_after>/*- * Copyright (c) 2016 Frederic Culot <culot@FreeBSD.org> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer * in this position and unchanged. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``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 AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdexcept> #include <curses.h> #include "tray.h" namespace portal { namespace gfx { Tray::Tray(const Point& center, int nbSlots) : nbSlots_(nbSlots) { Size paneSize; paneSize.setHeight(1); paneSize.setWidth(nbSlots * 2 + 1); Point panePos; panePos.setX(center.x() - paneSize.width() / 2); panePos.setY(center.y() - 1); pane_ = std::unique_ptr<Pane>(new Pane(paneSize, panePos)); pane_->borders(false); pane_->cursorLineHighlight(false); pane_->cursorLineUnderline(false); draw(); } void Tray::draw() const { pane_->clear(); drawSlots(); pane_->draw(); } void Tray::drawSlots() const { for (int i = 0; i < nbSlots_; ++i) { pane_->print(ACS_DIAMOND, (i == selectedSlotNum_ ? Style::Color::magenta : 0)); pane_->print(' '); } } void Tray::selectSlot(int slotNum) { if (slotNum >= nbSlots_ || slotNum < 0) { throw std::out_of_range("Tray::selectSlot(): invalid slotNum [" + std::to_string(slotNum) + "]"); } selectedSlotNum_ = slotNum; draw(); } void Tray::selectNextSlot() { ++selectedSlotNum_; if (selectedSlotNum_ >= nbSlots_) { selectedSlotNum_ = 0; } draw(); } void Tray::selectPreviousSlot() { --selectedSlotNum_; if (selectedSlotNum_ < 0) { selectedSlotNum_ = nbSlots_ - 1; } draw(); } } } <|endoftext|>
<commit_before>//----------------------------------------------------------------------------- // MurmurHash3 was written by Austin Appleby, and is placed in the public // domain. The author hereby disclaims copyright to this source code. #include "MurmurHash3.h" // Note - The x86 and x64 versions do _not_ produce the same results, as the // algorithms are optimized for their respective platforms. You can still // compile and run any of them on any platform, but your performance with the // non-native version will be less than optimal. //----------------------------------------------------------------------------- // Block read - if your platform needs to do endian-swapping or can only // handle aligned reads, do the conversion here FORCE_INLINE uint32_t getblock ( const uint32_t * p, int i ) { return p[i]; } FORCE_INLINE uint64_t getblock ( const uint64_t * p, int i ) { return p[i]; } //----------------------------------------------------------------------------- // Finalization mix - force all bits of a hash block to avalanche FORCE_INLINE uint32_t fmix ( uint32_t h ) { h ^= h >> 16; h *= 0x85ebca6b; h ^= h >> 13; h *= 0xc2b2ae35; h ^= h >> 16; return h; } //---------- FORCE_INLINE uint64_t fmix ( uint64_t k ) { k ^= k >> 33; k *= BIG_CONSTANT(0xff51afd7ed558ccd); k ^= k >> 33; k *= BIG_CONSTANT(0xc4ceb9fe1a85ec53); k ^= k >> 33; return k; } //----------------------------------------------------------------------------- void MurmurHash3_x86_32 ( const void * key, int len, uint32_t seed, void * out ) { const uint8_t * data = (const uint8_t*)key; const int nblocks = len / 4; uint32_t h1 = seed; uint32_t c1 = 0xcc9e2d51; uint32_t c2 = 0x1b873593; //---------- // body const uint32_t * blocks = (const uint32_t *)(data + nblocks*4); for(int i = -nblocks; i; i++) { uint32_t k1 = getblock(blocks,i); k1 *= c1; k1 = ROTL32(k1,15); k1 *= c2; h1 ^= k1; h1 = ROTL32(h1,13); h1 = h1*5+0xe6546b64; } //---------- // tail const uint8_t * tail = (const uint8_t*)(data + nblocks*4); uint32_t k1 = 0; switch(len & 3) { case 3: k1 ^= tail[2] << 16; case 2: k1 ^= tail[1] << 8; case 1: k1 ^= tail[0]; k1 *= c1; k1 = ROTL32(k1,16); k1 *= c2; h1 ^= k1; }; //---------- // finalization h1 ^= len; h1 = fmix(h1); *(uint32_t*)out = h1; } //----------------------------------------------------------------------------- void MurmurHash3_x86_128 ( const void * key, const int len, uint32_t seed, void * out ) { const uint8_t * data = (const uint8_t*)key; const int nblocks = len / 16; uint32_t h1 = seed; uint32_t h2 = seed; uint32_t h3 = seed; uint32_t h4 = seed; uint32_t c1 = 0x239b961b; uint32_t c2 = 0xab0e9789; uint32_t c3 = 0x38b34ae5; uint32_t c4 = 0xa1e38b93; //---------- // body const uint32_t * blocks = (const uint32_t *)(data + nblocks*16); for(int i = -nblocks; i; i++) { uint32_t k1 = getblock(blocks,i*4+0); uint32_t k2 = getblock(blocks,i*4+1); uint32_t k3 = getblock(blocks,i*4+2); uint32_t k4 = getblock(blocks,i*4+3); k1 *= c1; k1 = ROTL32(k1,15); k1 *= c2; h1 ^= k1; h1 = ROTL32(h1,19); h1 += h2; h1 = h1*5+0x561ccd1b; k2 *= c2; k2 = ROTL32(k2,16); k2 *= c3; h2 ^= k2; h2 = ROTL32(h2,17); h2 += h3; h2 = h2*5+0x0bcaa747; k3 *= c3; k3 = ROTL32(k3,17); k3 *= c4; h3 ^= k3; h3 = ROTL32(h3,15); h3 += h4; h3 = h3*5+0x96cd1c35; k4 *= c4; k4 = ROTL32(k4,18); k4 *= c1; h4 ^= k4; h4 = ROTL32(h4,13); h4 += h1; h4 = h4*5+0x32ac3b17; } //---------- // tail const uint8_t * tail = (const uint8_t*)(data + nblocks*16); uint32_t k1 = 0; uint32_t k2 = 0; uint32_t k3 = 0; uint32_t k4 = 0; switch(len & 15) { case 15: k4 ^= tail[14] << 16; case 14: k4 ^= tail[13] << 8; case 13: k4 ^= tail[12] << 0; k4 *= c4; k4 = ROTL32(k4,18); k4 *= c1; h4 ^= k4; case 12: k3 ^= tail[11] << 24; case 11: k3 ^= tail[10] << 16; case 10: k3 ^= tail[ 9] << 8; case 9: k3 ^= tail[ 8] << 0; k3 *= c3; k3 = ROTL32(k3,17); k3 *= c4; h3 ^= k3; case 8: k2 ^= tail[ 7] << 24; case 7: k2 ^= tail[ 6] << 16; case 6: k2 ^= tail[ 5] << 8; case 5: k2 ^= tail[ 4] << 0; k2 *= c2; k2 = ROTL32(k2,16); k2 *= c3; h2 ^= k2; case 4: k1 ^= tail[ 3] << 24; case 3: k1 ^= tail[ 2] << 16; case 2: k1 ^= tail[ 1] << 8; case 1: k1 ^= tail[ 0] << 0; k1 *= c1; k1 = ROTL32(k1,15); k1 *= c2; h1 ^= k1; }; //---------- // finalization h1 ^= len; h2 ^= len; h3 ^= len; h4 ^= len; h1 += h2; h1 += h3; h1 += h4; h2 += h1; h3 += h1; h4 += h1; h1 = fmix(h1); h2 = fmix(h2); h3 = fmix(h3); h4 = fmix(h4); h1 += h2; h1 += h3; h1 += h4; h2 += h1; h3 += h1; h4 += h1; ((uint32_t*)out)[0] = h1; ((uint32_t*)out)[1] = h2; ((uint32_t*)out)[2] = h3; ((uint32_t*)out)[3] = h4; } //----------------------------------------------------------------------------- void MurmurHash3_x64_128 ( const void * key, const int len, const uint32_t seed, void * out ) { const uint8_t * data = (const uint8_t*)key; const int nblocks = len / 16; uint64_t h1 = seed; uint64_t h2 = seed; uint64_t c1 = BIG_CONSTANT(0x87c37b91114253d5); uint64_t c2 = BIG_CONSTANT(0x4cf5ad432745937f); //---------- // body const uint64_t * blocks = (const uint64_t *)(data); for(int i = 0; i < nblocks; i++) { uint64_t k1 = getblock(blocks,i*2+0); uint64_t k2 = getblock(blocks,i*2+1); k1 *= c1; k1 = ROTL64(k1,31); k1 *= c2; h1 ^= k1; h1 = ROTL64(h1,27); h1 += h2; h1 = h1*5+0x52dce729; k2 *= c2; k2 = ROTL64(k2,33); k2 *= c1; h2 ^= k2; h2 = ROTL64(h2,31); h2 += h1; h2 = h2*5+0x38495ab5; } //---------- // tail const uint8_t * tail = (const uint8_t*)(data + nblocks*16); uint64_t k1 = 0; uint64_t k2 = 0; switch(len & 15) { case 15: k2 ^= uint64_t(tail[14]) << 48; case 14: k2 ^= uint64_t(tail[13]) << 40; case 13: k2 ^= uint64_t(tail[12]) << 32; case 12: k2 ^= uint64_t(tail[11]) << 24; case 11: k2 ^= uint64_t(tail[10]) << 16; case 10: k2 ^= uint64_t(tail[ 9]) << 8; case 9: k2 ^= uint64_t(tail[ 8]) << 0; k2 *= c2; k2 = ROTL64(k2,33); k2 *= c1; h2 ^= k2; case 8: k1 ^= uint64_t(tail[ 7]) << 56; case 7: k1 ^= uint64_t(tail[ 6]) << 48; case 6: k1 ^= uint64_t(tail[ 5]) << 40; case 5: k1 ^= uint64_t(tail[ 4]) << 32; case 4: k1 ^= uint64_t(tail[ 3]) << 24; case 3: k1 ^= uint64_t(tail[ 2]) << 16; case 2: k1 ^= uint64_t(tail[ 1]) << 8; case 1: k1 ^= uint64_t(tail[ 0]) << 0; k1 *= c1; k1 = ROTL64(k1,29); k1 *= c2; h1 ^= k1; }; //---------- // finalization h1 ^= len; h2 ^= len; h1 += h2; h2 += h1; h1 = fmix(h1); h2 = fmix(h2); h1 += h2; h2 += h1; ((uint64_t*)out)[0] = h1; ((uint64_t*)out)[1] = h2; } //----------------------------------------------------------------------------- <commit_msg>Make MurmurHash3.cpp compile standalone on GCC<commit_after>//----------------------------------------------------------------------------- // MurmurHash3 was written by Austin Appleby, and is placed in the public // domain. The author hereby disclaims copyright to this source code. // Note - The x86 and x64 versions do _not_ produce the same results, as the // algorithms are optimized for their respective platforms. You can still // compile and run any of them on any platform, but your performance with the // non-native version will be less than optimal. //----------------------------------------------------------------------------- // Platform-specific functions and macros // Microsoft Visual Studio #if defined(_MSC_VER) #define FORCE_INLINE __forceinline #include <stdlib.h> #define ROTL32(x,y) _rotl(x,y) #define ROTL64(x,y) _rotl64(x,y) #define BIG_CONSTANT(x) (x) // Other compilers #else // defined(_MSC_VER) #include <stdint.h> #define FORCE_INLINE __attribute__((always_inline)) inline uint32_t rotl32 ( uint32_t x, int8_t r ) { return (x << r) | (x >> (32 - r)); } inline uint64_t rotl64 ( uint64_t x, int8_t r ) { return (x << r) | (x >> (64 - r)); } #define ROTL32(x,y) rotl32(x,y) #define ROTL64(x,y) rotl64(x,y) #define BIG_CONSTANT(x) (x##LLU) #endif // !defined(_MSC_VER) //----------------------------------------------------------------------------- // Block read - if your platform needs to do endian-swapping or can only // handle aligned reads, do the conversion here FORCE_INLINE uint32_t getblock ( const uint32_t * p, int i ) { return p[i]; } FORCE_INLINE uint64_t getblock ( const uint64_t * p, int i ) { return p[i]; } //----------------------------------------------------------------------------- // Finalization mix - force all bits of a hash block to avalanche FORCE_INLINE uint32_t fmix ( uint32_t h ) { h ^= h >> 16; h *= 0x85ebca6b; h ^= h >> 13; h *= 0xc2b2ae35; h ^= h >> 16; return h; } //---------- FORCE_INLINE uint64_t fmix ( uint64_t k ) { k ^= k >> 33; k *= BIG_CONSTANT(0xff51afd7ed558ccd); k ^= k >> 33; k *= BIG_CONSTANT(0xc4ceb9fe1a85ec53); k ^= k >> 33; return k; } //----------------------------------------------------------------------------- void MurmurHash3_x86_32 ( const void * key, int len, uint32_t seed, void * out ) { const uint8_t * data = (const uint8_t*)key; const int nblocks = len / 4; uint32_t h1 = seed; uint32_t c1 = 0xcc9e2d51; uint32_t c2 = 0x1b873593; //---------- // body const uint32_t * blocks = (const uint32_t *)(data + nblocks*4); for(int i = -nblocks; i; i++) { uint32_t k1 = getblock(blocks,i); k1 *= c1; k1 = ROTL32(k1,15); k1 *= c2; h1 ^= k1; h1 = ROTL32(h1,13); h1 = h1*5+0xe6546b64; } //---------- // tail const uint8_t * tail = (const uint8_t*)(data + nblocks*4); uint32_t k1 = 0; switch(len & 3) { case 3: k1 ^= tail[2] << 16; case 2: k1 ^= tail[1] << 8; case 1: k1 ^= tail[0]; k1 *= c1; k1 = ROTL32(k1,16); k1 *= c2; h1 ^= k1; }; //---------- // finalization h1 ^= len; h1 = fmix(h1); *(uint32_t*)out = h1; } //----------------------------------------------------------------------------- void MurmurHash3_x86_128 ( const void * key, const int len, uint32_t seed, void * out ) { const uint8_t * data = (const uint8_t*)key; const int nblocks = len / 16; uint32_t h1 = seed; uint32_t h2 = seed; uint32_t h3 = seed; uint32_t h4 = seed; uint32_t c1 = 0x239b961b; uint32_t c2 = 0xab0e9789; uint32_t c3 = 0x38b34ae5; uint32_t c4 = 0xa1e38b93; //---------- // body const uint32_t * blocks = (const uint32_t *)(data + nblocks*16); for(int i = -nblocks; i; i++) { uint32_t k1 = getblock(blocks,i*4+0); uint32_t k2 = getblock(blocks,i*4+1); uint32_t k3 = getblock(blocks,i*4+2); uint32_t k4 = getblock(blocks,i*4+3); k1 *= c1; k1 = ROTL32(k1,15); k1 *= c2; h1 ^= k1; h1 = ROTL32(h1,19); h1 += h2; h1 = h1*5+0x561ccd1b; k2 *= c2; k2 = ROTL32(k2,16); k2 *= c3; h2 ^= k2; h2 = ROTL32(h2,17); h2 += h3; h2 = h2*5+0x0bcaa747; k3 *= c3; k3 = ROTL32(k3,17); k3 *= c4; h3 ^= k3; h3 = ROTL32(h3,15); h3 += h4; h3 = h3*5+0x96cd1c35; k4 *= c4; k4 = ROTL32(k4,18); k4 *= c1; h4 ^= k4; h4 = ROTL32(h4,13); h4 += h1; h4 = h4*5+0x32ac3b17; } //---------- // tail const uint8_t * tail = (const uint8_t*)(data + nblocks*16); uint32_t k1 = 0; uint32_t k2 = 0; uint32_t k3 = 0; uint32_t k4 = 0; switch(len & 15) { case 15: k4 ^= tail[14] << 16; case 14: k4 ^= tail[13] << 8; case 13: k4 ^= tail[12] << 0; k4 *= c4; k4 = ROTL32(k4,18); k4 *= c1; h4 ^= k4; case 12: k3 ^= tail[11] << 24; case 11: k3 ^= tail[10] << 16; case 10: k3 ^= tail[ 9] << 8; case 9: k3 ^= tail[ 8] << 0; k3 *= c3; k3 = ROTL32(k3,17); k3 *= c4; h3 ^= k3; case 8: k2 ^= tail[ 7] << 24; case 7: k2 ^= tail[ 6] << 16; case 6: k2 ^= tail[ 5] << 8; case 5: k2 ^= tail[ 4] << 0; k2 *= c2; k2 = ROTL32(k2,16); k2 *= c3; h2 ^= k2; case 4: k1 ^= tail[ 3] << 24; case 3: k1 ^= tail[ 2] << 16; case 2: k1 ^= tail[ 1] << 8; case 1: k1 ^= tail[ 0] << 0; k1 *= c1; k1 = ROTL32(k1,15); k1 *= c2; h1 ^= k1; }; //---------- // finalization h1 ^= len; h2 ^= len; h3 ^= len; h4 ^= len; h1 += h2; h1 += h3; h1 += h4; h2 += h1; h3 += h1; h4 += h1; h1 = fmix(h1); h2 = fmix(h2); h3 = fmix(h3); h4 = fmix(h4); h1 += h2; h1 += h3; h1 += h4; h2 += h1; h3 += h1; h4 += h1; ((uint32_t*)out)[0] = h1; ((uint32_t*)out)[1] = h2; ((uint32_t*)out)[2] = h3; ((uint32_t*)out)[3] = h4; } //----------------------------------------------------------------------------- void MurmurHash3_x64_128 ( const void * key, const int len, const uint32_t seed, void * out ) { const uint8_t * data = (const uint8_t*)key; const int nblocks = len / 16; uint64_t h1 = seed; uint64_t h2 = seed; uint64_t c1 = BIG_CONSTANT(0x87c37b91114253d5); uint64_t c2 = BIG_CONSTANT(0x4cf5ad432745937f); //---------- // body const uint64_t * blocks = (const uint64_t *)(data); for(int i = 0; i < nblocks; i++) { uint64_t k1 = getblock(blocks,i*2+0); uint64_t k2 = getblock(blocks,i*2+1); k1 *= c1; k1 = ROTL64(k1,31); k1 *= c2; h1 ^= k1; h1 = ROTL64(h1,27); h1 += h2; h1 = h1*5+0x52dce729; k2 *= c2; k2 = ROTL64(k2,33); k2 *= c1; h2 ^= k2; h2 = ROTL64(h2,31); h2 += h1; h2 = h2*5+0x38495ab5; } //---------- // tail const uint8_t * tail = (const uint8_t*)(data + nblocks*16); uint64_t k1 = 0; uint64_t k2 = 0; switch(len & 15) { case 15: k2 ^= uint64_t(tail[14]) << 48; case 14: k2 ^= uint64_t(tail[13]) << 40; case 13: k2 ^= uint64_t(tail[12]) << 32; case 12: k2 ^= uint64_t(tail[11]) << 24; case 11: k2 ^= uint64_t(tail[10]) << 16; case 10: k2 ^= uint64_t(tail[ 9]) << 8; case 9: k2 ^= uint64_t(tail[ 8]) << 0; k2 *= c2; k2 = ROTL64(k2,33); k2 *= c1; h2 ^= k2; case 8: k1 ^= uint64_t(tail[ 7]) << 56; case 7: k1 ^= uint64_t(tail[ 6]) << 48; case 6: k1 ^= uint64_t(tail[ 5]) << 40; case 5: k1 ^= uint64_t(tail[ 4]) << 32; case 4: k1 ^= uint64_t(tail[ 3]) << 24; case 3: k1 ^= uint64_t(tail[ 2]) << 16; case 2: k1 ^= uint64_t(tail[ 1]) << 8; case 1: k1 ^= uint64_t(tail[ 0]) << 0; k1 *= c1; k1 = ROTL64(k1,29); k1 *= c2; h1 ^= k1; }; //---------- // finalization h1 ^= len; h2 ^= len; h1 += h2; h2 += h1; h1 = fmix(h1); h2 = fmix(h2); h1 += h2; h2 += h1; ((uint64_t*)out)[0] = h1; ((uint64_t*)out)[1] = h2; } //----------------------------------------------------------------------------- <|endoftext|>
<commit_before>/* * This file is part of openfx-arena <https://github.com/olear/openfx-arena>, * Copyright (C) 2015, 2016 FxArena DA * Copyright (C) 2016 INRIA * * openfx-arena is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. * * openfx-arena is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with openfx-arena. If not, see <http://www.gnu.org/licenses/gpl-2.0.html> */ #include "ofxsMacros.h" #include "ofxsImageEffect.h" #include "openCLUtilities.hpp" #include <cmath> #define kPluginName "SwirlCL" #define kPluginGrouping "Extra/Distort" #define kPluginIdentifier "fr.inria.openfx.SwirlCL" #define kPluginDescription "OpenCL Swirl Filter" #define kPluginVersionMajor 1 #define kPluginVersionMinor 0 #define kSupportsTiles 0 #define kSupportsMultiResolution 1 #define kSupportsRenderScale 1 #define kRenderThreadSafety eRenderFullySafe #define kHostFrameThreading false #define kHostMasking true #define kHostMixing true #define kParamAmount "amount" #define kParamAmountLabel "Amount" #define kParamAmountHint "Adjust swirl amount" #define kParamAmountDefault 3 #define kParamRadius "radius" #define kParamRadiusLabel "Radius" #define kParamRadiusHint "Adjust swirl radius" #define kParamRadiusDefault 100 #define kParamKernel \ "const sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE;\n" \ "\n" \ "float clampRGB( float x ) {\n" \ " return x > 1.f ? 1.f\n" \ " : x < 0.f ? 0.f\n" \ " : x;\n" \ "}\n" \ "\n" \ "kernel void swirl (read_only image2d_t in, write_only image2d_t out/*, int centerW, int centerH*/, double amount, double radius) {\n" \ "\n" \ " int2 d = get_image_dim(in);\n" \ " int2 pos = (int2)(get_global_id(0),get_global_id(1));\n" \ " // get from plugin\n" \ " int centerW=d.x/2;\n" \ " int centerH=d.y/2;\n" \ " int x = pos.x - centerW;\n" \ " int y = pos.y - centerH;\n" \ "\n" \ " float a = amount*exp(-(x*x+y*y)/(radius*radius));\n" \ " float u = (cos(a)*x + sin(a)*y);\n" \ " float v = (-sin(a)*x + cos(a)*y);\n" \ "\n" \ " u += (float)centerW;\n" \ " v += (float)centerH;\n" \ "\n" \ " float4 fp = read_imagef(in,sampler,(int2)((int)u,(int)v));\n" \ "\n" \ " // Interpolation\n" \ " int2 p11 = (int2)(floor(u),floor(v));\n" \ " float dx = u-(float)p11.x;\n" \ " float dy = v-(float)p11.y;\n" \ "\n" \ " float4 C[5];\n" \ " float4 d0,d2,d3,a0,a1,a2,a3;\n" \ "\n" \ " for (int i = 0; i < 4; i++) {\n" \ " d0 = read_imagef(in,sampler,(int2)((int)u-1,(int)v+i)) - read_imagef(in,sampler,(int2)((int)u,(int)v+i));\n" \ " d2 = read_imagef(in,sampler,(int2)((int)u+1,(int)v+i)) - read_imagef(in,sampler,(int2)((int)u,(int)v+i));\n" \ " d3 = read_imagef(in,sampler,(int2)((int)u+2,(int)v+i)) - read_imagef(in,sampler,(int2)((int)u,(int)v+i));\n" \ " a0 = read_imagef(in,sampler,(int2)((int)u, (int)v+i));\n" \ " a1 = -1.0/3*d0 + d2 - 1.0/6*d3;\n" \ " a2 = 1.0/2*d0 + 1.0/2*d2;\n" \ " a3 = -1.0/6*d0 - 1.0/2*d2 + 1.0/6*d3;\n" \ "\n" \ " C[i] = a0 + a1*dx + a2*dx*dx + a3*dx*dx*dx;\n" \ " }\n" \ "\n" \ " d0 = C[0]-C[1];\n" \ " d2 = C[2]-C[1];\n" \ " d3 = C[3]-C[1];\n" \ " a0 = C[1];\n" \ " a1 = -1.0/3*d0 + d2 -1.0/6*d3;\n" \ " a2 = 1.0/2*d0 + 1.0/2*d2;\n" \ " a3 = -1.0/6*d0 - 1.0/2*d2 + 1.0/6*d3;\n" \ " fp = (float4)(a0 + a1*dy + a2*dy*dy + a3*dy*dy*dy);\n" \ " fp.x = clampRGB(fp.x);\n" \ " fp.y = clampRGB(fp.y);\n" \ " fp.z = clampRGB(fp.z);\n" \ " fp.w = clampRGB(fp.w);\n" \ "\n" \ " write_imagef(out,(int2)(pos.x,pos.y),fp);\n" \ "}" using namespace OFX; class SwirlCLPlugin : public ImageEffect { public: SwirlCLPlugin(OfxImageEffectHandle handle); virtual ~SwirlCLPlugin(); virtual void render(const RenderArguments &args) OVERRIDE FINAL; virtual bool getRegionOfDefinition(const RegionOfDefinitionArguments &args, OfxRectD &rod) OVERRIDE FINAL; private: Clip *dstClip_; Clip *srcClip_; cl::Context context_; cl::Program program_; DoubleParam *amount_; DoubleParam *radius_; }; SwirlCLPlugin::SwirlCLPlugin(OfxImageEffectHandle handle) : ImageEffect(handle) , dstClip_(0) , srcClip_(0) , amount_(0) , radius_(0) { dstClip_ = fetchClip(kOfxImageEffectOutputClipName); assert(dstClip_ && dstClip_->getPixelComponents() == ePixelComponentRGBA); srcClip_ = fetchClip(kOfxImageEffectSimpleSourceClipName); assert(srcClip_ && srcClip_->getPixelComponents() == ePixelComponentRGBA); amount_ = fetchDoubleParam(kParamAmount); radius_ = fetchDoubleParam(kParamRadius); assert(amount_ && radius_); // setup opencl context and build kernel context_ = createCLContext(); program_ = buildProgramFromString(context_, kParamKernel); } SwirlCLPlugin::~SwirlCLPlugin() { } void SwirlCLPlugin::render(const RenderArguments &args) { // render scale if (!kSupportsRenderScale && (args.renderScale.x != 1. || args.renderScale.y != 1.)) { throwSuiteStatusException(kOfxStatFailed); return; } // get src clip if (!srcClip_) { throwSuiteStatusException(kOfxStatFailed); return; } assert(srcClip_); std::auto_ptr<const Image> srcImg(srcClip_->fetchImage(args.time)); OfxRectI srcRod,srcBounds; if (srcImg.get()) { srcRod = srcImg->getRegionOfDefinition(); srcBounds = srcImg->getBounds(); if (srcImg->getRenderScale().x != args.renderScale.x || srcImg->getRenderScale().y != args.renderScale.y || srcImg->getField() != args.fieldToRender) { setPersistentMessage(Message::eMessageError, "", "OFX Host gave image with wrong scale or field properties"); throwSuiteStatusException(kOfxStatFailed); return; } } else { throwSuiteStatusException(kOfxStatFailed); return; } // get dest clip if (!dstClip_) { throwSuiteStatusException(kOfxStatFailed); return; } assert(dstClip_); std::auto_ptr<Image> dstImg(dstClip_->fetchImage(args.time)); if (!dstImg.get()) { throwSuiteStatusException(kOfxStatFailed); return; } if (dstImg->getRenderScale().x != args.renderScale.x || dstImg->getRenderScale().y != args.renderScale.y || dstImg->getField() != args.fieldToRender) { setPersistentMessage(Message::eMessageError, "", "OFX Host gave image with wrong scale or field properties"); throwSuiteStatusException(kOfxStatFailed); return; } // get bit depth BitDepthEnum dstBitDepth = dstImg->getPixelDepth(); if (dstBitDepth != eBitDepthFloat || (srcImg.get() && (dstBitDepth != srcImg->getPixelDepth()))) { throwSuiteStatusException(kOfxStatErrFormat); return; } // get pixel component PixelComponentEnum dstComponents = dstImg->getPixelComponents(); if (dstComponents != ePixelComponentRGBA|| (srcImg.get() && (dstComponents != srcImg->getPixelComponents()))) { throwSuiteStatusException(kOfxStatErrFormat); return; } // are we in the image bounds? OfxRectI dstBounds = dstImg->getBounds(); if(args.renderWindow.x1 < dstBounds.x1 || args.renderWindow.x1 >= dstBounds.x2 || args.renderWindow.y1 < dstBounds.y1 || args.renderWindow.y1 >= dstBounds.y2 || args.renderWindow.x2 <= dstBounds.x1 || args.renderWindow.x2 > dstBounds.x2 || args.renderWindow.y2 <= dstBounds.y1 || args.renderWindow.y2 > dstBounds.y2) { throwSuiteStatusException(kOfxStatErrValue); return; } // get params double amount, radius; amount_->getValueAtTime(args.time, amount); radius_->getValueAtTime(args.time, radius); // setup kernel cl::Kernel kernel(program_, "swirl"); // kernel arg 0 & 1 is reserved for input & output kernel.setArg(2, std::floor(amount * args.renderScale.x + 0.5)); kernel.setArg(3, std::floor(radius * args.renderScale.x + 0.5)); // get available devices VECTOR_CLASS<cl::Device> devices = context_.getInfo<CL_CONTEXT_DEVICES>(); // render renderCL((float*)dstImg->getPixelData(), (float*)srcImg->getPixelData(), args.renderWindow.x2 - args.renderWindow.x1, args.renderWindow.y2 - args.renderWindow.y1, context_, devices[0], kernel); } bool SwirlCLPlugin::getRegionOfDefinition(const RegionOfDefinitionArguments &args, OfxRectD &rod) { if (!kSupportsRenderScale && (args.renderScale.x != 1. || args.renderScale.y != 1.)) { throwSuiteStatusException(kOfxStatFailed); return false; } if (srcClip_ && srcClip_->isConnected()) { rod = srcClip_->getRegionOfDefinition(args.time); } else { rod.x1 = rod.y1 = kOfxFlagInfiniteMin; rod.x2 = rod.y2 = kOfxFlagInfiniteMax; } return true; } mDeclarePluginFactory(SwirlCLPluginFactory, {}, {}); /** @brief The basic describe function, passed a plugin descriptor */ void SwirlCLPluginFactory::describe(ImageEffectDescriptor &desc) { // basic labels desc.setLabel(kPluginName); desc.setPluginGrouping(kPluginGrouping); desc.setPluginDescription(kPluginDescription); // add the supported contexts desc.addSupportedContext(eContextGeneral); desc.addSupportedContext(eContextFilter); // add supported pixel depths desc.addSupportedBitDepth(eBitDepthFloat); // add other desc.setSupportsTiles(kSupportsTiles); desc.setSupportsMultiResolution(kSupportsMultiResolution); desc.setRenderThreadSafety(kRenderThreadSafety); desc.setHostFrameThreading(kHostFrameThreading); desc.setHostMaskingEnabled(kHostMasking); desc.setHostMixingEnabled(kHostMixing); } /** @brief The describe in context function, passed a plugin descriptor and a context */ void SwirlCLPluginFactory::describeInContext(ImageEffectDescriptor &desc, ContextEnum /*context*/) { // create the mandated source clip ClipDescriptor *srcClip = desc.defineClip(kOfxImageEffectSimpleSourceClipName); srcClip->addSupportedComponent(ePixelComponentRGBA); srcClip->setTemporalClipAccess(false); srcClip->setSupportsTiles(kSupportsTiles); srcClip->setIsMask(false); // create the mandated output clip ClipDescriptor *dstClip = desc.defineClip(kOfxImageEffectOutputClipName); dstClip->addSupportedComponent(ePixelComponentRGBA); dstClip->setSupportsTiles(kSupportsTiles); // create param(s) PageParamDescriptor *page = desc.definePageParam(kPluginName); { DoubleParamDescriptor *param = desc.defineDoubleParam(kParamAmount); param->setLabel(kParamAmountLabel); param->setHint(kParamAmountHint); param->setRange(-360, 360); param->setDisplayRange(-10, 10); param->setDefault(kParamAmountDefault); page->addChild(*param); } { DoubleParamDescriptor *param = desc.defineDoubleParam(kParamRadius); param->setLabel(kParamRadiusLabel); param->setHint(kParamRadiusHint); param->setRange(0, 10000); param->setDisplayRange(0, 1000); param->setDefault(kParamRadiusDefault); page->addChild(*param); } } /** @brief The create instance function, the plugin must return an object derived from the \ref ImageEffect class */ ImageEffect* SwirlCLPluginFactory::createInstance(OfxImageEffectHandle handle, ContextEnum /*context*/) { return new SwirlCLPlugin(handle); } static SwirlCLPluginFactory p(kPluginIdentifier, kPluginVersionMajor, kPluginVersionMinor); mRegisterPluginFactoryInstance(p) <commit_msg>SwirlCL: added swirl center support<commit_after>/* * This file is part of openfx-arena <https://github.com/olear/openfx-arena>, * Copyright (C) 2015, 2016 FxArena DA * Copyright (C) 2016 INRIA * * openfx-arena is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. * * openfx-arena is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with openfx-arena. If not, see <http://www.gnu.org/licenses/gpl-2.0.html> */ #include "ofxsPositionInteract.h" #include "ofxsMacros.h" #include "ofxsImageEffect.h" #include "openCLUtilities.hpp" #include <cmath> #define kPluginName "SwirlCL" #define kPluginGrouping "Extra/Distort" #define kPluginIdentifier "fr.inria.openfx.SwirlCL" #define kPluginDescription "OpenCL Swirl Filter" #define kPluginVersionMajor 1 #define kPluginVersionMinor 0 #define kSupportsTiles 0 #define kSupportsMultiResolution 1 #define kSupportsRenderScale 1 #define kRenderThreadSafety eRenderFullySafe #define kHostFrameThreading false #define kHostMasking true #define kHostMixing true #define kParamAmount "amount" #define kParamAmountLabel "Amount" #define kParamAmountHint "Adjust swirl amount" #define kParamAmountDefault 3 #define kParamRadius "radius" #define kParamRadiusLabel "Radius" #define kParamRadiusHint "Adjust swirl radius" #define kParamRadiusDefault 100 #define kParamPosition "center" #define kParamPositionLabel "Center" #define kParamPositionHint "Swirl center" #define kParamKernel \ "const sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE;\n" \ "\n" \ "float clampRGB( float x ) {\n" \ " return x > 1.f ? 1.f\n" \ " : x < 0.f ? 0.f\n" \ " : x;\n" \ "}\n" \ "\n" \ "kernel void swirl (read_only image2d_t in, write_only image2d_t out, double centerW, double centerH, double amount, double radius) {\n" \ "\n" \ " int2 d = get_image_dim(in);\n" \ " int2 pos = (int2)(get_global_id(0),get_global_id(1));\n" \ " int x = pos.x - centerW;\n" \ " int y = pos.y - centerH;\n" \ "\n" \ " float a = amount*exp(-(x*x+y*y)/(radius*radius));\n" \ " float u = (cos(a)*x + sin(a)*y);\n" \ " float v = (-sin(a)*x + cos(a)*y);\n" \ "\n" \ " u += (float)centerW;\n" \ " v += (float)centerH;\n" \ "\n" \ " float4 fp = read_imagef(in,sampler,(int2)((int)u,(int)v));\n" \ "\n" \ " // Interpolation\n" \ " int2 p11 = (int2)(floor(u),floor(v));\n" \ " float dx = u-(float)p11.x;\n" \ " float dy = v-(float)p11.y;\n" \ "\n" \ " float4 C[5];\n" \ " float4 d0,d2,d3,a0,a1,a2,a3;\n" \ "\n" \ " for (int i = 0; i < 4; i++) {\n" \ " d0 = read_imagef(in,sampler,(int2)((int)u-1,(int)v+i)) - read_imagef(in,sampler,(int2)((int)u,(int)v+i));\n" \ " d2 = read_imagef(in,sampler,(int2)((int)u+1,(int)v+i)) - read_imagef(in,sampler,(int2)((int)u,(int)v+i));\n" \ " d3 = read_imagef(in,sampler,(int2)((int)u+2,(int)v+i)) - read_imagef(in,sampler,(int2)((int)u,(int)v+i));\n" \ " a0 = read_imagef(in,sampler,(int2)((int)u, (int)v+i));\n" \ " a1 = -1.0/3*d0 + d2 - 1.0/6*d3;\n" \ " a2 = 1.0/2*d0 + 1.0/2*d2;\n" \ " a3 = -1.0/6*d0 - 1.0/2*d2 + 1.0/6*d3;\n" \ "\n" \ " C[i] = a0 + a1*dx + a2*dx*dx + a3*dx*dx*dx;\n" \ " }\n" \ "\n" \ " d0 = C[0]-C[1];\n" \ " d2 = C[2]-C[1];\n" \ " d3 = C[3]-C[1];\n" \ " a0 = C[1];\n" \ " a1 = -1.0/3*d0 + d2 -1.0/6*d3;\n" \ " a2 = 1.0/2*d0 + 1.0/2*d2;\n" \ " a3 = -1.0/6*d0 - 1.0/2*d2 + 1.0/6*d3;\n" \ " fp = (float4)(a0 + a1*dy + a2*dy*dy + a3*dy*dy*dy);\n" \ " fp.x = clampRGB(fp.x);\n" \ " fp.y = clampRGB(fp.y);\n" \ " fp.z = clampRGB(fp.z);\n" \ " fp.w = clampRGB(fp.w);\n" \ "\n" \ " write_imagef(out,(int2)(pos.x,pos.y),fp);\n" \ "}" using namespace OFX; class SwirlCLPlugin : public ImageEffect { public: SwirlCLPlugin(OfxImageEffectHandle handle); virtual ~SwirlCLPlugin(); virtual void render(const RenderArguments &args) OVERRIDE FINAL; virtual bool getRegionOfDefinition(const RegionOfDefinitionArguments &args, OfxRectD &rod) OVERRIDE FINAL; private: Clip *dstClip_; Clip *srcClip_; cl::Context context_; cl::Program program_; DoubleParam *amount_; DoubleParam *radius_; Double2DParam *position_; }; SwirlCLPlugin::SwirlCLPlugin(OfxImageEffectHandle handle) : ImageEffect(handle) , dstClip_(0) , srcClip_(0) , amount_(0) , radius_(0) { dstClip_ = fetchClip(kOfxImageEffectOutputClipName); assert(dstClip_ && dstClip_->getPixelComponents() == ePixelComponentRGBA); srcClip_ = fetchClip(kOfxImageEffectSimpleSourceClipName); assert(srcClip_ && srcClip_->getPixelComponents() == ePixelComponentRGBA); amount_ = fetchDoubleParam(kParamAmount); radius_ = fetchDoubleParam(kParamRadius); position_ = fetchDouble2DParam(kParamPosition); assert(amount_ && radius_ && position_); // setup opencl context and build kernel context_ = createCLContext(); program_ = buildProgramFromString(context_, kParamKernel); } SwirlCLPlugin::~SwirlCLPlugin() { } void SwirlCLPlugin::render(const RenderArguments &args) { // render scale if (!kSupportsRenderScale && (args.renderScale.x != 1. || args.renderScale.y != 1.)) { throwSuiteStatusException(kOfxStatFailed); return; } // get src clip if (!srcClip_) { throwSuiteStatusException(kOfxStatFailed); return; } assert(srcClip_); std::auto_ptr<const Image> srcImg(srcClip_->fetchImage(args.time)); OfxRectI srcRod,srcBounds; if (srcImg.get()) { srcRod = srcImg->getRegionOfDefinition(); srcBounds = srcImg->getBounds(); if (srcImg->getRenderScale().x != args.renderScale.x || srcImg->getRenderScale().y != args.renderScale.y || srcImg->getField() != args.fieldToRender) { setPersistentMessage(Message::eMessageError, "", "OFX Host gave image with wrong scale or field properties"); throwSuiteStatusException(kOfxStatFailed); return; } } else { throwSuiteStatusException(kOfxStatFailed); return; } // get dest clip if (!dstClip_) { throwSuiteStatusException(kOfxStatFailed); return; } assert(dstClip_); std::auto_ptr<Image> dstImg(dstClip_->fetchImage(args.time)); if (!dstImg.get()) { throwSuiteStatusException(kOfxStatFailed); return; } if (dstImg->getRenderScale().x != args.renderScale.x || dstImg->getRenderScale().y != args.renderScale.y || dstImg->getField() != args.fieldToRender) { setPersistentMessage(Message::eMessageError, "", "OFX Host gave image with wrong scale or field properties"); throwSuiteStatusException(kOfxStatFailed); return; } // get bit depth BitDepthEnum dstBitDepth = dstImg->getPixelDepth(); if (dstBitDepth != eBitDepthFloat || (srcImg.get() && (dstBitDepth != srcImg->getPixelDepth()))) { throwSuiteStatusException(kOfxStatErrFormat); return; } // get pixel component PixelComponentEnum dstComponents = dstImg->getPixelComponents(); if (dstComponents != ePixelComponentRGBA|| (srcImg.get() && (dstComponents != srcImg->getPixelComponents()))) { throwSuiteStatusException(kOfxStatErrFormat); return; } // are we in the image bounds? OfxRectI dstBounds = dstImg->getBounds(); if(args.renderWindow.x1 < dstBounds.x1 || args.renderWindow.x1 >= dstBounds.x2 || args.renderWindow.y1 < dstBounds.y1 || args.renderWindow.y1 >= dstBounds.y2 || args.renderWindow.x2 <= dstBounds.x1 || args.renderWindow.x2 > dstBounds.x2 || args.renderWindow.y2 <= dstBounds.y1 || args.renderWindow.y2 > dstBounds.y2) { throwSuiteStatusException(kOfxStatErrValue); return; } // get params double amount, radius, x, y; amount_->getValueAtTime(args.time, amount); radius_->getValueAtTime(args.time, radius); position_->getValueAtTime(args.time, x, y); // Position x y double ypos = y*args.renderScale.y; double xpos = x*args.renderScale.x; // setup kernel cl::Kernel kernel(program_, "swirl"); // kernel arg 0 & 1 is reserved for input & output kernel.setArg(2, xpos); kernel.setArg(3, ypos); kernel.setArg(4, amount); kernel.setArg(5, std::floor(radius * args.renderScale.x + 0.5)); // get available devices VECTOR_CLASS<cl::Device> devices = context_.getInfo<CL_CONTEXT_DEVICES>(); // render renderCL((float*)dstImg->getPixelData(), (float*)srcImg->getPixelData(), args.renderWindow.x2 - args.renderWindow.x1, args.renderWindow.y2 - args.renderWindow.y1, context_, devices[0], kernel); } bool SwirlCLPlugin::getRegionOfDefinition(const RegionOfDefinitionArguments &args, OfxRectD &rod) { if (!kSupportsRenderScale && (args.renderScale.x != 1. || args.renderScale.y != 1.)) { throwSuiteStatusException(kOfxStatFailed); return false; } if (srcClip_ && srcClip_->isConnected()) { rod = srcClip_->getRegionOfDefinition(args.time); } else { rod.x1 = rod.y1 = kOfxFlagInfiniteMin; rod.x2 = rod.y2 = kOfxFlagInfiniteMax; } return true; } mDeclarePluginFactory(SwirlCLPluginFactory, {}, {}); /** @brief The basic describe function, passed a plugin descriptor */ void SwirlCLPluginFactory::describe(ImageEffectDescriptor &desc) { // basic labels desc.setLabel(kPluginName); desc.setPluginGrouping(kPluginGrouping); desc.setPluginDescription(kPluginDescription); // add the supported contexts desc.addSupportedContext(eContextGeneral); desc.addSupportedContext(eContextFilter); // add supported pixel depths desc.addSupportedBitDepth(eBitDepthFloat); // add other desc.setSupportsTiles(kSupportsTiles); desc.setSupportsMultiResolution(kSupportsMultiResolution); desc.setRenderThreadSafety(kRenderThreadSafety); desc.setHostFrameThreading(kHostFrameThreading); desc.setHostMaskingEnabled(kHostMasking); desc.setHostMixingEnabled(kHostMixing); } /** @brief The describe in context function, passed a plugin descriptor and a context */ void SwirlCLPluginFactory::describeInContext(ImageEffectDescriptor &desc, ContextEnum /*context*/) { // create the mandated source clip ClipDescriptor *srcClip = desc.defineClip(kOfxImageEffectSimpleSourceClipName); srcClip->addSupportedComponent(ePixelComponentRGBA); srcClip->setTemporalClipAccess(false); srcClip->setSupportsTiles(kSupportsTiles); srcClip->setIsMask(false); // create the mandated output clip ClipDescriptor *dstClip = desc.defineClip(kOfxImageEffectOutputClipName); dstClip->addSupportedComponent(ePixelComponentRGBA); dstClip->setSupportsTiles(kSupportsTiles); // create param(s) PageParamDescriptor *page = desc.definePageParam(kPluginName); bool hostHasNativeOverlayForPosition; { Double2DParamDescriptor* param = desc.defineDouble2DParam(kParamPosition); param->setLabel(kParamPositionLabel); param->setHint(kParamPositionHint); param->setDoubleType(eDoubleTypeXYAbsolute); param->setDefaultCoordinateSystem(eCoordinatesNormalised); param->setDefault(0.5, 0.5); param->setAnimates(true); hostHasNativeOverlayForPosition = param->getHostHasNativeOverlayHandle(); if (hostHasNativeOverlayForPosition) { param->setUseHostNativeOverlayHandle(true); } page->addChild(*param); } { DoubleParamDescriptor *param = desc.defineDoubleParam(kParamAmount); param->setLabel(kParamAmountLabel); param->setHint(kParamAmountHint); param->setRange(-100, 100); param->setDisplayRange(-10, 10); param->setDefault(kParamAmountDefault); page->addChild(*param); } { DoubleParamDescriptor *param = desc.defineDoubleParam(kParamRadius); param->setLabel(kParamRadiusLabel); param->setHint(kParamRadiusHint); param->setRange(0, 10000); param->setDisplayRange(0, 1000); param->setDefault(kParamRadiusDefault); page->addChild(*param); } } /** @brief The create instance function, the plugin must return an object derived from the \ref ImageEffect class */ ImageEffect* SwirlCLPluginFactory::createInstance(OfxImageEffectHandle handle, ContextEnum /*context*/) { return new SwirlCLPlugin(handle); } static SwirlCLPluginFactory p(kPluginIdentifier, kPluginVersionMajor, kPluginVersionMinor); mRegisterPluginFactoryInstance(p) <|endoftext|>
<commit_before>#include <Windows.h> #include <stdio.h> // Entry point BOOL WINAPI DllMain(HMODULE hModule, DWORD dwReason, LPVOID) { if (dwReason == DLL_PROCESS_ATTACH) { // Disable calls for DLL_THREAD_ATTACH and DLL_THREAD_DETACH DisableThreadLibraryCalls(hModule); } return TRUE; } // Called when the dll is loaded extern "C" __declspec(dllexport) void OnLoad() { //using namespace Common; printf("44656469636174656420746f206d756d2e2049206d69737320796f752e\n"); /* if (!Phasor::SetupDirectories()) { std::string last_err; GetLastErrorAsText(last_err); printf("Phasor was unable to setup the required directories\n"); printf("LastError details: %s\n", last_err.c_str()); return; }*/ }<commit_msg>new branch for start of Phasor<commit_after>#include <Windows.h> #include <stdio.h> // Entry point BOOL WINAPI DllMain(HMODULE hModule, DWORD dwReason, LPVOID) { if (dwReason == DLL_PROCESS_ATTACH) { // Disable calls for DLL_THREAD_ATTACH and DLL_THREAD_DETACH DisableThreadLibraryCalls(hModule); } return TRUE; } // Called when the dll is loaded extern "C" __declspec(dllexport) void OnLoad() { //using namespace Common; printf("44656469636174656420746f206d756d2e2049206d69737320796f752e\n"); /* if (!Phasor::SetupDirectories()) { std::string last_err; GetLastErrorAsText(last_err); printf("Phasor was unable to setup the required directories\n"); printf("LastError details: %s\n", last_err.c_str()); return; }*/ }<|endoftext|>
<commit_before>/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2013 The PHP Group | +----------------------------------------------------------------------+ | http://www.opensource.org/licenses/mit-license.php MIT License | +----------------------------------------------------------------------+ | Author: Jani Taskinen <jani.taskinen@iki.fi> | | Author: Patrick Reilly <preilly@php.net> | +----------------------------------------------------------------------+ */ #define V8JS_DEBUG 0 //#define PHP_V8_VERSION "0.1.4" #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php_v8js_macros.h" extern "C" { #include "php_ini.h" #include "ext/standard/info.h" #include "ext/standard/php_string.h" #include "ext/standard/php_smart_str.h" } #include "v8js_class.h" #include "v8js_exceptions.h" #include "v8js_v8object_class.h" ZEND_DECLARE_MODULE_GLOBALS(v8js) /* {{{ INI Settings */ static ZEND_INI_MH(v8js_OnUpdateV8Flags) /* {{{ */ { if (new_value) { if (V8JSG(v8_flags)) { free(V8JSG(v8_flags)); V8JSG(v8_flags) = NULL; } if (!new_value[0]) { return FAILURE; } V8JSG(v8_flags) = zend_strndup(new_value, new_value_length); } return SUCCESS; } static ZEND_INI_MH(v8js_OnUpdateUseDate) /* {{{ */ { bool value; if (new_value_length==2 && strcasecmp("on", new_value)==0) { value = (bool) 1; } else if (new_value_length==3 && strcasecmp("yes", new_value)==0) { value = (bool) 1; } else if (new_value_length==4 && strcasecmp("true", new_value)==0) { value = (bool) 1; } else { value = (bool) atoi(new_value); } V8JSG(use_date) = value; return SUCCESS; } /* }}} */ static ZEND_INI_MH(v8js_OnUpdateUseArrayAccess) /* {{{ */ { bool value; if (new_value_length==2 && strcasecmp("on", new_value)==0) { value = (bool) 1; } else if (new_value_length==3 && strcasecmp("yes", new_value)==0) { value = (bool) 1; } else if (new_value_length==4 && strcasecmp("true", new_value)==0) { value = (bool) 1; } else { value = (bool) atoi(new_value); } V8JSG(use_array_access) = value; return SUCCESS; } /* }}} */ ZEND_INI_BEGIN() /* {{{ */ ZEND_INI_ENTRY("v8js.flags", NULL, ZEND_INI_ALL, v8js_OnUpdateV8Flags) ZEND_INI_ENTRY("v8js.use_date", "0", ZEND_INI_ALL, v8js_OnUpdateUseDate) ZEND_INI_ENTRY("v8js.use_array_access", "0", ZEND_INI_ALL, v8js_OnUpdateUseArrayAccess) ZEND_INI_END() /* }}} */ /* }}} INI */ #ifdef COMPILE_DL_V8JS ZEND_GET_MODULE(v8js) #endif /* {{{ PHP_MINIT_FUNCTION */ PHP_MINIT_FUNCTION(v8js) { PHP_MINIT(v8js_class)(INIT_FUNC_ARGS_PASSTHRU); PHP_MINIT(v8js_exceptions)(INIT_FUNC_ARGS_PASSTHRU); PHP_MINIT(v8js_v8object_class)(INIT_FUNC_ARGS_PASSTHRU); REGISTER_INI_ENTRIES(); return SUCCESS; } /* }}} */ /* {{{ PHP_MSHUTDOWN_FUNCTION */ static PHP_MSHUTDOWN_FUNCTION(v8js) { UNREGISTER_INI_ENTRIES(); return SUCCESS; } /* }}} */ /* {{{ PHP_RSHUTDOWN_FUNCTION */ static PHP_RSHUTDOWN_FUNCTION(v8js) { // If the timer thread is running then stop it if (V8JSG(timer_thread)) { V8JSG(timer_stop) = true; V8JSG(timer_thread)->join(); } #if V8JS_DEBUG v8::HeapStatistics stats; v8::V8::GetHeapStatistics(&stats); float used = stats.used_heap_size() / 1024.0 / 1024.0; float total = stats.total_heap_size() / 1024.0 / 1024.0; fprintf(stderr, "### RSHUTDOWN ###\n"); fprintf(stderr, "############ Heap Used/Total %.2f/%.2f MB ############\n", used, total); fflush(stderr); #endif return SUCCESS; } /* }}} */ /* {{{ PHP_MINFO_FUNCTION */ static PHP_MINFO_FUNCTION(v8js) { php_info_print_table_start(); php_info_print_table_header(2, "V8 Javascript Engine", "enabled"); php_info_print_table_header(2, "V8 Engine Compiled Version", PHP_V8_VERSION); php_info_print_table_header(2, "V8 Engine Linked Version", v8::V8::GetVersion()); php_info_print_table_header(2, "Version", PHP_V8JS_VERSION); php_info_print_table_end(); DISPLAY_INI_ENTRIES(); } /* }}} */ /* {{{ PHP_GINIT_FUNCTION */ static PHP_GINIT_FUNCTION(v8js) { /* If ZTS is disabled, the v8js_globals instance is declared right in the BSS and hence automatically initialized by C++ compiler. Most of the variables are just zeroed. If ZTS is enabled however, v8js_globals just points to a freshly allocated, uninitialized piece of memory, hence we need to initialize all fields on our own. Likewise on shutdown we have to run the destructors manually. */ #ifdef ZTS v8js_globals->extensions = NULL; v8js_globals->v8_initialized = 0; v8js_globals->v8_flags = NULL; v8js_globals->timer_thread = NULL; v8js_globals->timer_stop = false; new(&v8js_globals->timer_mutex) std::mutex; new(&v8js_globals->timer_stack) std::deque<v8js_timer_ctx *>; v8js_globals->fatal_error_abort = 0; #endif } /* }}} */ /* {{{ PHP_GSHUTDOWN_FUNCTION */ static PHP_GSHUTDOWN_FUNCTION(v8js) { if (v8js_globals->extensions) { zend_hash_destroy(v8js_globals->extensions); free(v8js_globals->extensions); v8js_globals->extensions = NULL; } if (v8js_globals->v8_flags) { free(v8js_globals->v8_flags); v8js_globals->v8_flags = NULL; } #ifdef ZTS v8js_globals->timer_stack.~deque(); v8js_globals->timer_mutex.~mutex(); #endif } /* }}} */ /* {{{ v8js_functions[] */ static const zend_function_entry v8js_functions[] = { {NULL, NULL, NULL} }; /* }}} */ /* {{{ v8js_module_entry */ zend_module_entry v8js_module_entry = { STANDARD_MODULE_HEADER_EX, NULL, NULL, "v8js", v8js_functions, PHP_MINIT(v8js), PHP_MSHUTDOWN(v8js), NULL, PHP_RSHUTDOWN(v8js), PHP_MINFO(v8js), PHP_V8JS_VERSION, PHP_MODULE_GLOBALS(v8js), PHP_GINIT(v8js), PHP_GSHUTDOWN(v8js), NULL, STANDARD_MODULE_PROPERTIES_EX }; /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */ <commit_msg>Remove hard-coded PHP_V8_VERSION symbol<commit_after>/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2013 The PHP Group | +----------------------------------------------------------------------+ | http://www.opensource.org/licenses/mit-license.php MIT License | +----------------------------------------------------------------------+ | Author: Jani Taskinen <jani.taskinen@iki.fi> | | Author: Patrick Reilly <preilly@php.net> | +----------------------------------------------------------------------+ */ #define V8JS_DEBUG 0 #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php_v8js_macros.h" extern "C" { #include "php_ini.h" #include "ext/standard/info.h" #include "ext/standard/php_string.h" #include "ext/standard/php_smart_str.h" } #include "v8js_class.h" #include "v8js_exceptions.h" #include "v8js_v8object_class.h" ZEND_DECLARE_MODULE_GLOBALS(v8js) /* {{{ INI Settings */ static ZEND_INI_MH(v8js_OnUpdateV8Flags) /* {{{ */ { if (new_value) { if (V8JSG(v8_flags)) { free(V8JSG(v8_flags)); V8JSG(v8_flags) = NULL; } if (!new_value[0]) { return FAILURE; } V8JSG(v8_flags) = zend_strndup(new_value, new_value_length); } return SUCCESS; } static ZEND_INI_MH(v8js_OnUpdateUseDate) /* {{{ */ { bool value; if (new_value_length==2 && strcasecmp("on", new_value)==0) { value = (bool) 1; } else if (new_value_length==3 && strcasecmp("yes", new_value)==0) { value = (bool) 1; } else if (new_value_length==4 && strcasecmp("true", new_value)==0) { value = (bool) 1; } else { value = (bool) atoi(new_value); } V8JSG(use_date) = value; return SUCCESS; } /* }}} */ static ZEND_INI_MH(v8js_OnUpdateUseArrayAccess) /* {{{ */ { bool value; if (new_value_length==2 && strcasecmp("on", new_value)==0) { value = (bool) 1; } else if (new_value_length==3 && strcasecmp("yes", new_value)==0) { value = (bool) 1; } else if (new_value_length==4 && strcasecmp("true", new_value)==0) { value = (bool) 1; } else { value = (bool) atoi(new_value); } V8JSG(use_array_access) = value; return SUCCESS; } /* }}} */ ZEND_INI_BEGIN() /* {{{ */ ZEND_INI_ENTRY("v8js.flags", NULL, ZEND_INI_ALL, v8js_OnUpdateV8Flags) ZEND_INI_ENTRY("v8js.use_date", "0", ZEND_INI_ALL, v8js_OnUpdateUseDate) ZEND_INI_ENTRY("v8js.use_array_access", "0", ZEND_INI_ALL, v8js_OnUpdateUseArrayAccess) ZEND_INI_END() /* }}} */ /* }}} INI */ #ifdef COMPILE_DL_V8JS ZEND_GET_MODULE(v8js) #endif /* {{{ PHP_MINIT_FUNCTION */ PHP_MINIT_FUNCTION(v8js) { PHP_MINIT(v8js_class)(INIT_FUNC_ARGS_PASSTHRU); PHP_MINIT(v8js_exceptions)(INIT_FUNC_ARGS_PASSTHRU); PHP_MINIT(v8js_v8object_class)(INIT_FUNC_ARGS_PASSTHRU); REGISTER_INI_ENTRIES(); return SUCCESS; } /* }}} */ /* {{{ PHP_MSHUTDOWN_FUNCTION */ static PHP_MSHUTDOWN_FUNCTION(v8js) { UNREGISTER_INI_ENTRIES(); return SUCCESS; } /* }}} */ /* {{{ PHP_RSHUTDOWN_FUNCTION */ static PHP_RSHUTDOWN_FUNCTION(v8js) { // If the timer thread is running then stop it if (V8JSG(timer_thread)) { V8JSG(timer_stop) = true; V8JSG(timer_thread)->join(); } #if V8JS_DEBUG v8::HeapStatistics stats; v8::V8::GetHeapStatistics(&stats); float used = stats.used_heap_size() / 1024.0 / 1024.0; float total = stats.total_heap_size() / 1024.0 / 1024.0; fprintf(stderr, "### RSHUTDOWN ###\n"); fprintf(stderr, "############ Heap Used/Total %.2f/%.2f MB ############\n", used, total); fflush(stderr); #endif return SUCCESS; } /* }}} */ /* {{{ PHP_MINFO_FUNCTION */ static PHP_MINFO_FUNCTION(v8js) { php_info_print_table_start(); php_info_print_table_header(2, "V8 Javascript Engine", "enabled"); php_info_print_table_header(2, "V8 Engine Compiled Version", PHP_V8_VERSION); php_info_print_table_header(2, "V8 Engine Linked Version", v8::V8::GetVersion()); php_info_print_table_header(2, "Version", PHP_V8JS_VERSION); php_info_print_table_end(); DISPLAY_INI_ENTRIES(); } /* }}} */ /* {{{ PHP_GINIT_FUNCTION */ static PHP_GINIT_FUNCTION(v8js) { /* If ZTS is disabled, the v8js_globals instance is declared right in the BSS and hence automatically initialized by C++ compiler. Most of the variables are just zeroed. If ZTS is enabled however, v8js_globals just points to a freshly allocated, uninitialized piece of memory, hence we need to initialize all fields on our own. Likewise on shutdown we have to run the destructors manually. */ #ifdef ZTS v8js_globals->extensions = NULL; v8js_globals->v8_initialized = 0; v8js_globals->v8_flags = NULL; v8js_globals->timer_thread = NULL; v8js_globals->timer_stop = false; new(&v8js_globals->timer_mutex) std::mutex; new(&v8js_globals->timer_stack) std::deque<v8js_timer_ctx *>; v8js_globals->fatal_error_abort = 0; #endif } /* }}} */ /* {{{ PHP_GSHUTDOWN_FUNCTION */ static PHP_GSHUTDOWN_FUNCTION(v8js) { if (v8js_globals->extensions) { zend_hash_destroy(v8js_globals->extensions); free(v8js_globals->extensions); v8js_globals->extensions = NULL; } if (v8js_globals->v8_flags) { free(v8js_globals->v8_flags); v8js_globals->v8_flags = NULL; } #ifdef ZTS v8js_globals->timer_stack.~deque(); v8js_globals->timer_mutex.~mutex(); #endif } /* }}} */ /* {{{ v8js_functions[] */ static const zend_function_entry v8js_functions[] = { {NULL, NULL, NULL} }; /* }}} */ /* {{{ v8js_module_entry */ zend_module_entry v8js_module_entry = { STANDARD_MODULE_HEADER_EX, NULL, NULL, "v8js", v8js_functions, PHP_MINIT(v8js), PHP_MSHUTDOWN(v8js), NULL, PHP_RSHUTDOWN(v8js), PHP_MINFO(v8js), PHP_V8JS_VERSION, PHP_MODULE_GLOBALS(v8js), PHP_GINIT(v8js), PHP_GSHUTDOWN(v8js), NULL, STANDARD_MODULE_PROPERTIES_EX }; /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */ <|endoftext|>
<commit_before>#include <math.h> #include <string> #include "io.hh" #include "str.hh" #include "conf.hh" #include "HmmSet.hh" #include "FeatureGenerator.hh" #include "PhnReader.hh" #include "Recipe.hh" #include "SpeakerConfig.hh" using namespace aku; #define TINY 1e-10 std::string save_summary_file; int info; float grid_start; float grid_step; int grid_size; bool relative_grid; conf::Config config; Recipe recipe; HmmSet model; FeatureGenerator fea_gen; SpeakerConfig speaker_conf(fea_gen); VtlnModule *vtln_module; std::string cur_speaker; int cur_warp_index; typedef struct { float center; // Center warp value std::vector<float> warp_factors; std::vector<double> log_likelihoods; } SpeakerStats; typedef std::map<std::string, SpeakerStats> SpeakerStatsMap; SpeakerStatsMap speaker_stats; void set_speaker(std::string speaker, std::string utterance, int grid_iter) { float new_warp; int i; cur_speaker = speaker; assert(cur_speaker.size() > 0); speaker_conf.set_speaker(speaker); if (utterance.size() > 0) speaker_conf.set_utterance(utterance); SpeakerStatsMap::iterator it = speaker_stats.find(speaker); if (it == speaker_stats.end()) { // New speaker encountered SpeakerStats new_speaker; if (relative_grid) new_speaker.center = vtln_module->get_warp_factor(); else new_speaker.center = 1; speaker_stats[cur_speaker] = new_speaker; } new_warp = speaker_stats[cur_speaker].center + grid_start + grid_iter * grid_step; vtln_module->set_warp_factor(new_warp); for (i = 0; i < (int) speaker_stats[cur_speaker].warp_factors.size(); i++) { if (fabs(new_warp - speaker_stats[cur_speaker].warp_factors[i]) < TINY) break; } if (i == (int) speaker_stats[cur_speaker].warp_factors.size()) { // New warp factor speaker_stats[cur_speaker].warp_factors.push_back(new_warp); speaker_stats[cur_speaker].log_likelihoods.push_back(0); } cur_warp_index = i; } void compute_vtln_log_likelihoods(Segmentator *seg, std::string &speaker, std::string &utterance) { int grid_iter; int i; for (grid_iter = 0; grid_iter < grid_size; grid_iter++) { set_speaker(speaker, utterance, grid_iter); seg->reset(); seg->init_utterance_segmentation(); while (seg->next_frame()) { const std::vector<Segmentator::IndexProbPair> &pdfs = seg->pdf_probs(); FeatureVec fea_vec = fea_gen.generate(seg->current_frame()); if (fea_gen.eof()) break; // EOF in FeatureGenerator for (i = 0; i < (int) pdfs.size(); i++) { // Get probabilities speaker_stats[cur_speaker].log_likelihoods[cur_warp_index] += util::safe_log( pdfs[i].prob * model.pdf_likelihood( pdfs[i].index, fea_vec)); } } } } void save_vtln_stats(FILE *fp) { for (SpeakerStatsMap::iterator it = speaker_stats.begin(); it != speaker_stats.end(); it++) { fprintf(fp, "[%s]\n", (*it).first.c_str()); for (int i = 0; i < (int) (*it).second.warp_factors.size(); i++) { fprintf(fp, "%.3f: %.3f\n", (*it).second.warp_factors[i], (*it).second.log_likelihoods[i]); } fprintf(fp, "\n"); } } void find_best_warp_factors(void) { for (SpeakerStatsMap::iterator it = speaker_stats.begin(); it != speaker_stats.end(); it++) { assert( (*it).second.warp_factors.size() > 0 && (*it).second.warp_factors.size() == (*it).second.log_likelihoods.size()); float best_wf = (*it).second.warp_factors[0]; double best_ll = (*it).second.log_likelihoods[0]; for (int i = 1; i < (int) (*it).second.warp_factors.size(); i++) { if ((*it).second.log_likelihoods[i] > best_ll) { best_ll = (*it).second.log_likelihoods[i]; best_wf = (*it).second.warp_factors[i]; } } speaker_conf.set_speaker((*it).first); vtln_module->set_warp_factor(best_wf); } } int main(int argc, char *argv[]) { PhnReader *phn_reader; try { config("usage: vtln [OPTION...]\n")('h', "help", "", "", "display help")( 'b', "base=BASENAME", "arg", "", "base filename for model files")('g', "gk=FILE", "arg", "", "Gaussian kernels")('m', "mc=FILE", "arg", "", "kernel indices for states")('p', "ph=FILE", "arg", "", "HMM definitions")('c', "config=FILE", "arg must", "", "feature configuration")('r', "recipe=FILE", "arg must", "", "recipe file")('O', "ophn", "", "", "use output phns for VTLN")( 'v', "vtln=MODULE", "arg must", "", "VTLN module name")('S', "speakers=FILE", "arg must", "", "speaker configuration input file")('o', "out=FILE", "arg", "", "output speaker configuration file")('s', "savesum=FILE", "arg", "", "save summary information (loglikelihoods)")('\0', "snl", "", "", "phn-files with state number labels")('\0', "rsamp", "", "", "phn sample numbers are relative to start time")('\0', "grid-size=INT", "arg", "21", "warping grid size (default: 21/5)")('\0', "grid-rad=FLOAT", "arg", "0.1", "radius of warping grid (default: 0.1/0.03)")( '\0', "relative", "", "", "relative warping grid (and smaller grid defaults)")('B', "batch=INT", "arg", "0", "number of batch processes with the same recipe")('I', "bindex=INT", "arg", "0", "batch process index")('i', "info=INT", "arg", "0", "info level"); config.default_parse(argc, argv); info = config["info"].get_int(); fea_gen.load_configuration(io::Stream(config["config"].get_str())); if (config["base"].specified) { model.read_all(config["base"].get_str()); } else if (config["gk"].specified && config["mc"].specified && config["ph"].specified) { model.read_gk(config["gk"].get_str()); model.read_mc(config["mc"].get_str()); model.read_ph(config["ph"].get_str()); } else { throw std::string( "Must give either --base or all --gk, --mc and --ph"); } if (config["savesum"].specified) save_summary_file = config["savesum"].get_str(); if (config["batch"].specified ^ config["bindex"].specified) throw std::string("Must give both --batch and --bindex"); // Read recipe file recipe.read(io::Stream(config["recipe"].get_str()), config["batch"].get_int(), config["bindex"].get_int(), true); vtln_module = dynamic_cast<VtlnModule*> (fea_gen.module( config["vtln"].get_str())); if (vtln_module == NULL) throw std::string("Module ") + config["vtln"].get_str() + std::string(" is not a VTLN module"); grid_start = config["grid-rad"].get_float(); grid_size = std::max(config["grid-size"].get_int(), 1); grid_step = 2 * grid_start / std::max(grid_size - 1, 1); relative_grid = config["relative"].specified; if (relative_grid) { if (!config["grid-rad"].specified) grid_start = 0.03; if (!config["grid-size"].specified) grid_size = 5; grid_step = 2 * grid_start / std::max(grid_size - 1, 1); } grid_start = -grid_start; // Check the dimension if (model.dim() != fea_gen.dim()) { throw str::fmt(128, "gaussian dimension is %d but feature dimension is %d", model.dim(), fea_gen.dim()); } speaker_conf.read_speaker_file(io::Stream(config["speakers"].get_str())); for (int f = 0; f < (int) recipe.infos.size(); f++) { if (info > 0) { fprintf(stderr, "Processing file: %s", recipe.infos[f].audio_path.c_str()); if (recipe.infos[f].start_time || recipe.infos[f].end_time) fprintf(stderr, " (%.2f-%.2f)", recipe.infos[f].start_time, recipe.infos[f].end_time); fprintf(stderr, "\n"); } // Open the audio and phn files from the given list. phn_reader = recipe.infos[f].init_phn_files(&model, config["rsamp"].specified, config["snl"].specified, config["ophn"].specified, &fea_gen, NULL); if (recipe.infos[f].speaker_id.size() == 0) throw std::string("Speaker ID is missing"); compute_vtln_log_likelihoods(phn_reader, recipe.infos[f].speaker_id, recipe.infos[f].utterance_id); fea_gen.close(); phn_reader->close(); delete phn_reader; } // Find the best warp factors from statistics find_best_warp_factors(); if (config["savesum"].specified) { // Save the statistics save_vtln_stats(io::Stream(save_summary_file, "w")); } // Write new speaker configuration if (config["out"].specified) { std::set<std::string> *speaker_set = NULL, *utterance_set = NULL; std::set<std::string> speakers, empty_ut; if (config["batch"].get_int() > 1) { if (config["bindex"].get_int() == 1) speakers.insert(std::string("default")); for (SpeakerStatsMap::iterator it = speaker_stats.begin(); it != speaker_stats.end(); it++) speakers.insert((*it).first); speaker_set = &speakers; utterance_set = &empty_ut; } speaker_conf.write_speaker_file( io::Stream(config["out"].get_str(), "w"), speaker_set, utterance_set); } } catch (HmmSet::UnknownHmm &e) { fprintf(stderr, "Unknown HMM in transcription\n"); abort(); } catch (std::exception &e) { fprintf(stderr, "exception: %s\n", e.what()); abort(); } catch (std::string &str) { fprintf(stderr, "exception: %s\n", str.c_str()); abort(); } } <commit_msg>Changed due to HmmNetBaumWelch/Segmentator. Indentation fix<commit_after>#include <math.h> #include <string> #include "io.hh" #include "str.hh" #include "conf.hh" #include "HmmSet.hh" #include "FeatureGenerator.hh" #include "PhnReader.hh" #include "Recipe.hh" #include "SpeakerConfig.hh" using namespace aku; #define TINY 1e-10 std::string save_summary_file; int info; float grid_start; float grid_step; int grid_size; bool relative_grid; conf::Config config; Recipe recipe; HmmSet model; FeatureGenerator fea_gen; SpeakerConfig speaker_conf(fea_gen); VtlnModule *vtln_module; std::string cur_speaker; int cur_warp_index; typedef struct { float center; // Center warp value std::vector<float> warp_factors; std::vector<double> log_likelihoods; } SpeakerStats; typedef std::map<std::string, SpeakerStats> SpeakerStatsMap; SpeakerStatsMap speaker_stats; void set_speaker(std::string speaker, std::string utterance, int grid_iter) { float new_warp; int i; cur_speaker = speaker; assert(cur_speaker.size() > 0); speaker_conf.set_speaker(speaker); if (utterance.size() > 0) speaker_conf.set_utterance(utterance); SpeakerStatsMap::iterator it = speaker_stats.find(speaker); if (it == speaker_stats.end()) { // New speaker encountered SpeakerStats new_speaker; if (relative_grid) new_speaker.center = vtln_module->get_warp_factor(); else new_speaker.center = 1; speaker_stats[cur_speaker] = new_speaker; } new_warp = speaker_stats[cur_speaker].center + grid_start + grid_iter * grid_step; vtln_module->set_warp_factor(new_warp); for (i = 0; i < (int) speaker_stats[cur_speaker].warp_factors.size(); i++) { if (fabs(new_warp - speaker_stats[cur_speaker].warp_factors[i]) < TINY) break; } if (i == (int) speaker_stats[cur_speaker].warp_factors.size()) { // New warp factor speaker_stats[cur_speaker].warp_factors.push_back(new_warp); speaker_stats[cur_speaker].log_likelihoods.push_back(0); } cur_warp_index = i; } void compute_vtln_log_likelihoods(Segmentator *seg, std::string &speaker, std::string &utterance) { int grid_iter; for (grid_iter = 0; grid_iter < grid_size; grid_iter++) { set_speaker(speaker, utterance, grid_iter); seg->reset(); seg->init_utterance_segmentation(); while (seg->next_frame()) { const Segmentator::IndexProbMap &pdfs = seg->pdf_probs(); FeatureVec fea_vec = fea_gen.generate(seg->current_frame()); if (fea_gen.eof()) break; // EOF in FeatureGenerator for (Segmentator::IndexProbMap::const_iterator it = pdfs.begin(); it != pdfs.end(); ++it) { // Get probabilities speaker_stats[cur_speaker].log_likelihoods[cur_warp_index] += util::safe_log((*it).second*model.pdf_likelihood((*it).first, fea_vec)); } } } } void save_vtln_stats(FILE *fp) { for (SpeakerStatsMap::iterator it = speaker_stats.begin(); it != speaker_stats.end(); it++) { fprintf(fp, "[%s]\n", (*it).first.c_str()); for (int i = 0; i < (int) (*it).second.warp_factors.size(); i++) { fprintf(fp, "%.3f: %.3f\n", (*it).second.warp_factors[i], (*it).second.log_likelihoods[i]); } fprintf(fp, "\n"); } } void find_best_warp_factors(void) { for (SpeakerStatsMap::iterator it = speaker_stats.begin(); it != speaker_stats.end(); it++) { assert( (*it).second.warp_factors.size() > 0 && (*it).second.warp_factors.size() == (*it).second.log_likelihoods.size()); float best_wf = (*it).second.warp_factors[0]; double best_ll = (*it).second.log_likelihoods[0]; for (int i = 1; i < (int) (*it).second.warp_factors.size(); i++) { if ((*it).second.log_likelihoods[i] > best_ll) { best_ll = (*it).second.log_likelihoods[i]; best_wf = (*it).second.warp_factors[i]; } } speaker_conf.set_speaker((*it).first); vtln_module->set_warp_factor(best_wf); } } int main(int argc, char *argv[]) { PhnReader *phn_reader; try { config("usage: vtln [OPTION...]\n") ('h', "help", "", "", "display help") ('b', "base=BASENAME", "arg", "", "base filename for model files") ('g', "gk=FILE", "arg", "", "Gaussian kernels") ('m', "mc=FILE", "arg", "", "kernel indices for states") ('p', "ph=FILE", "arg", "", "HMM definitions") ('c', "config=FILE", "arg must", "", "feature configuration") ('r', "recipe=FILE", "arg must", "", "recipe file") ('O', "ophn", "", "", "use output phns for VTLN") ('v', "vtln=MODULE", "arg must", "", "VTLN module name") ('S', "speakers=FILE", "arg must", "", "speaker configuration input file") ('o', "out=FILE", "arg", "", "output speaker configuration file") ('s', "savesum=FILE", "arg", "", "save summary information (loglikelihoods)") ('\0', "snl", "", "", "phn-files with state number labels") ('\0', "rsamp", "", "", "phn sample numbers are relative to start time") ('\0', "grid-size=INT", "arg", "21", "warping grid size (default: 21/5)") ('\0', "grid-rad=FLOAT", "arg", "0.1", "radius of warping grid (default: 0.1/0.03)") ('\0', "relative", "", "", "relative warping grid (and smaller grid defaults)") ('B', "batch=INT", "arg", "0", "number of batch processes with the same recipe") ('I', "bindex=INT", "arg", "0", "batch process index") ('i', "info=INT", "arg", "0", "info level"); config.default_parse(argc, argv); info = config["info"].get_int(); fea_gen.load_configuration(io::Stream(config["config"].get_str())); if (config["base"].specified) { model.read_all(config["base"].get_str()); } else if (config["gk"].specified && config["mc"].specified && config["ph"].specified) { model.read_gk(config["gk"].get_str()); model.read_mc(config["mc"].get_str()); model.read_ph(config["ph"].get_str()); } else { throw std::string( "Must give either --base or all --gk, --mc and --ph"); } if (config["savesum"].specified) save_summary_file = config["savesum"].get_str(); if (config["batch"].specified ^ config["bindex"].specified) throw std::string("Must give both --batch and --bindex"); // Read recipe file recipe.read(io::Stream(config["recipe"].get_str()), config["batch"].get_int(), config["bindex"].get_int(), true); vtln_module = dynamic_cast<VtlnModule*> (fea_gen.module( config["vtln"].get_str())); if (vtln_module == NULL) throw std::string("Module ") + config["vtln"].get_str() + std::string(" is not a VTLN module"); grid_start = config["grid-rad"].get_float(); grid_size = std::max(config["grid-size"].get_int(), 1); grid_step = 2 * grid_start / std::max(grid_size - 1, 1); relative_grid = config["relative"].specified; if (relative_grid) { if (!config["grid-rad"].specified) grid_start = 0.03; if (!config["grid-size"].specified) grid_size = 5; grid_step = 2 * grid_start / std::max(grid_size - 1, 1); } grid_start = -grid_start; // Check the dimension if (model.dim() != fea_gen.dim()) { throw str::fmt(128, "gaussian dimension is %d but feature dimension is %d", model.dim(), fea_gen.dim()); } speaker_conf.read_speaker_file(io::Stream(config["speakers"].get_str())); for (int f = 0; f < (int) recipe.infos.size(); f++) { if (info > 0) { fprintf(stderr, "Processing file: %s", recipe.infos[f].audio_path.c_str()); if (recipe.infos[f].start_time || recipe.infos[f].end_time) fprintf(stderr, " (%.2f-%.2f)", recipe.infos[f].start_time, recipe.infos[f].end_time); fprintf(stderr, "\n"); } // Open the audio and phn files from the given list. phn_reader = recipe.infos[f].init_phn_files(&model, config["rsamp"].specified, config["snl"].specified, config["ophn"].specified, &fea_gen, NULL); if (recipe.infos[f].speaker_id.size() == 0) throw std::string("Speaker ID is missing"); compute_vtln_log_likelihoods(phn_reader, recipe.infos[f].speaker_id, recipe.infos[f].utterance_id); fea_gen.close(); phn_reader->close(); delete phn_reader; } // Find the best warp factors from statistics find_best_warp_factors(); if (config["savesum"].specified) { // Save the statistics save_vtln_stats(io::Stream(save_summary_file, "w")); } // Write new speaker configuration if (config["out"].specified) { std::set<std::string> *speaker_set = NULL, *utterance_set = NULL; std::set<std::string> speakers, empty_ut; if (config["batch"].get_int() > 1) { if (config["bindex"].get_int() == 1) speakers.insert(std::string("default")); for (SpeakerStatsMap::iterator it = speaker_stats.begin(); it != speaker_stats.end(); it++) speakers.insert((*it).first); speaker_set = &speakers; utterance_set = &empty_ut; } speaker_conf.write_speaker_file( io::Stream(config["out"].get_str(), "w"), speaker_set, utterance_set); } } catch (HmmSet::UnknownHmm &e) { fprintf(stderr, "Unknown HMM in transcription\n"); abort(); } catch (std::exception &e) { fprintf(stderr, "exception: %s\n", e.what()); abort(); } catch (std::string &str) { fprintf(stderr, "exception: %s\n", str.c_str()); abort(); } } <|endoftext|>
<commit_before>#include "engine/fs/file_system.h" #include "engine/array.h" #include "engine/base_proxy_allocator.h" #include "engine/blob.h" #include "engine/fs/disk_file_device.h" #include "engine/fs/file_system.h" #include "engine/mt/lock_free_fixed_queue.h" #include "engine/mt/task.h" #include "engine/mt/transaction.h" #include "engine/path.h" #include "engine/profiler.h" #include "engine/queue.h" #include "engine/string.h" namespace Lumix { namespace FS { enum TransFlags { E_CLOSE = 0, E_SUCCESS = 0x1, E_IS_OPEN = E_SUCCESS << 1, E_FAIL = E_IS_OPEN << 1, E_CANCELED = E_FAIL << 1 }; struct AsyncItem { IFile* m_file; ReadCallback m_cb; Mode m_mode; uint32 m_id; char m_path[MAX_PATH_LENGTH]; uint8 m_flags; }; static const int32 C_MAX_TRANS = 16; typedef MT::Transaction<AsyncItem> AsynTrans; typedef MT::LockFreeFixedQueue<AsynTrans, C_MAX_TRANS> TransQueue; typedef Queue<AsynTrans*, C_MAX_TRANS> InProgressQueue; typedef Array<AsyncItem> ItemsTable; typedef Array<IFileDevice*> DevicesTable; void IFile::release() { getDevice().destroyFile(this); } IFile& IFile::operator<<(const char* text) { write(text, stringLength(text)); return *this; } void IFile::getContents(OutputBlob& blob) { size_t tmp = size(); blob.resize((int)tmp); read(blob.getMutableData(), tmp); } #if !LUMIX_SINGLE_THREAD() class FSTask LUMIX_FINAL : public MT::Task { public: FSTask(TransQueue* queue, IAllocator& allocator) : MT::Task(allocator) , m_trans_queue(queue) { } ~FSTask() {} int task() { while (!m_trans_queue->isAborted()) { PROFILE_BLOCK("transaction"); AsynTrans* tr = m_trans_queue->pop(true); if (!tr) break; if ((tr->data.m_flags & E_IS_OPEN) == E_IS_OPEN) { tr->data.m_flags |= tr->data.m_file->open(Path(tr->data.m_path), tr->data.m_mode) ? E_SUCCESS : E_FAIL; } else if ((tr->data.m_flags & E_CLOSE) == E_CLOSE) { tr->data.m_file->close(); tr->data.m_file->release(); tr->data.m_file = nullptr; } tr->setCompleted(); } return 0; } void stop() { m_trans_queue->abort(); } private: TransQueue* m_trans_queue; }; #endif class FileSystemImpl LUMIX_FINAL : public FileSystem { public: explicit FileSystemImpl(IAllocator& allocator) : m_allocator(allocator) , m_pending(m_allocator) , m_devices(m_allocator) , m_in_progress(m_allocator) , m_last_id(0) { m_disk_device.m_devices[0] = nullptr; m_memory_device.m_devices[0] = nullptr; m_default_device.m_devices[0] = nullptr; m_save_game_device.m_devices[0] = nullptr; #if !LUMIX_SINGLE_THREAD() m_task = LUMIX_NEW(m_allocator, FSTask)(&m_transaction_queue, m_allocator); m_task->create("FSTask"); #endif } ~FileSystemImpl() { #if !LUMIX_SINGLE_THREAD() m_task->stop(); m_task->destroy(); LUMIX_DELETE(m_allocator, m_task); #endif while (!m_in_progress.empty()) { auto* trans = m_in_progress.front(); m_in_progress.pop(); if (trans->data.m_file) close(*trans->data.m_file); } for (auto& i : m_pending) { close(*i.m_file); } } BaseProxyAllocator& getAllocator() { return m_allocator; } bool hasWork() const override { return !m_in_progress.empty() || !m_pending.empty(); } bool mount(IFileDevice* device) override { for (int i = 0; i < m_devices.size(); i++) { if (m_devices[i] == device) { return false; } } if (equalStrings(device->name(), "memory")) { m_memory_device.m_devices[0] = device; m_memory_device.m_devices[1] = nullptr; } else if (equalStrings(device->name(), "disk")) { m_disk_device.m_devices[0] = device; m_disk_device.m_devices[1] = nullptr; } m_devices.push(device); return true; } bool unMount(IFileDevice* device) override { for (int i = 0; i < m_devices.size(); i++) { if (m_devices[i] == device) { m_devices.eraseFast(i); return true; } } return false; } IFile* createFile(const DeviceList& device_list) { IFile* prev = nullptr; for (int i = 0; i < lengthOf(device_list.m_devices); ++i) { if (!device_list.m_devices[i]) { break; } prev = device_list.m_devices[i]->createFile(prev); } return prev; } IFile* open(const DeviceList& device_list, const Path& file, Mode mode) override { IFile* prev = createFile(device_list); if (prev) { if (prev->open(file, mode)) { return prev; } else { prev->release(); return nullptr; } } return nullptr; } uint32 openAsync(const DeviceList& device_list, const Path& file, int mode, const ReadCallback& call_back) override { IFile* prev = createFile(device_list); if (prev) { AsyncItem& item = m_pending.emplace(); item.m_file = prev; item.m_cb = call_back; item.m_mode = mode; copyString(item.m_path, file.c_str()); item.m_flags = E_IS_OPEN; item.m_id = m_last_id; ++m_last_id; if (m_last_id == INVALID_ASYNC) m_last_id = 0; return item.m_id; } return INVALID_ASYNC; } void cancelAsync(uint32 id) override { if (id == INVALID_ASYNC) return; for (int i = 0, c = m_pending.size(); i < c; ++i) { if (m_pending[i].m_id == id) { m_pending[i].m_flags |= E_CANCELED; return; } } for (auto iter = m_in_progress.begin(), end = m_in_progress.end(); iter != end; ++iter) { if (iter.value()->data.m_id = id) { iter.value()->data.m_flags |= E_CANCELED; return; } } } void setDefaultDevice(const char* dev) override { fillDeviceList(dev, m_default_device); } void fillDeviceList(const char* dev, DeviceList& device_list) override { const char* token = nullptr; int device_index = 0; const char* end = dev + stringLength(dev); while (end > dev) { token = reverseFind(dev, token, ':'); char device[32]; if (token) { copyNString(device, (int)sizeof(device), token + 1, int(end - token - 1)); } else { copyNString(device, (int)sizeof(device), dev, int(end - dev)); } end = token; device_list.m_devices[device_index] = getDevice(device); ASSERT(device_list.m_devices[device_index]); ++device_index; } device_list.m_devices[device_index] = nullptr; } const DeviceList& getMemoryDevice() const override { return m_memory_device; } const DeviceList& getDiskDevice() const override { return m_disk_device; } void setSaveGameDevice(const char* dev) override { fillDeviceList(dev, m_save_game_device); } void close(IFile& file) override { file.close(); file.release(); } void closeAsync(IFile& file) override { AsyncItem& item = m_pending.emplace(); item.m_file = &file; item.m_cb.bind<closeAsync>(); item.m_mode = 0; item.m_flags = E_CLOSE; } void updateAsyncTransactions() override { PROFILE_FUNCTION(); while (!m_in_progress.empty()) { AsynTrans* tr = m_in_progress.front(); if (!tr->isCompleted()) break; PROFILE_BLOCK("processAsyncTransaction"); m_in_progress.pop(); if ((tr->data.m_flags & E_CANCELED) == 0) { tr->data.m_cb.invoke(*tr->data.m_file, !!(tr->data.m_flags & E_SUCCESS)); } if ((tr->data.m_flags & (E_SUCCESS | E_FAIL)) != 0) { closeAsync(*tr->data.m_file); } m_transaction_queue.dealoc(tr); } int32 can_add = C_MAX_TRANS - m_in_progress.size(); while (can_add && !m_pending.empty()) { AsynTrans* tr = m_transaction_queue.alloc(false); if (tr) { AsyncItem& item = m_pending[0]; tr->data.m_file = item.m_file; tr->data.m_cb = item.m_cb; tr->data.m_mode = item.m_mode; copyString(tr->data.m_path, sizeof(tr->data.m_path), item.m_path); tr->data.m_flags = item.m_flags; tr->reset(); m_transaction_queue.push(tr, true); m_in_progress.push(tr); m_pending.erase(0); } can_add--; } #if LUMIX_SINGLE_THREAD() while (AsynTrans* tr = m_transaction_queue.pop(false)) { PROFILE_BLOCK("transaction"); if ((tr->data.m_flags & E_IS_OPEN) == E_IS_OPEN) { tr->data.m_flags |= tr->data.m_file->open(Path(tr->data.m_path), tr->data.m_mode) ? E_SUCCESS : E_FAIL; } else if ((tr->data.m_flags & E_CLOSE) == E_CLOSE) { tr->data.m_file->close(); tr->data.m_file->release(); tr->data.m_file = nullptr; } tr->setCompleted(); } #endif } const DeviceList& getDefaultDevice() const override { return m_default_device; } const DeviceList& getSaveGameDevice() const override { return m_save_game_device; } IFileDevice* getDevice(const char* device) { for (int i = 0; i < m_devices.size(); ++i) { if (equalStrings(m_devices[i]->name(), device)) return m_devices[i]; } return nullptr; } static void closeAsync(IFile&, bool) {} private: BaseProxyAllocator m_allocator; #if !LUMIX_SINGLE_THREAD() FSTask* m_task; #endif DevicesTable m_devices; ItemsTable m_pending; TransQueue m_transaction_queue; InProgressQueue m_in_progress; DeviceList m_disk_device; DeviceList m_memory_device; DeviceList m_default_device; DeviceList m_save_game_device; uint32 m_last_id; }; FileSystem* FileSystem::create(IAllocator& allocator) { return LUMIX_NEW(allocator, FileSystemImpl)(allocator); } void FileSystem::destroy(FileSystem* fs) { LUMIX_DELETE(static_cast<FileSystemImpl*>(fs)->getAllocator().getSourceAllocator(), fs); } } // namespace FS } // namespace Lumix <commit_msg>fixed canceling of async fs op<commit_after>#include "engine/fs/file_system.h" #include "engine/array.h" #include "engine/base_proxy_allocator.h" #include "engine/blob.h" #include "engine/fs/disk_file_device.h" #include "engine/fs/file_system.h" #include "engine/mt/lock_free_fixed_queue.h" #include "engine/mt/task.h" #include "engine/mt/transaction.h" #include "engine/path.h" #include "engine/profiler.h" #include "engine/queue.h" #include "engine/string.h" namespace Lumix { namespace FS { enum TransFlags { E_CLOSE = 0, E_SUCCESS = 0x1, E_IS_OPEN = E_SUCCESS << 1, E_FAIL = E_IS_OPEN << 1, E_CANCELED = E_FAIL << 1 }; struct AsyncItem { IFile* m_file; ReadCallback m_cb; Mode m_mode; uint32 m_id; char m_path[MAX_PATH_LENGTH]; uint8 m_flags; }; static const int32 C_MAX_TRANS = 16; typedef MT::Transaction<AsyncItem> AsynTrans; typedef MT::LockFreeFixedQueue<AsynTrans, C_MAX_TRANS> TransQueue; typedef Queue<AsynTrans*, C_MAX_TRANS> InProgressQueue; typedef Array<AsyncItem> ItemsTable; typedef Array<IFileDevice*> DevicesTable; void IFile::release() { getDevice().destroyFile(this); } IFile& IFile::operator<<(const char* text) { write(text, stringLength(text)); return *this; } void IFile::getContents(OutputBlob& blob) { size_t tmp = size(); blob.resize((int)tmp); read(blob.getMutableData(), tmp); } #if !LUMIX_SINGLE_THREAD() class FSTask LUMIX_FINAL : public MT::Task { public: FSTask(TransQueue* queue, IAllocator& allocator) : MT::Task(allocator) , m_trans_queue(queue) { } ~FSTask() {} int task() { while (!m_trans_queue->isAborted()) { PROFILE_BLOCK("transaction"); AsynTrans* tr = m_trans_queue->pop(true); if (!tr) break; if ((tr->data.m_flags & E_IS_OPEN) == E_IS_OPEN) { tr->data.m_flags |= tr->data.m_file->open(Path(tr->data.m_path), tr->data.m_mode) ? E_SUCCESS : E_FAIL; } else if ((tr->data.m_flags & E_CLOSE) == E_CLOSE) { tr->data.m_file->close(); tr->data.m_file->release(); tr->data.m_file = nullptr; } tr->setCompleted(); } return 0; } void stop() { m_trans_queue->abort(); } private: TransQueue* m_trans_queue; }; #endif class FileSystemImpl LUMIX_FINAL : public FileSystem { public: explicit FileSystemImpl(IAllocator& allocator) : m_allocator(allocator) , m_pending(m_allocator) , m_devices(m_allocator) , m_in_progress(m_allocator) , m_last_id(0) { m_disk_device.m_devices[0] = nullptr; m_memory_device.m_devices[0] = nullptr; m_default_device.m_devices[0] = nullptr; m_save_game_device.m_devices[0] = nullptr; #if !LUMIX_SINGLE_THREAD() m_task = LUMIX_NEW(m_allocator, FSTask)(&m_transaction_queue, m_allocator); m_task->create("FSTask"); #endif } ~FileSystemImpl() { #if !LUMIX_SINGLE_THREAD() m_task->stop(); m_task->destroy(); LUMIX_DELETE(m_allocator, m_task); #endif while (!m_in_progress.empty()) { auto* trans = m_in_progress.front(); m_in_progress.pop(); if (trans->data.m_file) close(*trans->data.m_file); } for (auto& i : m_pending) { close(*i.m_file); } } BaseProxyAllocator& getAllocator() { return m_allocator; } bool hasWork() const override { return !m_in_progress.empty() || !m_pending.empty(); } bool mount(IFileDevice* device) override { for (int i = 0; i < m_devices.size(); i++) { if (m_devices[i] == device) { return false; } } if (equalStrings(device->name(), "memory")) { m_memory_device.m_devices[0] = device; m_memory_device.m_devices[1] = nullptr; } else if (equalStrings(device->name(), "disk")) { m_disk_device.m_devices[0] = device; m_disk_device.m_devices[1] = nullptr; } m_devices.push(device); return true; } bool unMount(IFileDevice* device) override { for (int i = 0; i < m_devices.size(); i++) { if (m_devices[i] == device) { m_devices.eraseFast(i); return true; } } return false; } IFile* createFile(const DeviceList& device_list) { IFile* prev = nullptr; for (int i = 0; i < lengthOf(device_list.m_devices); ++i) { if (!device_list.m_devices[i]) { break; } prev = device_list.m_devices[i]->createFile(prev); } return prev; } IFile* open(const DeviceList& device_list, const Path& file, Mode mode) override { IFile* prev = createFile(device_list); if (prev) { if (prev->open(file, mode)) { return prev; } else { prev->release(); return nullptr; } } return nullptr; } uint32 openAsync(const DeviceList& device_list, const Path& file, int mode, const ReadCallback& call_back) override { IFile* prev = createFile(device_list); if (prev) { AsyncItem& item = m_pending.emplace(); item.m_file = prev; item.m_cb = call_back; item.m_mode = mode; copyString(item.m_path, file.c_str()); item.m_flags = E_IS_OPEN; item.m_id = m_last_id; ++m_last_id; if (m_last_id == INVALID_ASYNC) m_last_id = 0; return item.m_id; } return INVALID_ASYNC; } void cancelAsync(uint32 id) override { if (id == INVALID_ASYNC) return; for (int i = 0, c = m_pending.size(); i < c; ++i) { if (m_pending[i].m_id == id) { m_pending[i].m_flags |= E_CANCELED; return; } } for (auto iter = m_in_progress.begin(), end = m_in_progress.end(); iter != end; ++iter) { if (iter.value()->data.m_id == id) { iter.value()->data.m_flags |= E_CANCELED; return; } } } void setDefaultDevice(const char* dev) override { fillDeviceList(dev, m_default_device); } void fillDeviceList(const char* dev, DeviceList& device_list) override { const char* token = nullptr; int device_index = 0; const char* end = dev + stringLength(dev); while (end > dev) { token = reverseFind(dev, token, ':'); char device[32]; if (token) { copyNString(device, (int)sizeof(device), token + 1, int(end - token - 1)); } else { copyNString(device, (int)sizeof(device), dev, int(end - dev)); } end = token; device_list.m_devices[device_index] = getDevice(device); ASSERT(device_list.m_devices[device_index]); ++device_index; } device_list.m_devices[device_index] = nullptr; } const DeviceList& getMemoryDevice() const override { return m_memory_device; } const DeviceList& getDiskDevice() const override { return m_disk_device; } void setSaveGameDevice(const char* dev) override { fillDeviceList(dev, m_save_game_device); } void close(IFile& file) override { file.close(); file.release(); } void closeAsync(IFile& file) override { AsyncItem& item = m_pending.emplace(); item.m_file = &file; item.m_cb.bind<closeAsync>(); item.m_mode = 0; item.m_flags = E_CLOSE; } void updateAsyncTransactions() override { PROFILE_FUNCTION(); while (!m_in_progress.empty()) { AsynTrans* tr = m_in_progress.front(); if (!tr->isCompleted()) break; PROFILE_BLOCK("processAsyncTransaction"); m_in_progress.pop(); if ((tr->data.m_flags & E_CANCELED) == 0) { tr->data.m_cb.invoke(*tr->data.m_file, !!(tr->data.m_flags & E_SUCCESS)); } if ((tr->data.m_flags & (E_SUCCESS | E_FAIL)) != 0) { closeAsync(*tr->data.m_file); } m_transaction_queue.dealoc(tr); } int32 can_add = C_MAX_TRANS - m_in_progress.size(); while (can_add && !m_pending.empty()) { AsynTrans* tr = m_transaction_queue.alloc(false); if (tr) { AsyncItem& item = m_pending[0]; tr->data.m_file = item.m_file; tr->data.m_cb = item.m_cb; tr->data.m_id = item.m_id; tr->data.m_mode = item.m_mode; copyString(tr->data.m_path, sizeof(tr->data.m_path), item.m_path); tr->data.m_flags = item.m_flags; tr->reset(); m_transaction_queue.push(tr, true); m_in_progress.push(tr); m_pending.erase(0); } can_add--; } #if LUMIX_SINGLE_THREAD() while (AsynTrans* tr = m_transaction_queue.pop(false)) { PROFILE_BLOCK("transaction"); if ((tr->data.m_flags & E_IS_OPEN) == E_IS_OPEN) { tr->data.m_flags |= tr->data.m_file->open(Path(tr->data.m_path), tr->data.m_mode) ? E_SUCCESS : E_FAIL; } else if ((tr->data.m_flags & E_CLOSE) == E_CLOSE) { tr->data.m_file->close(); tr->data.m_file->release(); tr->data.m_file = nullptr; } tr->setCompleted(); } #endif } const DeviceList& getDefaultDevice() const override { return m_default_device; } const DeviceList& getSaveGameDevice() const override { return m_save_game_device; } IFileDevice* getDevice(const char* device) { for (int i = 0; i < m_devices.size(); ++i) { if (equalStrings(m_devices[i]->name(), device)) return m_devices[i]; } return nullptr; } static void closeAsync(IFile&, bool) {} private: BaseProxyAllocator m_allocator; #if !LUMIX_SINGLE_THREAD() FSTask* m_task; #endif DevicesTable m_devices; ItemsTable m_pending; TransQueue m_transaction_queue; InProgressQueue m_in_progress; DeviceList m_disk_device; DeviceList m_memory_device; DeviceList m_default_device; DeviceList m_save_game_device; uint32 m_last_id; }; FileSystem* FileSystem::create(IAllocator& allocator) { return LUMIX_NEW(allocator, FileSystemImpl)(allocator); } void FileSystem::destroy(FileSystem* fs) { LUMIX_DELETE(static_cast<FileSystemImpl*>(fs)->getAllocator().getSourceAllocator(), fs); } } // namespace FS } // namespace Lumix <|endoftext|>
<commit_before>#ifndef ENTT_ENTITY_VIEW_PACK_HPP #define ENTT_ENTITY_VIEW_PACK_HPP #include <tuple> #include <type_traits> #include <utility> #include "fwd.hpp" #include "utility.hpp" namespace entt { /** * @brief View pack. * * The view pack allows users to combine multiple views into a single iterable * object, while also giving them full control over which view should lead the * iteration.<br/> * Its intended primary use is for custom storage and views, but it can also be * very convenient in everyday use. * * @tparam View Type of the leading view of the pack. * @tparam Other Types of all other views of the pack. */ template<typename View, typename... Other> class view_pack { using common_entity_type = std::common_type_t<typename View::entity_type, typename Other::entity_type...>; class view_pack_iterator { friend class view_pack<View, Other...>; using underlying_iterator = typename View::iterator; view_pack_iterator(underlying_iterator from, underlying_iterator to, const std::tuple<View, Other...> &ref) ENTT_NOEXCEPT : it{from}, last{to}, pack{std::get<Other>(ref)...} { if(it != last && !valid()) { ++(*this); } } [[nodiscard]] bool valid() const { const auto entity = *it; return (std::get<Other>(pack).contains(entity) && ...); } public: using difference_type = typename std::iterator_traits<underlying_iterator>::difference_type; using value_type = decltype(*std::declval<underlying_iterator>()); using pointer = void; using reference = value_type; using iterator_category = std::input_iterator_tag; view_pack_iterator & operator++() ENTT_NOEXCEPT { while(++it != last && !valid()); return *this; } view_pack_iterator operator++(int) ENTT_NOEXCEPT { view_pack_iterator orig = *this; return ++(*this), orig; } [[nodiscard]] reference operator*() const { return *it; } [[nodiscard]] bool operator==(const view_pack_iterator &other) const ENTT_NOEXCEPT { return other.it == it; } [[nodiscard]] bool operator!=(const view_pack_iterator &other) const ENTT_NOEXCEPT { return !(*this == other); } private: underlying_iterator it; const underlying_iterator last; const std::tuple<Other...> pack; }; class iterable_view_pack { friend class view_pack<View, Other...>; using iterable_view = decltype(std::declval<View>().each()); class iterable_view_pack_iterator { friend class iterable_view_pack; using underlying_iterator = typename iterable_view::iterator; iterable_view_pack_iterator(underlying_iterator from, underlying_iterator to, const std::tuple<Other...> &ref) ENTT_NOEXCEPT : it{from}, last{to}, pack{ref} { if(it != last && !valid()) { ++(*this); } } [[nodiscard]] bool valid() const { const auto entity = std::get<0>(*it); return (std::get<Other>(pack).contains(entity) && ...); } public: using difference_type = typename std::iterator_traits<underlying_iterator>::difference_type; using value_type = decltype(std::tuple_cat(*std::declval<underlying_iterator>(), std::declval<Other>().get({})...)); using pointer = void; using reference = value_type; using iterator_category = std::input_iterator_tag; iterable_view_pack_iterator & operator++() ENTT_NOEXCEPT { while(++it != last && !valid()); return *this; } iterable_view_pack_iterator operator++(int) ENTT_NOEXCEPT { iterable_view_pack_iterator orig = *this; return ++(*this), orig; } [[nodiscard]] reference operator*() const { const auto curr = *it; return std::tuple_cat(curr, std::get<Other>(pack).get(std::get<0>(curr))...); } [[nodiscard]] bool operator==(const iterable_view_pack_iterator &other) const ENTT_NOEXCEPT { return other.it == it; } [[nodiscard]] bool operator!=(const iterable_view_pack_iterator &other) const ENTT_NOEXCEPT { return !(*this == other); } private: underlying_iterator it; const underlying_iterator last; const std::tuple<Other...> pack; }; iterable_view_pack(const std::tuple<View, Other...> &ref) : iterable{std::get<View>(ref).each()}, pack{std::get<Other>(ref)...} {} public: using iterator = iterable_view_pack_iterator; [[nodiscard]] iterator begin() const ENTT_NOEXCEPT { return { iterable.begin(), iterable.end(), pack }; } [[nodiscard]] iterator end() const ENTT_NOEXCEPT { return { iterable.end(), iterable.end(), pack }; } private: iterable_view iterable; std::tuple<Other...> pack; }; public: /*! @brief Underlying entity identifier. */ using entity_type = common_entity_type; /*! @brief Input iterator type. */ using iterator = view_pack_iterator; /** * @brief Constructs a pack from a bunch of views. * @param view A reference to the leading view for the pack. * @param other References to the other views to use to construct the pack. */ view_pack(const View &view, const Other &... other) : pack{view, other...} {} /** * @brief Returns an iterator to the first entity of the pack. * * The returned iterator points to the first entity of the pack. If the pack * is empty, the returned iterator will be equal to `end()`. * * @note * Iterators stay true to the order imposed by the first view of the pack. * * @return An iterator to the first entity of the pack. */ [[nodiscard]] iterator begin() const ENTT_NOEXCEPT { return { std::get<View>(pack).begin(), std::get<View>(pack).end(), pack }; } /** * @brief Returns an iterator that is past the last entity of the pack. * * The returned iterator points to the entity following the last entity of * the pack. Attempting to dereference the returned iterator results in * undefined behavior. * * @note * Iterators stay true to the order imposed by the first view of the pack. * * @return An iterator to the entity following the last entity of the pack. */ [[nodiscard]] iterator end() const ENTT_NOEXCEPT { return { std::get<View>(pack).end(), std::get<View>(pack).end(), pack }; } /** * @brief Iterates entities and components and applies the given function * object to them. * * The function object is invoked for each entity. It is provided with the * entity itself and a set of references to non-empty components. The * _constness_ of the components is as requested.<br/> * The signature of the function must be equivalent to one of the following * forms: * * @code{.cpp} * void(const entity_type, Type &...); * void(Type &...); * @endcode * * @note * Empty types aren't explicitly instantiated and therefore they are never * returned during iterations. * * @tparam Func Type of the function object to invoke. * @param func A valid function object. */ template<typename Func> void each(Func func) const { for(auto value: std::get<View>(pack).each()) { const auto entity = std::get<0>(value); if((std::get<Other>(pack).contains(entity) && ...)) { std::apply(func, std::tuple_cat(value, std::get<Other>(pack).get(entity)...)); } } } /** * @brief Returns an iterable object to use to _visit_ the pack. * * The iterable object returns tuples that contain the current entity and a * set of references to its non-empty components. The _constness_ of the * components is as requested. * * @note * Empty types aren't explicitly instantiated and therefore they are never * returned during iterations. * * @return An iterable object to use to _visit_ the pack. */ [[nodiscard]] iterable_view_pack each() const ENTT_NOEXCEPT { return pack; } /** * @brief Returns a copy of the requested view from a pack. * @tparam Type Type of the view to return. * @return A copy of the requested view from the pack. */ template<typename Type> [[nodiscard]] operator Type() const ENTT_NOEXCEPT { return std::get<Type>(pack); } /** * @brief Appends a view to a pack. * @tparam Args View template arguments. * @param view A reference to a view to append to the pack. * @return The extended pack. */ template<typename... Args> [[nodiscard]] auto operator|(const basic_view<Args...> &view) const { return std::make_from_tuple<view_pack<View, Other..., basic_view<Args...>>>(std::tuple_cat(pack, std::make_tuple(view))); } /** * @brief Appends a pack and therefore all its views to another pack. * @tparam Pack Types of views of the pack to append. * @param other A reference to the pack to append. * @return The extended pack. */ template<typename... Pack> [[nodiscard]] auto operator|(const view_pack<Pack...> &other) const { return std::make_from_tuple<view_pack<View, Other..., Pack...>>(std::tuple_cat(pack, std::make_tuple(static_cast<Pack>(other)...))); } private: std::tuple<View, Other...> pack; }; /** * @brief Combines two views in a pack. * @tparam Args Template arguments of the first view. * @tparam Other Template arguments of the second view. * @param lhs A reference to the first view with which to create the pack. * @param rhs A reference to the second view with which to create the pack. * @return A pack that combines the two views in a single iterable object. */ template<typename... Args, typename... Other> [[nodiscard]] auto operator|(const basic_view<Args...> &lhs, const basic_view<Other...> &rhs) { return view_pack{lhs, rhs}; } /** * @brief Combines a view with a pack. * @tparam Args View template arguments. * @tparam Pack Types of views of the pack. * @param view A reference to the view to combine with the pack. * @param pack A reference to the pack to combine with the view. * @return The extended pack. */ template<typename... Args, typename... Pack> [[nodiscard]] auto operator|(const basic_view<Args...> &view, const view_pack<Pack...> &pack) { return view_pack{view} | pack; } } #endif <commit_msg>view_pack: get around an issue of VS2017<commit_after>#ifndef ENTT_ENTITY_VIEW_PACK_HPP #define ENTT_ENTITY_VIEW_PACK_HPP #include <tuple> #include <type_traits> #include <utility> #include "fwd.hpp" #include "utility.hpp" namespace entt { /** * @brief View pack. * * The view pack allows users to combine multiple views into a single iterable * object, while also giving them full control over which view should lead the * iteration.<br/> * Its intended primary use is for custom storage and views, but it can also be * very convenient in everyday use. * * @tparam View Type of the leading view of the pack. * @tparam Other Types of all other views of the pack. */ template<typename View, typename... Other> class view_pack { using common_entity_type = std::common_type_t<typename View::entity_type, typename Other::entity_type...>; class view_pack_iterator { friend class view_pack<View, Other...>; using underlying_iterator = typename View::iterator; view_pack_iterator(underlying_iterator from, underlying_iterator to, const std::tuple<View, Other...> &ref) ENTT_NOEXCEPT : it{from}, last{to}, pack{std::get<Other>(ref)...} { if(it != last && !valid()) { ++(*this); } } [[nodiscard]] bool valid() const { const auto entity = *it; return (std::get<Other>(pack).contains(entity) && ...); } public: using difference_type = typename std::iterator_traits<underlying_iterator>::difference_type; using value_type = decltype(*std::declval<underlying_iterator>()); using pointer = void; using reference = value_type; using iterator_category = std::input_iterator_tag; view_pack_iterator & operator++() ENTT_NOEXCEPT { while(++it != last && !valid()); return *this; } view_pack_iterator operator++(int) ENTT_NOEXCEPT { view_pack_iterator orig = *this; return ++(*this), orig; } [[nodiscard]] reference operator*() const { return *it; } [[nodiscard]] bool operator==(const view_pack_iterator &other) const ENTT_NOEXCEPT { return other.it == it; } [[nodiscard]] bool operator!=(const view_pack_iterator &other) const ENTT_NOEXCEPT { return !(*this == other); } private: underlying_iterator it; const underlying_iterator last; const std::tuple<Other...> pack; }; class iterable_view_pack { friend class view_pack<View, Other...>; using iterable_view = decltype(std::declval<View>().each()); class iterable_view_pack_iterator { friend class iterable_view_pack; using underlying_iterator = typename iterable_view::iterator; iterable_view_pack_iterator(underlying_iterator from, underlying_iterator to, const std::tuple<Other...> &ref) ENTT_NOEXCEPT : it{from}, last{to}, pack{ref} { if(it != last && !valid()) { ++(*this); } } [[nodiscard]] bool valid() const { const auto entity = std::get<0>(*it); return (std::get<Other>(pack).contains(entity) && ...); } public: using difference_type = typename std::iterator_traits<underlying_iterator>::difference_type; using value_type = decltype(std::tuple_cat(*std::declval<underlying_iterator>(), std::declval<Other>().get({})...)); using pointer = void; using reference = value_type; using iterator_category = std::input_iterator_tag; iterable_view_pack_iterator & operator++() ENTT_NOEXCEPT { while(++it != last && !valid()); return *this; } iterable_view_pack_iterator operator++(int) ENTT_NOEXCEPT { iterable_view_pack_iterator orig = *this; return ++(*this), orig; } [[nodiscard]] reference operator*() const { const auto curr = *it; return std::tuple_cat(curr, std::get<Other>(pack).get(std::get<0>(curr))...); } [[nodiscard]] bool operator==(const iterable_view_pack_iterator &other) const ENTT_NOEXCEPT { return other.it == it; } [[nodiscard]] bool operator!=(const iterable_view_pack_iterator &other) const ENTT_NOEXCEPT { return !(*this == other); } private: underlying_iterator it; const underlying_iterator last; const std::tuple<Other...> pack; }; iterable_view_pack(const std::tuple<View, Other...> &ref) : iterable{std::get<View>(ref).each()}, pack{std::get<Other>(ref)...} {} public: using iterator = iterable_view_pack_iterator; [[nodiscard]] iterator begin() const ENTT_NOEXCEPT { return { iterable.begin(), iterable.end(), pack }; } [[nodiscard]] iterator end() const ENTT_NOEXCEPT { return { iterable.end(), iterable.end(), pack }; } private: iterable_view iterable; std::tuple<Other...> pack; }; public: /*! @brief Underlying entity identifier. */ using entity_type = common_entity_type; /*! @brief Input iterator type. */ using iterator = view_pack_iterator; /** * @brief Constructs a pack from a bunch of views. * @param view A reference to the leading view for the pack. * @param other References to the other views to use to construct the pack. */ view_pack(const View &view, const Other &... other) : pack{view, other...} {} /** * @brief Returns an iterator to the first entity of the pack. * * The returned iterator points to the first entity of the pack. If the pack * is empty, the returned iterator will be equal to `end()`. * * @note * Iterators stay true to the order imposed by the first view of the pack. * * @return An iterator to the first entity of the pack. */ [[nodiscard]] iterator begin() const ENTT_NOEXCEPT { return { std::get<View>(pack).begin(), std::get<View>(pack).end(), pack }; } /** * @brief Returns an iterator that is past the last entity of the pack. * * The returned iterator points to the entity following the last entity of * the pack. Attempting to dereference the returned iterator results in * undefined behavior. * * @note * Iterators stay true to the order imposed by the first view of the pack. * * @return An iterator to the entity following the last entity of the pack. */ [[nodiscard]] iterator end() const ENTT_NOEXCEPT { return { std::get<View>(pack).end(), std::get<View>(pack).end(), pack }; } /** * @brief Iterates entities and components and applies the given function * object to them. * * The function object is invoked for each entity. It is provided with the * entity itself and a set of references to non-empty components. The * _constness_ of the components is as requested.<br/> * The signature of the function must be equivalent to one of the following * forms: * * @code{.cpp} * void(const entity_type, Type &...); * void(Type &...); * @endcode * * @note * Empty types aren't explicitly instantiated and therefore they are never * returned during iterations. * * @tparam Func Type of the function object to invoke. * @param func A valid function object. */ template<typename Func> void each(Func func) const { for(auto value: std::get<View>(pack).each()) { const auto entity = std::get<0>(value); if((std::get<Other>(pack).contains(entity) && ...)) { std::apply(func, std::tuple_cat(value, std::get<Other>(pack).get(entity)...)); } } } /** * @brief Returns an iterable object to use to _visit_ the pack. * * The iterable object returns tuples that contain the current entity and a * set of references to its non-empty components. The _constness_ of the * components is as requested. * * @note * Empty types aren't explicitly instantiated and therefore they are never * returned during iterations. * * @return An iterable object to use to _visit_ the pack. */ [[nodiscard]] iterable_view_pack each() const ENTT_NOEXCEPT { return pack; } /** * @brief Returns a copy of the requested view from a pack. * @tparam Type Type of the view to return. * @return A copy of the requested view from the pack. */ template<typename Type> operator Type() const ENTT_NOEXCEPT { return std::get<Type>(pack); } /** * @brief Appends a view to a pack. * @tparam Args View template arguments. * @param view A reference to a view to append to the pack. * @return The extended pack. */ template<typename... Args> [[nodiscard]] auto operator|(const basic_view<Args...> &view) const { return std::make_from_tuple<view_pack<View, Other..., basic_view<Args...>>>(std::tuple_cat(pack, std::make_tuple(view))); } /** * @brief Appends a pack and therefore all its views to another pack. * @tparam Pack Types of views of the pack to append. * @param other A reference to the pack to append. * @return The extended pack. */ template<typename... Pack> [[nodiscard]] auto operator|(const view_pack<Pack...> &other) const { return std::make_from_tuple<view_pack<View, Other..., Pack...>>(std::tuple_cat(pack, std::make_tuple(static_cast<Pack>(other)...))); } private: std::tuple<View, Other...> pack; }; /** * @brief Combines two views in a pack. * @tparam Args Template arguments of the first view. * @tparam Other Template arguments of the second view. * @param lhs A reference to the first view with which to create the pack. * @param rhs A reference to the second view with which to create the pack. * @return A pack that combines the two views in a single iterable object. */ template<typename... Args, typename... Other> [[nodiscard]] auto operator|(const basic_view<Args...> &lhs, const basic_view<Other...> &rhs) { return view_pack{lhs, rhs}; } /** * @brief Combines a view with a pack. * @tparam Args View template arguments. * @tparam Pack Types of views of the pack. * @param view A reference to the view to combine with the pack. * @param pack A reference to the pack to combine with the view. * @return The extended pack. */ template<typename... Args, typename... Pack> [[nodiscard]] auto operator|(const basic_view<Args...> &view, const view_pack<Pack...> &pack) { return view_pack{view} | pack; } } #endif <|endoftext|>
<commit_before><commit_msg>/.. at the end of paths should also be removed, used in conjunction with ORIGIN<commit_after><|endoftext|>
<commit_before><commit_msg>Resolved memory bug, hopefully not by adding another one.<commit_after><|endoftext|>
<commit_before>/* * mod.cpp * * Created on: August, 2014 * Author: Adrien Perkins */ #include "common.h" #include "serial_port.h" #include "read_thread.h" #include "wifly_thread.h" #include "mod.h" #include "dirk_thread.h" using std::string; using namespace std; // variable declarations bool verbose = false; // default verbose to false bool debug = false; // default debug to false bool nowifly = false; // default to wanting wifly bool get_commands = false; // default for whether or not we want to read the command file bool dual_wifly = false; // default to only have one wifly active bool phased_array = false; // default to not using a phased array antenna bool execute_tracking = false; // default to not executing a tracking mission float flight_alt = 380; // default flight is AMSL MAVInfo uav; // object to hold all the state information on the UAV int RUNNING_FLAG = 1; // default the read and write threads to be running char* wifly_port1; char* wifly_port2; char* pa_port; /** * read in the passed arguments to the function on start * * TODO: figure out what to return and how to handle uart and baud values */ void read_arguments(int argc, char **argv, char **uart_name, int *baudrate, char **wifly1, char **wifly2) { // string to be displayed on incorrect inputs to show correct function usage const char *commandline_usage = "\tusage: %s -d <devicename> -b <baudrate> [options]\n\n" "\t-v/--verbose\t\t detailed output of current state\n" "\n\t\tdefault: -d %s -b %i\n"; // loop through all the program arguments for (int i = 1; i < argc; i++) { /* argv[0] is "mavlink" */ // help text requested if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0) { printf(commandline_usage, argv[0], *uart_name, *baudrate); throw EXIT_FAILURE; } /* UART device ID */ if (strcmp(argv[i], "-d") == 0 || strcmp(argv[i], "--device") == 0) { if (argc > i + 1) { *uart_name = argv[i + 1]; } else { cout << "nope\n"; //printf(commandline_usage, argv[0], *uart_name, *baudrate); //throw EXIT_FAILURE; } } /* baud rate */ if (strcmp(argv[i], "-b") == 0 || strcmp(argv[i], "--baud") == 0) { if (argc > i + 1) { *baudrate = atoi(argv[i + 1]); } else { cout << "more nope\n"; //printf(commandline_usage, argv[0], *uart_name, *baudrate); //throw EXIT_FAILURE; } } /* verbosity */ if (strcmp(argv[i], "-v") == 0 || strcmp(argv[i], "--verbose") == 0) { verbose = true; } /* debug */ if (strcmp(argv[i], "-v") == 0 || strcmp(argv[i], "--debug") == 0) { debug = true; } /* wifly state */ if (strcmp(argv[i], "-nw") == 0 || strcmp(argv[i], "--nowifly") == 0) { nowifly = true; } /* command file state */ if (strcmp(argv[i], "-c") == 0 || strcmp(argv[i], "--commands") == 0) { get_commands = true; } /* wifly 1 port */ if (strcmp(argv[i], "-w1") == 0 || strcmp(argv[i], "--wifly1") == 0) { *wifly1 = argv[i + 1]; } /* wifly 2 port */ if (strcmp(argv[i], "-w2") == 0 || strcmp(argv[i], "--wifly2") == 0) { *wifly2 = argv[i + 1]; dual_wifly = true; } /* phased array port */ if (strcmp(argv[i], "-pa") == 0 || strcmp(argv[i], "--phased") == 0) { phased_array = true; } /* whether or not executing a tracking mission */ if (strcmp(argv[i], "-pp") == 0 || strcmp(argv[i], "--planning") == 0) { execute_tracking = true; } } } void quit_handler(int sig) { // notify user of termination printf("Terminating script\n"); // set the running flag to 0 to kill all loops RUNNING_FLAG = 0; end_serial(); } int main(int argc, char **argv) { cout << "starting...\n"; printf("printf starting...\n"); // ids of the threads pthread_t readId; pthread_t wiflyId; pthread_t phasedId; /* default values for arguments */ char *uart_name = (char*)"/dev/ttyUSB1"; wifly_port1 = (char*) "/dev/ttyUSB0"; wifly_port2 = (char*) "/dev/ttyUSB2"; int baudrate = 115200; cout << "reading arguments\n"; // read the input arguments read_arguments(argc, argv, &uart_name, &baudrate, &wifly_port1, &wifly_port2); // open and configure the com port being used for communication //begin_serial(uart_name, baudrate); // setup termination using CRT-C signal(SIGINT, quit_handler); // need to create read and write threads cout<< "handling threads\n"; //pthread_create(&readId, NULL, read_thread, (void *)&uav); // create a thread for the wifly stuff (only if want wifly running) if (!nowifly && !phased_array) { printf("starting wifly thread...\n"); pthread_create(&wiflyId, NULL, wifly_thread, (void *)&uav); } if (phased_array) { printf("starting dirk antenna thread...\n"); pthread_create(&phasedId, NULL, dirk_thread, (void *)&uav); } //pthread_join(readId, NULL); if (!nowifly && !phased_array) { pthread_join(wiflyId, NULL); } if (phased_array) { pthread_join(phasedId, NULL); } // pthread_join(wiflyId, NULL); // pthread_join(phasedId, NULL); end_serial(); return 0; } <commit_msg>bring back ability to read from the pixhawk<commit_after>/* * mod.cpp * * Created on: August, 2014 * Author: Adrien Perkins */ #include "common.h" #include "serial_port.h" #include "read_thread.h" #include "wifly_thread.h" #include "mod.h" #include "dirk_thread.h" using std::string; using namespace std; // variable declarations bool verbose = false; // default verbose to false bool debug = false; // default debug to false bool nowifly = false; // default to wanting wifly bool get_commands = false; // default for whether or not we want to read the command file bool dual_wifly = false; // default to only have one wifly active bool phased_array = false; // default to not using a phased array antenna bool execute_tracking = false; // default to not executing a tracking mission float flight_alt = 380; // default flight is AMSL MAVInfo uav; // object to hold all the state information on the UAV int RUNNING_FLAG = 1; // default the read and write threads to be running char* wifly_port1; char* wifly_port2; char* pa_port; /** * read in the passed arguments to the function on start * * TODO: figure out what to return and how to handle uart and baud values */ void read_arguments(int argc, char **argv, char **uart_name, int *baudrate, char **wifly1, char **wifly2) { // string to be displayed on incorrect inputs to show correct function usage const char *commandline_usage = "\tusage: %s -d <devicename> -b <baudrate> [options]\n\n" "\t-v/--verbose\t\t detailed output of current state\n" "\n\t\tdefault: -d %s -b %i\n"; // loop through all the program arguments for (int i = 1; i < argc; i++) { /* argv[0] is "mavlink" */ // help text requested if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0) { printf(commandline_usage, argv[0], *uart_name, *baudrate); throw EXIT_FAILURE; } /* UART device ID */ if (strcmp(argv[i], "-d") == 0 || strcmp(argv[i], "--device") == 0) { if (argc > i + 1) { *uart_name = argv[i + 1]; } else { cout << "nope\n"; //printf(commandline_usage, argv[0], *uart_name, *baudrate); //throw EXIT_FAILURE; } } /* baud rate */ if (strcmp(argv[i], "-b") == 0 || strcmp(argv[i], "--baud") == 0) { if (argc > i + 1) { *baudrate = atoi(argv[i + 1]); } else { cout << "more nope\n"; //printf(commandline_usage, argv[0], *uart_name, *baudrate); //throw EXIT_FAILURE; } } /* verbosity */ if (strcmp(argv[i], "-v") == 0 || strcmp(argv[i], "--verbose") == 0) { verbose = true; } /* debug */ if (strcmp(argv[i], "-v") == 0 || strcmp(argv[i], "--debug") == 0) { debug = true; } /* wifly state */ if (strcmp(argv[i], "-nw") == 0 || strcmp(argv[i], "--nowifly") == 0) { nowifly = true; } /* command file state */ if (strcmp(argv[i], "-c") == 0 || strcmp(argv[i], "--commands") == 0) { get_commands = true; } /* wifly 1 port */ if (strcmp(argv[i], "-w1") == 0 || strcmp(argv[i], "--wifly1") == 0) { *wifly1 = argv[i + 1]; } /* wifly 2 port */ if (strcmp(argv[i], "-w2") == 0 || strcmp(argv[i], "--wifly2") == 0) { *wifly2 = argv[i + 1]; dual_wifly = true; } /* phased array port */ if (strcmp(argv[i], "-pa") == 0 || strcmp(argv[i], "--phased") == 0) { phased_array = true; } /* whether or not executing a tracking mission */ if (strcmp(argv[i], "-pp") == 0 || strcmp(argv[i], "--planning") == 0) { execute_tracking = true; } } } void quit_handler(int sig) { // notify user of termination printf("Terminating script\n"); // set the running flag to 0 to kill all loops RUNNING_FLAG = 0; end_serial(); } int main(int argc, char **argv) { cout << "starting...\n"; printf("printf starting...\n"); // ids of the threads pthread_t readId; pthread_t wiflyId; pthread_t phasedId; /* default values for arguments */ char *uart_name = (char*)"/dev/ttyUSB1"; wifly_port1 = (char*) "/dev/ttyUSB0"; wifly_port2 = (char*) "/dev/ttyUSB2"; int baudrate = 115200; cout << "reading arguments\n"; // read the input arguments read_arguments(argc, argv, &uart_name, &baudrate, &wifly_port1, &wifly_port2); // open and configure the com port being used for communication begin_serial(uart_name, baudrate); // setup termination using CRT-C signal(SIGINT, quit_handler); // need to create read and write threads cout<< "handling threads\n"; pthread_create(&readId, NULL, read_thread, (void *)&uav); // create a thread for the wifly stuff (only if want wifly running) if (!nowifly && !phased_array) { printf("starting wifly thread...\n"); pthread_create(&wiflyId, NULL, wifly_thread, (void *)&uav); } if (phased_array) { printf("starting dirk antenna thread...\n"); pthread_create(&phasedId, NULL, dirk_thread, (void *)&uav); } pthread_join(readId, NULL); if (!nowifly && !phased_array) { pthread_join(wiflyId, NULL); } if (phased_array) { pthread_join(phasedId, NULL); } // pthread_join(wiflyId, NULL); // pthread_join(phasedId, NULL); end_serial(); return 0; } <|endoftext|>
<commit_before>#include <imageprocessing/ComponentTree.h> #include <imageprocessing/Mser.h> #include <sopnet/features/Overlap.h> #include <util/ProgramOptions.h> #include "ComponentTreeConverter.h" #include "StackSliceExtractor.h" static logger::LogChannel stacksliceextractorlog("stacksliceextractorlog", "[StackSliceExtractor] "); util::ProgramOption optionSimilarityThreshold( util::_module = "sopnet.slices", util::_long_name = "similarityThreshold", util::_description_text = "The minimum normalized overlap [#overlap/(#size1 + #size2 - #overlap)] for which two slices are considered the same.", util::_default_value = 0.75); util::ProgramOption optionSetDifferenceThreshold( util::_module = "sopnet.slices", util::_long_name = "setDifferenceThreshold", util::_description_text = "The maximal set difference for which two slices are considered the same.", util::_default_value = 200); StackSliceExtractor::StackSliceExtractor(unsigned int section) : _section(section), _sliceImageExtractor(boost::make_shared<ImageExtractor>()), _mserParameters(boost::make_shared<MserParameters>()), _sliceCollector(boost::make_shared<SliceCollector>()) { registerInput(_sliceImageStack, "slices"); registerInput(_forceExplanation, "force explanation"); registerOutput(_sliceCollector->getOutput("slices"), "slices"); registerOutput(_sliceCollector->getOutput("conflict sets"), "conflict sets"); _sliceImageStack.registerCallback(&StackSliceExtractor::onInputSet, this); // set default mser parameters from program options _mserParameters->darkToBright = false; _mserParameters->brightToDark = true; _mserParameters->minArea = 0; _mserParameters->maxArea = 100000000; } void StackSliceExtractor::onInputSet(const pipeline::InputSet<ImageStack>&) { LOG_DEBUG(stacksliceextractorlog) << "image stack set" << std::endl; // connect input image stack to slice image extractor _sliceImageExtractor->setInput(_sliceImageStack.getAssignedOutput()); // clear slice collector content _sliceCollector->clearInputs(0); // for each image in the stack, set up the pipeline for (unsigned int i = 0; i < _sliceImageStack->size(); i++) { boost::shared_ptr<Mser<unsigned char> > mser = boost::make_shared<Mser<unsigned char> >(); mser->setInput("image", _sliceImageExtractor->getOutput(i)); mser->setInput("parameters", _mserParameters); boost::shared_ptr<ComponentTreeConverter> converter = boost::make_shared<ComponentTreeConverter>(_section); converter->setInput(mser->getOutput()); _sliceCollector->addInput(converter->getOutput()); } LOG_DEBUG(stacksliceextractorlog) << "internal pipeline set up" << std::endl; } StackSliceExtractor::SliceCollector::SliceCollector() { registerInputs(_slices, "slices"); registerOutput(_allSlices, "slices"); registerOutput(_conflictSets, "conflict sets"); } void StackSliceExtractor::SliceCollector::updateOutputs() { /* * initialise */ _allSlices->clear(); _conflictSets->clear(); // create a copy of the input slice collections std::vector<Slices> inputSlices; foreach (boost::shared_ptr<Slices> slices, _slices) inputSlices.push_back(*slices); // remove all duplicates from the slice collections inputSlices = removeDuplicates(inputSlices); // create outputs extractSlices(inputSlices); extractConstraints(inputSlices); LOG_DEBUG(stacksliceextractorlog) << _allSlices->size() << " slices found" << std::endl; LOG_DEBUG(stacksliceextractorlog) << _conflictSets->size() << " conflict sets found" << std::endl; } unsigned int StackSliceExtractor::SliceCollector::countSlices(const std::vector<Slices>& slices) { unsigned int numSlices = 0; for (unsigned int level = 0; level < slices.size(); level++) numSlices += slices[level].size(); return numSlices; } std::vector<Slices> StackSliceExtractor::SliceCollector::removeDuplicates(const std::vector<Slices>& slices) { LOG_DEBUG(stacksliceextractorlog) << "removing duplicates from " << countSlices(slices) << " slices" << std::endl; unsigned int oldSize = 0; unsigned int newSize = countSlices(slices); std::vector<Slices> withoutDuplicates = slices; while (oldSize != newSize) { LOG_DEBUG(stacksliceextractorlog) << "current size is " << countSlices(withoutDuplicates) << std::endl; withoutDuplicates = removeDuplicatesPass(withoutDuplicates); LOG_DEBUG(stacksliceextractorlog) << "new size is " << countSlices(withoutDuplicates) << std::endl; oldSize = newSize; newSize = countSlices(withoutDuplicates); } LOG_DEBUG(stacksliceextractorlog) << "removed " << (countSlices(slices) - countSlices(withoutDuplicates)) << " slices" << std::endl; return withoutDuplicates; } std::vector<Slices> StackSliceExtractor::SliceCollector::removeDuplicatesPass(const std::vector<Slices>& allSlices) { std::vector<Slices> slices = allSlices; Overlap normalizedOverlap(true /* normalize */, false /* don't align */); double overlapThreshold = optionSimilarityThreshold; unsigned int setDifferenceThreshold = optionSetDifferenceThreshold; // for all levels for (unsigned int level = 0; level < slices.size(); level++) { // for each slice foreach (boost::shared_ptr<Slice> slice, slices[level]) { std::vector<boost::shared_ptr<Slice> > duplicates; // for all sub-levels for (unsigned int subLevel = level + 1; subLevel < slices.size(); subLevel++) { std::vector<boost::shared_ptr<Slice> > toBeRemoved; // for each slice foreach (boost::shared_ptr<Slice> subSlice, slices[subLevel]) { // if the overlap exceeds the threshold... if (normalizedOverlap.exceeds(*slice, *subSlice, overlapThreshold)) { // get the set difference Overlap nonNormalizedOverlap(false, false); int overlap = nonNormalizedOverlap(*slice, *subSlice); int sliceSize = slice->getComponent()->getSize(); int subSliceSize = subSlice->getComponent()->getSize(); // ...and the set difference is small enough, store // subSlice as aduplicate of slice unsigned int setDifference = (sliceSize - overlap) + (subSliceSize - overlap); if (setDifference < setDifferenceThreshold) { duplicates.push_back(subSlice); toBeRemoved.push_back(subSlice); } } } // remove duplicates from this level foreach (boost::shared_ptr<Slice> subSlice, toBeRemoved) slices[subLevel].remove(subSlice); } // replace slice and duplicates by their intersection foreach (boost::shared_ptr<Slice> duplicate, duplicates) { LOG_ALL(stacksliceextractorlog) << "intersecting " << slice->getId() << " and " << duplicate->getId() << std::endl; LOG_ALL(stacksliceextractorlog) << "previous size was " << slice->getComponent()->getSize() << std::endl; slice->intersect(*duplicate); LOG_ALL(stacksliceextractorlog) << "new size is " << slice->getComponent()->getSize() << std::endl; } } } return slices; } void StackSliceExtractor::SliceCollector::extractSlices(const std::vector<Slices>& slices) { // for all levels for (unsigned int level = 0; level < slices.size(); level++) _allSlices->addAll(slices[level]); } void StackSliceExtractor::SliceCollector::extractConstraints(const std::vector<Slices>& slices) { Overlap overlap(false /* don't normlize */, false /* don't align */); std::vector<unsigned int> conflictIds(2); // for all levels for (unsigned int level = 0; level < slices.size(); level++) { // for each slice foreach (boost::shared_ptr<Slice> slice, slices[level]) { unsigned int numOverlaps = 0; // for all sub-levels for (unsigned int subLevel = level + 1; subLevel < slices.size(); subLevel++) { // for each slice foreach (boost::shared_ptr<Slice> subSlice, slices[subLevel]) { // if there is overlap, add a consistency constraint if (overlap.exceeds(*slice, *subSlice, 0)) { conflictIds[0] = slice->getId(); conflictIds[1] = subSlice->getId(); _allSlices->addConflicts(conflictIds); ConflictSet conflictSet; conflictSet.addSlice(slice->getId()); conflictSet.addSlice(subSlice->getId()); _conflictSets->add(conflictSet); } } } // if there is no overlap with other slices, make sure that this // slice will be picked at most once if (numOverlaps == 0) { ConflictSet conflictSet; conflictSet.addSlice(slice->getId()); _conflictSets->add(conflictSet); } } } } <commit_msg>bugfix: StackSliceExtractor did not create output data<commit_after>#include <imageprocessing/ComponentTree.h> #include <imageprocessing/Mser.h> #include <sopnet/features/Overlap.h> #include <util/ProgramOptions.h> #include "ComponentTreeConverter.h" #include "StackSliceExtractor.h" static logger::LogChannel stacksliceextractorlog("stacksliceextractorlog", "[StackSliceExtractor] "); util::ProgramOption optionSimilarityThreshold( util::_module = "sopnet.slices", util::_long_name = "similarityThreshold", util::_description_text = "The minimum normalized overlap [#overlap/(#size1 + #size2 - #overlap)] for which two slices are considered the same.", util::_default_value = 0.75); util::ProgramOption optionSetDifferenceThreshold( util::_module = "sopnet.slices", util::_long_name = "setDifferenceThreshold", util::_description_text = "The maximal set difference for which two slices are considered the same.", util::_default_value = 200); StackSliceExtractor::StackSliceExtractor(unsigned int section) : _section(section), _sliceImageExtractor(boost::make_shared<ImageExtractor>()), _mserParameters(boost::make_shared<MserParameters>()), _sliceCollector(boost::make_shared<SliceCollector>()) { registerInput(_sliceImageStack, "slices"); registerInput(_forceExplanation, "force explanation"); registerOutput(_sliceCollector->getOutput("slices"), "slices"); registerOutput(_sliceCollector->getOutput("conflict sets"), "conflict sets"); _sliceImageStack.registerCallback(&StackSliceExtractor::onInputSet, this); // set default mser parameters from program options _mserParameters->darkToBright = false; _mserParameters->brightToDark = true; _mserParameters->minArea = 0; _mserParameters->maxArea = 100000000; } void StackSliceExtractor::onInputSet(const pipeline::InputSet<ImageStack>&) { LOG_DEBUG(stacksliceextractorlog) << "image stack set" << std::endl; // connect input image stack to slice image extractor _sliceImageExtractor->setInput(_sliceImageStack.getAssignedOutput()); // clear slice collector content _sliceCollector->clearInputs(0); // for each image in the stack, set up the pipeline for (unsigned int i = 0; i < _sliceImageStack->size(); i++) { boost::shared_ptr<Mser<unsigned char> > mser = boost::make_shared<Mser<unsigned char> >(); mser->setInput("image", _sliceImageExtractor->getOutput(i)); mser->setInput("parameters", _mserParameters); boost::shared_ptr<ComponentTreeConverter> converter = boost::make_shared<ComponentTreeConverter>(_section); converter->setInput(mser->getOutput()); _sliceCollector->addInput(converter->getOutput()); } LOG_DEBUG(stacksliceextractorlog) << "internal pipeline set up" << std::endl; } StackSliceExtractor::SliceCollector::SliceCollector() : _allSlices(new Slices()), _conflictSets(new ConflictSets()) { registerInputs(_slices, "slices"); registerOutput(_allSlices, "slices"); registerOutput(_conflictSets, "conflict sets"); } void StackSliceExtractor::SliceCollector::updateOutputs() { /* * initialise */ _allSlices->clear(); _conflictSets->clear(); // create a copy of the input slice collections std::vector<Slices> inputSlices; foreach (boost::shared_ptr<Slices> slices, _slices) inputSlices.push_back(*slices); // remove all duplicates from the slice collections inputSlices = removeDuplicates(inputSlices); // create outputs extractSlices(inputSlices); extractConstraints(inputSlices); LOG_DEBUG(stacksliceextractorlog) << _allSlices->size() << " slices found" << std::endl; LOG_DEBUG(stacksliceextractorlog) << _conflictSets->size() << " conflict sets found" << std::endl; } unsigned int StackSliceExtractor::SliceCollector::countSlices(const std::vector<Slices>& slices) { unsigned int numSlices = 0; for (unsigned int level = 0; level < slices.size(); level++) numSlices += slices[level].size(); return numSlices; } std::vector<Slices> StackSliceExtractor::SliceCollector::removeDuplicates(const std::vector<Slices>& slices) { LOG_DEBUG(stacksliceextractorlog) << "removing duplicates from " << countSlices(slices) << " slices" << std::endl; unsigned int oldSize = 0; unsigned int newSize = countSlices(slices); std::vector<Slices> withoutDuplicates = slices; while (oldSize != newSize) { LOG_DEBUG(stacksliceextractorlog) << "current size is " << countSlices(withoutDuplicates) << std::endl; withoutDuplicates = removeDuplicatesPass(withoutDuplicates); LOG_DEBUG(stacksliceextractorlog) << "new size is " << countSlices(withoutDuplicates) << std::endl; oldSize = newSize; newSize = countSlices(withoutDuplicates); } LOG_DEBUG(stacksliceextractorlog) << "removed " << (countSlices(slices) - countSlices(withoutDuplicates)) << " slices" << std::endl; return withoutDuplicates; } std::vector<Slices> StackSliceExtractor::SliceCollector::removeDuplicatesPass(const std::vector<Slices>& allSlices) { std::vector<Slices> slices = allSlices; Overlap normalizedOverlap(true /* normalize */, false /* don't align */); double overlapThreshold = optionSimilarityThreshold; unsigned int setDifferenceThreshold = optionSetDifferenceThreshold; // for all levels for (unsigned int level = 0; level < slices.size(); level++) { // for each slice foreach (boost::shared_ptr<Slice> slice, slices[level]) { std::vector<boost::shared_ptr<Slice> > duplicates; // for all sub-levels for (unsigned int subLevel = level + 1; subLevel < slices.size(); subLevel++) { std::vector<boost::shared_ptr<Slice> > toBeRemoved; // for each slice foreach (boost::shared_ptr<Slice> subSlice, slices[subLevel]) { // if the overlap exceeds the threshold... if (normalizedOverlap.exceeds(*slice, *subSlice, overlapThreshold)) { // get the set difference Overlap nonNormalizedOverlap(false, false); int overlap = nonNormalizedOverlap(*slice, *subSlice); int sliceSize = slice->getComponent()->getSize(); int subSliceSize = subSlice->getComponent()->getSize(); // ...and the set difference is small enough, store // subSlice as aduplicate of slice unsigned int setDifference = (sliceSize - overlap) + (subSliceSize - overlap); if (setDifference < setDifferenceThreshold) { duplicates.push_back(subSlice); toBeRemoved.push_back(subSlice); } } } // remove duplicates from this level foreach (boost::shared_ptr<Slice> subSlice, toBeRemoved) slices[subLevel].remove(subSlice); } // replace slice and duplicates by their intersection foreach (boost::shared_ptr<Slice> duplicate, duplicates) { LOG_ALL(stacksliceextractorlog) << "intersecting " << slice->getId() << " and " << duplicate->getId() << std::endl; LOG_ALL(stacksliceextractorlog) << "previous size was " << slice->getComponent()->getSize() << std::endl; slice->intersect(*duplicate); LOG_ALL(stacksliceextractorlog) << "new size is " << slice->getComponent()->getSize() << std::endl; } } } return slices; } void StackSliceExtractor::SliceCollector::extractSlices(const std::vector<Slices>& slices) { // for all levels for (unsigned int level = 0; level < slices.size(); level++) _allSlices->addAll(slices[level]); } void StackSliceExtractor::SliceCollector::extractConstraints(const std::vector<Slices>& slices) { Overlap overlap(false /* don't normlize */, false /* don't align */); std::vector<unsigned int> conflictIds(2); // for all levels for (unsigned int level = 0; level < slices.size(); level++) { // for each slice foreach (boost::shared_ptr<Slice> slice, slices[level]) { unsigned int numOverlaps = 0; // for all sub-levels for (unsigned int subLevel = level + 1; subLevel < slices.size(); subLevel++) { // for each slice foreach (boost::shared_ptr<Slice> subSlice, slices[subLevel]) { // if there is overlap, add a consistency constraint if (overlap.exceeds(*slice, *subSlice, 0)) { conflictIds[0] = slice->getId(); conflictIds[1] = subSlice->getId(); _allSlices->addConflicts(conflictIds); ConflictSet conflictSet; conflictSet.addSlice(slice->getId()); conflictSet.addSlice(subSlice->getId()); _conflictSets->add(conflictSet); } } } // if there is no overlap with other slices, make sure that this // slice will be picked at most once if (numOverlaps == 0) { ConflictSet conflictSet; conflictSet.addSlice(slice->getId()); _conflictSets->add(conflictSet); } } } } <|endoftext|>
<commit_before>//===-- CommandObjectDisassemble.cpp ----------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "CommandObjectDisassemble.h" // C Includes // C++ Includes // Other libraries and framework includes // Project includes #include "lldb/Core/AddressRange.h" #include "lldb/Interpreter/Args.h" #include "lldb/Interpreter/CommandCompletions.h" #include "lldb/Interpreter/CommandInterpreter.h" #include "lldb/Interpreter/CommandReturnObject.h" #include "lldb/Core/Disassembler.h" #include "lldb/Interpreter/Options.h" #include "lldb/Core/SourceManager.h" #include "lldb/Target/StackFrame.h" #include "lldb/Symbol/Symbol.h" #include "lldb/Target/Process.h" #include "lldb/Target/Target.h" #define DEFAULT_DISASM_BYTE_SIZE 32 using namespace lldb; using namespace lldb_private; CommandObjectDisassemble::CommandOptions::CommandOptions () : Options(), m_func_name(), m_start_addr(), m_end_addr () { ResetOptionValues(); } CommandObjectDisassemble::CommandOptions::~CommandOptions () { } Error CommandObjectDisassemble::CommandOptions::SetOptionValue (int option_idx, const char *option_arg) { Error error; char short_option = (char) m_getopt_table[option_idx].val; switch (short_option) { case 'm': show_mixed = true; break; case 'c': num_lines_context = Args::StringToUInt32(option_arg, 0, 0); break; case 'b': show_bytes = true; break; case 's': m_start_addr = Args::StringToUInt64(optarg, LLDB_INVALID_ADDRESS, 0); if (m_start_addr == LLDB_INVALID_ADDRESS) m_start_addr = Args::StringToUInt64(optarg, LLDB_INVALID_ADDRESS, 16); if (m_start_addr == LLDB_INVALID_ADDRESS) error.SetErrorStringWithFormat ("Invalid start address string '%s'.\n", optarg); break; case 'e': m_end_addr = Args::StringToUInt64(optarg, LLDB_INVALID_ADDRESS, 0); if (m_end_addr == LLDB_INVALID_ADDRESS) m_end_addr = Args::StringToUInt64(optarg, LLDB_INVALID_ADDRESS, 16); if (m_end_addr == LLDB_INVALID_ADDRESS) error.SetErrorStringWithFormat ("Invalid end address string '%s'.\n", optarg); break; case 'n': m_func_name = option_arg; break; case 'r': raw = true; break; default: error.SetErrorStringWithFormat("Unrecognized short option '%c'.\n", short_option); break; } return error; } void CommandObjectDisassemble::CommandOptions::ResetOptionValues () { Options::ResetOptionValues(); show_mixed = false; show_bytes = false; num_lines_context = 0; m_func_name.clear(); m_start_addr = LLDB_INVALID_ADDRESS; m_end_addr = LLDB_INVALID_ADDRESS; raw = false; } const lldb::OptionDefinition* CommandObjectDisassemble::CommandOptions::GetDefinitions () { return g_option_table; } lldb::OptionDefinition CommandObjectDisassemble::CommandOptions::g_option_table[] = { { LLDB_OPT_SET_ALL, false, "bytes", 'b', no_argument, NULL, 0, eArgTypeNone, "Show opcode bytes when disassembling."}, { LLDB_OPT_SET_ALL, false, "context", 'c', required_argument, NULL, 0, eArgTypeNumLines, "Number of context lines of source to show."}, { LLDB_OPT_SET_ALL, false, "mixed", 'm', no_argument, NULL, 0, eArgTypeNone, "Enable mixed source and assembly display."}, { LLDB_OPT_SET_ALL, false, "raw", 'r', no_argument, NULL, 0, eArgTypeNone, "Print raw disassembly with no symbol information."}, { LLDB_OPT_SET_1, true, "start-address", 's', required_argument, NULL, 0, eArgTypeAddress, "Address to start disassembling."}, { LLDB_OPT_SET_1, false, "end-address", 'e', required_argument, NULL, 0, eArgTypeAddress, "Address to start disassembling."}, { LLDB_OPT_SET_2, true, "name", 'n', required_argument, NULL, CommandCompletions::eSymbolCompletion, eArgTypeFunctionName, "Disassemble entire contents of the given function name."}, //{ LLDB_OPT_SET_3, false, "current-frame", 'f', no_argument, NULL, 0, "<current-frame>", "Disassemble entire contents of the current frame's function."}, { 0, false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL } }; //------------------------------------------------------------------------- // CommandObjectDisassemble //------------------------------------------------------------------------- CommandObjectDisassemble::CommandObjectDisassemble (CommandInterpreter &interpreter) : CommandObject (interpreter, "disassemble", "Disassemble bytes in the current function, or elsewhere in the executable program as specified by the user.", "disassemble [<cmd-options>]") { } CommandObjectDisassemble::~CommandObjectDisassemble() { } bool CommandObjectDisassemble::Execute ( Args& command, CommandReturnObject &result ) { Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); if (target == NULL) { result.AppendError ("invalid target, set executable file using 'file' command"); result.SetStatus (eReturnStatusFailed); return false; } ArchSpec arch(target->GetArchitecture()); if (!arch.IsValid()) { result.AppendError ("target needs valid architecure in order to be able to disassemble"); result.SetStatus (eReturnStatusFailed); return false; } Disassembler *disassembler = Disassembler::FindPlugin(arch); if (disassembler == NULL) { result.AppendErrorWithFormat ("Unable to find Disassembler plug-in for %s architecture.\n", arch.AsCString()); result.SetStatus (eReturnStatusFailed); return false; } result.SetStatus (eReturnStatusSuccessFinishResult); if (command.GetArgumentCount() != 0) { result.AppendErrorWithFormat ("\"disassemble\" arguments are specified as options.\n"); GetOptions()->GenerateOptionUsage (m_interpreter, result.GetErrorStream(), this); result.SetStatus (eReturnStatusFailed); return false; } ExecutionContext exe_ctx(m_interpreter.GetDebugger().GetExecutionContext()); if (m_options.show_mixed && m_options.num_lines_context == 0) m_options.num_lines_context = 1; if (!m_options.m_func_name.empty()) { ConstString name(m_options.m_func_name.c_str()); if (Disassembler::Disassemble (m_interpreter.GetDebugger(), arch, exe_ctx, name, NULL, // Module * m_options.show_mixed ? m_options.num_lines_context : 0, m_options.show_bytes, result.GetOutputStream())) { result.SetStatus (eReturnStatusSuccessFinishResult); } else { result.AppendErrorWithFormat ("Unable to find symbol with name '%s'.\n", name.GetCString()); result.SetStatus (eReturnStatusFailed); } } else { AddressRange range; if (m_options.m_start_addr != LLDB_INVALID_ADDRESS) { range.GetBaseAddress().SetOffset (m_options.m_start_addr); if (m_options.m_end_addr != LLDB_INVALID_ADDRESS) { if (m_options.m_end_addr < m_options.m_start_addr) { result.AppendErrorWithFormat ("End address before start address.\n"); result.SetStatus (eReturnStatusFailed); return false; } range.SetByteSize (m_options.m_end_addr - m_options.m_start_addr); } else range.SetByteSize (DEFAULT_DISASM_BYTE_SIZE); } else { if (exe_ctx.frame) { SymbolContext sc(exe_ctx.frame->GetSymbolContext(eSymbolContextFunction | eSymbolContextSymbol)); if (sc.function) range = sc.function->GetAddressRange(); else if (sc.symbol && sc.symbol->GetAddressRangePtr()) range = *sc.symbol->GetAddressRangePtr(); else range.GetBaseAddress() = exe_ctx.frame->GetFrameCodeAddress(); } else { result.AppendError ("invalid frame"); result.SetStatus (eReturnStatusFailed); return false; } } if (range.GetByteSize() == 0) range.SetByteSize(DEFAULT_DISASM_BYTE_SIZE); if (Disassembler::Disassemble (m_interpreter.GetDebugger(), arch, exe_ctx, range, m_options.show_mixed ? m_options.num_lines_context : 0, m_options.show_bytes, result.GetOutputStream())) { result.SetStatus (eReturnStatusSuccessFinishResult); } else { result.AppendErrorWithFormat ("Failed to disassemble memory at 0x%8.8llx.\n", m_options.m_start_addr); result.SetStatus (eReturnStatusFailed); } } return result.Succeeded(); } <commit_msg>Uncomment/fix "-f" command option for disassemble command.<commit_after>//===-- CommandObjectDisassemble.cpp ----------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "CommandObjectDisassemble.h" // C Includes // C++ Includes // Other libraries and framework includes // Project includes #include "lldb/Core/AddressRange.h" #include "lldb/Interpreter/Args.h" #include "lldb/Interpreter/CommandCompletions.h" #include "lldb/Interpreter/CommandInterpreter.h" #include "lldb/Interpreter/CommandReturnObject.h" #include "lldb/Core/Disassembler.h" #include "lldb/Interpreter/Options.h" #include "lldb/Core/SourceManager.h" #include "lldb/Target/StackFrame.h" #include "lldb/Symbol/Symbol.h" #include "lldb/Target/Process.h" #include "lldb/Target/Target.h" #define DEFAULT_DISASM_BYTE_SIZE 32 using namespace lldb; using namespace lldb_private; CommandObjectDisassemble::CommandOptions::CommandOptions () : Options(), m_func_name(), m_start_addr(), m_end_addr () { ResetOptionValues(); } CommandObjectDisassemble::CommandOptions::~CommandOptions () { } Error CommandObjectDisassemble::CommandOptions::SetOptionValue (int option_idx, const char *option_arg) { Error error; char short_option = (char) m_getopt_table[option_idx].val; switch (short_option) { case 'm': show_mixed = true; break; case 'c': num_lines_context = Args::StringToUInt32(option_arg, 0, 0); break; case 'b': show_bytes = true; break; case 's': m_start_addr = Args::StringToUInt64(optarg, LLDB_INVALID_ADDRESS, 0); if (m_start_addr == LLDB_INVALID_ADDRESS) m_start_addr = Args::StringToUInt64(optarg, LLDB_INVALID_ADDRESS, 16); if (m_start_addr == LLDB_INVALID_ADDRESS) error.SetErrorStringWithFormat ("Invalid start address string '%s'.\n", optarg); break; case 'e': m_end_addr = Args::StringToUInt64(optarg, LLDB_INVALID_ADDRESS, 0); if (m_end_addr == LLDB_INVALID_ADDRESS) m_end_addr = Args::StringToUInt64(optarg, LLDB_INVALID_ADDRESS, 16); if (m_end_addr == LLDB_INVALID_ADDRESS) error.SetErrorStringWithFormat ("Invalid end address string '%s'.\n", optarg); break; case 'n': m_func_name = option_arg; break; case 'r': raw = true; break; default: error.SetErrorStringWithFormat("Unrecognized short option '%c'.\n", short_option); break; } return error; } void CommandObjectDisassemble::CommandOptions::ResetOptionValues () { Options::ResetOptionValues(); show_mixed = false; show_bytes = false; num_lines_context = 0; m_func_name.clear(); m_start_addr = LLDB_INVALID_ADDRESS; m_end_addr = LLDB_INVALID_ADDRESS; raw = false; } const lldb::OptionDefinition* CommandObjectDisassemble::CommandOptions::GetDefinitions () { return g_option_table; } lldb::OptionDefinition CommandObjectDisassemble::CommandOptions::g_option_table[] = { { LLDB_OPT_SET_ALL, false, "bytes", 'b', no_argument, NULL, 0, eArgTypeNone, "Show opcode bytes when disassembling."}, { LLDB_OPT_SET_ALL, false, "context", 'c', required_argument, NULL, 0, eArgTypeNumLines, "Number of context lines of source to show."}, { LLDB_OPT_SET_ALL, false, "mixed", 'm', no_argument, NULL, 0, eArgTypeNone, "Enable mixed source and assembly display."}, { LLDB_OPT_SET_ALL, false, "raw", 'r', no_argument, NULL, 0, eArgTypeNone, "Print raw disassembly with no symbol information."}, { LLDB_OPT_SET_1, true, "start-address", 's', required_argument, NULL, 0, eArgTypeAddress, "Address to start disassembling."}, { LLDB_OPT_SET_1, false, "end-address", 'e', required_argument, NULL, 0, eArgTypeAddress, "Address to start disassembling."}, { LLDB_OPT_SET_2, true, "name", 'n', required_argument, NULL, CommandCompletions::eSymbolCompletion, eArgTypeFunctionName, "Disassemble entire contents of the given function name."}, { LLDB_OPT_SET_3, false, "current-frame", 'f', no_argument, NULL, 0, eArgTypeNone, "Disassemble entire contents of the current frame's function."}, { 0, false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL } }; //------------------------------------------------------------------------- // CommandObjectDisassemble //------------------------------------------------------------------------- CommandObjectDisassemble::CommandObjectDisassemble (CommandInterpreter &interpreter) : CommandObject (interpreter, "disassemble", "Disassemble bytes in the current function, or elsewhere in the executable program as specified by the user.", "disassemble [<cmd-options>]") { } CommandObjectDisassemble::~CommandObjectDisassemble() { } bool CommandObjectDisassemble::Execute ( Args& command, CommandReturnObject &result ) { Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get(); if (target == NULL) { result.AppendError ("invalid target, set executable file using 'file' command"); result.SetStatus (eReturnStatusFailed); return false; } ArchSpec arch(target->GetArchitecture()); if (!arch.IsValid()) { result.AppendError ("target needs valid architecure in order to be able to disassemble"); result.SetStatus (eReturnStatusFailed); return false; } Disassembler *disassembler = Disassembler::FindPlugin(arch); if (disassembler == NULL) { result.AppendErrorWithFormat ("Unable to find Disassembler plug-in for %s architecture.\n", arch.AsCString()); result.SetStatus (eReturnStatusFailed); return false; } result.SetStatus (eReturnStatusSuccessFinishResult); if (command.GetArgumentCount() != 0) { result.AppendErrorWithFormat ("\"disassemble\" arguments are specified as options.\n"); GetOptions()->GenerateOptionUsage (m_interpreter, result.GetErrorStream(), this); result.SetStatus (eReturnStatusFailed); return false; } ExecutionContext exe_ctx(m_interpreter.GetDebugger().GetExecutionContext()); if (m_options.show_mixed && m_options.num_lines_context == 0) m_options.num_lines_context = 1; if (!m_options.m_func_name.empty()) { ConstString name(m_options.m_func_name.c_str()); if (Disassembler::Disassemble (m_interpreter.GetDebugger(), arch, exe_ctx, name, NULL, // Module * m_options.show_mixed ? m_options.num_lines_context : 0, m_options.show_bytes, result.GetOutputStream())) { result.SetStatus (eReturnStatusSuccessFinishResult); } else { result.AppendErrorWithFormat ("Unable to find symbol with name '%s'.\n", name.GetCString()); result.SetStatus (eReturnStatusFailed); } } else { AddressRange range; if (m_options.m_start_addr != LLDB_INVALID_ADDRESS) { range.GetBaseAddress().SetOffset (m_options.m_start_addr); if (m_options.m_end_addr != LLDB_INVALID_ADDRESS) { if (m_options.m_end_addr < m_options.m_start_addr) { result.AppendErrorWithFormat ("End address before start address.\n"); result.SetStatus (eReturnStatusFailed); return false; } range.SetByteSize (m_options.m_end_addr - m_options.m_start_addr); } else range.SetByteSize (DEFAULT_DISASM_BYTE_SIZE); } else { if (exe_ctx.frame) { SymbolContext sc(exe_ctx.frame->GetSymbolContext(eSymbolContextFunction | eSymbolContextSymbol)); if (sc.function) range = sc.function->GetAddressRange(); else if (sc.symbol && sc.symbol->GetAddressRangePtr()) range = *sc.symbol->GetAddressRangePtr(); else range.GetBaseAddress() = exe_ctx.frame->GetFrameCodeAddress(); } else { result.AppendError ("invalid frame"); result.SetStatus (eReturnStatusFailed); return false; } } if (range.GetByteSize() == 0) range.SetByteSize(DEFAULT_DISASM_BYTE_SIZE); if (Disassembler::Disassemble (m_interpreter.GetDebugger(), arch, exe_ctx, range, m_options.show_mixed ? m_options.num_lines_context : 0, m_options.show_bytes, result.GetOutputStream())) { result.SetStatus (eReturnStatusSuccessFinishResult); } else { result.AppendErrorWithFormat ("Failed to disassemble memory at 0x%8.8llx.\n", m_options.m_start_addr); result.SetStatus (eReturnStatusFailed); } } return result.Succeeded(); } <|endoftext|>
<commit_before>/* * Distributed under the OSI-approved Apache License, Version 2.0. See * accompanying file Copyright.txt for details. * * InlineWriter.cpp * * Created on: Nov 16, 2018 * Author: Aron Helser aron.helser@kitware.com */ #include "InlineWriter.h" #include "InlineReader.h" #include "InlineWriter.tcc" #include "adios2/helper/adiosFunctions.h" #include <adios2-perfstubs-interface.h> #include <iostream> namespace adios2 { namespace core { namespace engine { InlineWriter::InlineWriter(IO &io, const std::string &name, const Mode mode, helper::Comm comm) : Engine("InlineWriter", io, name, mode, std::move(comm)) { PERFSTUBS_SCOPED_TIMER("InlineWriter::Open"); m_WriterRank = m_Comm.Rank(); Init(); if (m_Verbosity == 5) { std::cout << "Inline Writer " << m_WriterRank << " Open(" << m_Name << ")." << std::endl; } m_IsOpen = true; } InlineWriter::~InlineWriter() { if (m_IsOpen) { DestructorClose(m_FailVerbose); } m_IsOpen = false; } const InlineReader *InlineWriter::GetReader() const { const auto &engine_map = m_IO.GetEngines(); if (engine_map.size() != 2) { helper::Throw<std::runtime_error>( "Engine", "InlineWriter", "GetReader", "There must be exactly one reader and one " "writer for the inline engine."); } std::shared_ptr<Engine> e = engine_map.begin()->second; if (e->OpenMode() == adios2::Mode::Write) { e = engine_map.rbegin()->second; } const auto reader = dynamic_cast<InlineReader *>(e.get()); if (!reader) { helper::Throw<std::runtime_error>( "Engine", "InlineWriter", "GetReader", "dynamic_cast<InlineReader*> failed; this is very likely a bug."); } return reader; } StepStatus InlineWriter::BeginStep(StepMode mode, const float timeoutSeconds) { PERFSTUBS_SCOPED_TIMER("InlineWriter::BeginStep"); if (m_InsideStep) { helper::Throw<std::runtime_error>( "Engine", "InlineWriter", "BeginStep", "InlineWriter::BeginStep was called but the " "writer is already inside a step"); } auto reader = GetReader(); if (reader->IsInsideStep()) { m_InsideStep = false; return StepStatus::NotReady; } m_InsideStep = true; if (m_CurrentStep == static_cast<size_t>(-1)) { m_CurrentStep = 0; // 0 is the first step } else { ++m_CurrentStep; } if (m_Verbosity == 5) { std::cout << "Inline Writer " << m_WriterRank << " BeginStep() new step " << m_CurrentStep << "\n"; } // m_BlocksInfo for all variables should be cleared at this point, // whether they were read in the last step or not. ResetVariables(); return StepStatus::OK; } void InlineWriter::ResetVariables() { auto availVars = m_IO.GetAvailableVariables(); for (auto &varPair : availVars) { const auto &name = varPair.first; const DataType type = m_IO.InquireVariableType(name); if (type == DataType::Struct) { } #define declare_type(T) \ else if (type == helper::GetDataType<T>()) \ { \ Variable<T> &variable = FindVariable<T>(name, "in call to BeginStep"); \ variable.m_BlocksInfo.clear(); \ } ADIOS2_FOREACH_STDTYPE_1ARG(declare_type) #undef declare_type } m_ResetVariables = false; } size_t InlineWriter::CurrentStep() const { return m_CurrentStep; } void InlineWriter::PerformPuts() { PERFSTUBS_SCOPED_TIMER("InlineWriter::PerformPuts"); if (m_Verbosity == 5) { std::cout << "Inline Writer " << m_WriterRank << " PerformPuts()\n"; } m_ResetVariables = true; } void InlineWriter::EndStep() { PERFSTUBS_SCOPED_TIMER("InlineWriter::EndStep"); if (!m_InsideStep) { helper::Throw<std::runtime_error>( "Engine", "InlineWriter", "EndStep", "InlineWriter::EndStep() cannot be called " "without a call to BeginStep() first"); } if (m_Verbosity == 5) { std::cout << "Inline Writer " << m_WriterRank << " EndStep() Step " << m_CurrentStep << std::endl; } m_InsideStep = false; } void InlineWriter::Flush(const int) { PERFSTUBS_SCOPED_TIMER("InlineWriter::Flush"); if (m_Verbosity == 5) { std::cout << "Inline Writer " << m_WriterRank << " Flush()\n"; } } bool InlineWriter::IsInsideStep() const { return m_InsideStep; } // PRIVATE #define declare_type(T) \ void InlineWriter::DoPutSync(Variable<T> &variable, const T *data) \ { \ PERFSTUBS_SCOPED_TIMER("InlineWriter::DoPutSync"); \ PutSyncCommon(variable, data); \ } \ void InlineWriter::DoPutDeferred(Variable<T> &variable, const T *data) \ { \ PERFSTUBS_SCOPED_TIMER("InlineWriter::DoPutDeferred"); \ PutDeferredCommon(variable, data); \ } ADIOS2_FOREACH_STDTYPE_1ARG(declare_type) #undef declare_type void InlineWriter::Init() { InitParameters(); InitTransports(); } void InlineWriter::InitParameters() { for (const auto &pair : m_IO.m_Parameters) { std::string key(pair.first); std::transform(key.begin(), key.end(), key.begin(), ::tolower); std::string value(pair.second); if (key == "verbose") { m_Verbosity = std::stoi(value); if (m_Verbosity < 0 || m_Verbosity > 5) helper::Throw<std::invalid_argument>( "Engine", "InlineWriter", "InitParameters", "Method verbose argument must be an " "integer in the range [0,5], in call to " "Open or Engine constructor"); } } } void InlineWriter::InitTransports() { // Nothing to process from m_IO.m_TransportsParameters } void InlineWriter::DoClose(const int transportIndex) { PERFSTUBS_SCOPED_TIMER("InlineWriter::DoClose"); if (m_Verbosity == 5) { std::cout << "Inline Writer " << m_WriterRank << " Close(" << m_Name << ")\n"; } // end of stream m_CurrentStep = static_cast<size_t>(-1); } } // end namespace engine } // end namespace core } // end namespace adios2 <commit_msg>allow an inline writer to be created and used without an inline reader<commit_after>/* * Distributed under the OSI-approved Apache License, Version 2.0. See * accompanying file Copyright.txt for details. * * InlineWriter.cpp * * Created on: Nov 16, 2018 * Author: Aron Helser aron.helser@kitware.com */ #include "InlineWriter.h" #include "InlineReader.h" #include "InlineWriter.tcc" #include "adios2/helper/adiosFunctions.h" #include <adios2-perfstubs-interface.h> #include <iostream> namespace adios2 { namespace core { namespace engine { InlineWriter::InlineWriter(IO &io, const std::string &name, const Mode mode, helper::Comm comm) : Engine("InlineWriter", io, name, mode, std::move(comm)) { PERFSTUBS_SCOPED_TIMER("InlineWriter::Open"); m_WriterRank = m_Comm.Rank(); Init(); if (m_Verbosity == 5) { std::cout << "Inline Writer " << m_WriterRank << " Open(" << m_Name << ")." << std::endl; } m_IsOpen = true; } InlineWriter::~InlineWriter() { if (m_IsOpen) { DestructorClose(m_FailVerbose); } m_IsOpen = false; } const InlineReader *InlineWriter::GetReader() const { const auto &engine_map = m_IO.GetEngines(); if (engine_map.size() == 1) { // it should be fine for a writer to be created and start running, // without the reader having been created. This is necessary to run // correctly with ParaView Catalyst Live. return nullptr; } else if (engine_map.size() > 2) { helper::Throw<std::runtime_error>( "Engine", "InlineWriter", "GetReader", "There must be only one inline writer and at most " "one inline reader."); } std::shared_ptr<Engine> e = engine_map.begin()->second; if (e->OpenMode() == adios2::Mode::Write) { e = engine_map.rbegin()->second; } const auto reader = dynamic_cast<InlineReader *>(e.get()); if (!reader) { helper::Throw<std::runtime_error>( "Engine", "InlineWriter", "GetReader", "dynamic_cast<InlineReader*> failed; this is very likely a bug."); } return reader; } StepStatus InlineWriter::BeginStep(StepMode mode, const float timeoutSeconds) { PERFSTUBS_SCOPED_TIMER("InlineWriter::BeginStep"); if (m_InsideStep) { helper::Throw<std::runtime_error>( "Engine", "InlineWriter", "BeginStep", "InlineWriter::BeginStep was called but the " "writer is already inside a step"); } auto reader = GetReader(); if (reader && reader->IsInsideStep()) { m_InsideStep = false; return StepStatus::NotReady; } m_InsideStep = true; if (m_CurrentStep == static_cast<size_t>(-1)) { m_CurrentStep = 0; // 0 is the first step } else { ++m_CurrentStep; } if (m_Verbosity == 5) { std::cout << "Inline Writer " << m_WriterRank << " BeginStep() new step " << m_CurrentStep << "\n"; } // m_BlocksInfo for all variables should be cleared at this point, // whether they were read in the last step or not. ResetVariables(); return StepStatus::OK; } void InlineWriter::ResetVariables() { auto availVars = m_IO.GetAvailableVariables(); for (auto &varPair : availVars) { const auto &name = varPair.first; const DataType type = m_IO.InquireVariableType(name); if (type == DataType::Struct) { } #define declare_type(T) \ else if (type == helper::GetDataType<T>()) \ { \ Variable<T> &variable = FindVariable<T>(name, "in call to BeginStep"); \ variable.m_BlocksInfo.clear(); \ } ADIOS2_FOREACH_STDTYPE_1ARG(declare_type) #undef declare_type } m_ResetVariables = false; } size_t InlineWriter::CurrentStep() const { return m_CurrentStep; } void InlineWriter::PerformPuts() { PERFSTUBS_SCOPED_TIMER("InlineWriter::PerformPuts"); if (m_Verbosity == 5) { std::cout << "Inline Writer " << m_WriterRank << " PerformPuts()\n"; } m_ResetVariables = true; } void InlineWriter::EndStep() { PERFSTUBS_SCOPED_TIMER("InlineWriter::EndStep"); if (!m_InsideStep) { helper::Throw<std::runtime_error>( "Engine", "InlineWriter", "EndStep", "InlineWriter::EndStep() cannot be called " "without a call to BeginStep() first"); } if (m_Verbosity == 5) { std::cout << "Inline Writer " << m_WriterRank << " EndStep() Step " << m_CurrentStep << std::endl; } m_InsideStep = false; } void InlineWriter::Flush(const int) { PERFSTUBS_SCOPED_TIMER("InlineWriter::Flush"); if (m_Verbosity == 5) { std::cout << "Inline Writer " << m_WriterRank << " Flush()\n"; } } bool InlineWriter::IsInsideStep() const { return m_InsideStep; } // PRIVATE #define declare_type(T) \ void InlineWriter::DoPutSync(Variable<T> &variable, const T *data) \ { \ PERFSTUBS_SCOPED_TIMER("InlineWriter::DoPutSync"); \ PutSyncCommon(variable, data); \ } \ void InlineWriter::DoPutDeferred(Variable<T> &variable, const T *data) \ { \ PERFSTUBS_SCOPED_TIMER("InlineWriter::DoPutDeferred"); \ PutDeferredCommon(variable, data); \ } ADIOS2_FOREACH_STDTYPE_1ARG(declare_type) #undef declare_type void InlineWriter::Init() { InitParameters(); InitTransports(); } void InlineWriter::InitParameters() { for (const auto &pair : m_IO.m_Parameters) { std::string key(pair.first); std::transform(key.begin(), key.end(), key.begin(), ::tolower); std::string value(pair.second); if (key == "verbose") { m_Verbosity = std::stoi(value); if (m_Verbosity < 0 || m_Verbosity > 5) helper::Throw<std::invalid_argument>( "Engine", "InlineWriter", "InitParameters", "Method verbose argument must be an " "integer in the range [0,5], in call to " "Open or Engine constructor"); } } } void InlineWriter::InitTransports() { // Nothing to process from m_IO.m_TransportsParameters } void InlineWriter::DoClose(const int transportIndex) { PERFSTUBS_SCOPED_TIMER("InlineWriter::DoClose"); if (m_Verbosity == 5) { std::cout << "Inline Writer " << m_WriterRank << " Close(" << m_Name << ")\n"; } // end of stream m_CurrentStep = static_cast<size_t>(-1); } } // end namespace engine } // end namespace core } // end namespace adios2 <|endoftext|>
<commit_before>#include "MessageTransport.h" void MessageTransport::Init(uint64_t nodeID_, Endpoint& endpoint_) { nodeID = nodeID_; endpoint = endpoint_; server.Init(endpoint.GetPort()); server.SetTransport(this); } uint64_t MessageTransport::GetNodeID() { return nodeID; } Endpoint& MessageTransport::GetEndpoint() { return endpoint; } void MessageTransport::AddEndpoint(uint64_t nodeID, Endpoint endpoint) { MessageConnection* conn; if (nodeID < this->nodeID) return; conn = GetConnection(nodeID); if (conn != NULL) return; if (nodeID == this->nodeID) Log_Trace("connecting to self"); conn = new MessageConnection; conn->SetTransport(this); conn->SetNodeID(nodeID); conn->SetEndpoint(endpoint); conn->Connect(); } void MessageTransport::SendMessage(uint64_t nodeID, Buffer& prefix, Message& msg) { MessageConnection* conn; conn = GetConnection(nodeID); if (!conn) { Log_Trace("no connection to nodeID %" PRIu64, nodeID); return; } if (conn->GetProgress() != MessageConnection::READY) { Log_Trace("connection to %" PRIu64 " has progress: %d", nodeID, conn->GetProgress()); return; } msg.Write(msgBuffer); conn->Write(prefix, msgBuffer); } void MessageTransport::SendPriorityMessage(uint64_t nodeID, Buffer& prefix, Message& msg) { MessageConnection* conn; conn = GetConnection(nodeID); if (!conn) { Log_Trace("no connection to nodeID %" PRIu64, nodeID); return; } if (conn->GetProgress() != MessageConnection::READY) { Log_Trace("connection to %" PRIu64 " has progress: %d", nodeID, conn->GetProgress()); return; } msg.Write(msgBuffer); conn->WritePriority(prefix, msgBuffer); } void MessageTransport::AddConnection(MessageConnection* conn) { conns.Append(conn); } MessageConnection* MessageTransport::GetConnection(uint64_t nodeID) { MessageConnection* it; for (it = conns.Head(); it != NULL; it = conns.Next(it)) { if (it->GetNodeID() == nodeID) return it; } return NULL; } void MessageTransport::DeleteConnection(MessageConnection* conn) { conn->Close(); if (conn->next != conn) conns.Remove(conn); delete conn; // TODO: what happens when control returns to OnRead() } <commit_msg>Fixed last TODO in Messaging.<commit_after>#include "MessageTransport.h" void MessageTransport::Init(uint64_t nodeID_, Endpoint& endpoint_) { nodeID = nodeID_; endpoint = endpoint_; server.Init(endpoint.GetPort()); server.SetTransport(this); } uint64_t MessageTransport::GetNodeID() { return nodeID; } Endpoint& MessageTransport::GetEndpoint() { return endpoint; } void MessageTransport::AddEndpoint(uint64_t nodeID, Endpoint endpoint) { MessageConnection* conn; if (nodeID < this->nodeID) return; conn = GetConnection(nodeID); if (conn != NULL) return; if (nodeID == this->nodeID) Log_Trace("connecting to self"); conn = new MessageConnection; conn->SetTransport(this); conn->SetNodeID(nodeID); conn->SetEndpoint(endpoint); conn->Connect(); } void MessageTransport::SendMessage(uint64_t nodeID, Buffer& prefix, Message& msg) { MessageConnection* conn; conn = GetConnection(nodeID); if (!conn) { Log_Trace("no connection to nodeID %" PRIu64, nodeID); return; } if (conn->GetProgress() != MessageConnection::READY) { Log_Trace("connection to %" PRIu64 " has progress: %d", nodeID, conn->GetProgress()); return; } msg.Write(msgBuffer); conn->Write(prefix, msgBuffer); } void MessageTransport::SendPriorityMessage(uint64_t nodeID, Buffer& prefix, Message& msg) { MessageConnection* conn; conn = GetConnection(nodeID); if (!conn) { Log_Trace("no connection to nodeID %" PRIu64, nodeID); return; } if (conn->GetProgress() != MessageConnection::READY) { Log_Trace("connection to %" PRIu64 " has progress: %d", nodeID, conn->GetProgress()); return; } msg.Write(msgBuffer); conn->WritePriority(prefix, msgBuffer); } void MessageTransport::AddConnection(MessageConnection* conn) { conns.Append(conn); } MessageConnection* MessageTransport::GetConnection(uint64_t nodeID) { MessageConnection* it; for (it = conns.Head(); it != NULL; it = conns.Next(it)) { if (it->GetNodeID() == nodeID) return it; } return NULL; } void MessageTransport::DeleteConnection(MessageConnection* conn) { conn->Close(); if (conn->next != conn) conns.Remove(conn); delete conn; } <|endoftext|>
<commit_before>/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2012 Scientific Computing and Imaging Institute, University of Utah. License for the specific language governing rights and limitations under 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 <QtGui> #include <iostream> #include <Interface/Application/ModuleLogWindow.h> using namespace SCIRun::Gui; using namespace SCIRun::Dataflow::Networks; namespace { int moveIncrement = 40; } ModuleLogWindow::ModuleLogWindow(const QString& moduleName, QWidget* parent) : QDialog(parent), moduleName_(moduleName) { setupUi(this); setModal(false); setWindowTitle("Log for " + moduleName); setVisible(false); connect(buttonBox->button(QDialogButtonBox::Discard), SIGNAL(clicked()), logTextEdit_, SLOT(clear())); } void ModuleLogWindow::appendMessage(const QString& message, const QColor& color /* = Qt::black */) { logTextEdit_->insertHtml(QString("<p style=\"color:") + color.name() + "\">" + message + "</p><br>"); } void ModuleLogWindow::popupMessageBox(const QString& message) { QMessageBox::critical(this->parentWidget(), windowTitle(), "Error in " + moduleName_ + "\n" + message, QMessageBox::Ok); } ModuleLogger::ModuleLogger(ModuleLogWindow* window) { connect(this, SIGNAL(logSignal(const QString&, const QColor&)), window, SLOT(appendMessage(const QString&, const QColor&))); connect(this, SIGNAL(alert(const QColor&)), window, SIGNAL(messageReceived(const QColor&))); connect(this, SIGNAL(popup(const QString&)), window, SLOT(popupMessageBox(const QString&))); } void ModuleLogger::error(const std::string& msg) const { const QColor red = Qt::red; auto qmsg = QString::fromStdString(msg); logSignal("<b>ERROR: " + qmsg + "</b>", red); alert(red); popup(qmsg); } void ModuleLogger::warning(const std::string& msg) const { const QColor yellow = Qt::yellow; logSignal("WARNING: " + QString::fromStdString(msg), yellow); alert(yellow); } void ModuleLogger::remark(const std::string& msg) const { const QColor blue = Qt::blue; logSignal("REMARK: " + QString::fromStdString(msg), blue); alert(blue); } void ModuleLogger::status(const std::string& msg) const { logSignal(QString::fromStdString(msg), Qt::black); }<commit_msg>Near future code.<commit_after>/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2012 Scientific Computing and Imaging Institute, University of Utah. License for the specific language governing rights and limitations under 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 <QtGui> #include <iostream> #include <Interface/Application/ModuleLogWindow.h> using namespace SCIRun::Gui; using namespace SCIRun::Dataflow::Networks; namespace { int moveIncrement = 40; } ModuleLogWindow::ModuleLogWindow(const QString& moduleName, QWidget* parent) : QDialog(parent), moduleName_(moduleName) { setupUi(this); setModal(false); setWindowTitle("Log for " + moduleName); setVisible(false); connect(buttonBox->button(QDialogButtonBox::Discard), SIGNAL(clicked()), logTextEdit_, SLOT(clear())); } void ModuleLogWindow::appendMessage(const QString& message, const QColor& color /* = Qt::black */) { logTextEdit_->insertHtml(QString("<p style=\"color:") + color.name() + "\">" + message + "</p><br>"); } void ModuleLogWindow::popupMessageBox(const QString& message) { QMessageBox::critical(this->parentWidget(), windowTitle(), "Error in " + moduleName_ + "\n" + message, QMessageBox::Ok); } ModuleLogger::ModuleLogger(ModuleLogWindow* window) { connect(this, SIGNAL(logSignal(const QString&, const QColor&)), window, SLOT(appendMessage(const QString&, const QColor&))); connect(this, SIGNAL(alert(const QColor&)), window, SIGNAL(messageReceived(const QColor&))); //TODO //if (!SCIRunOptions::isTrue(ProgramOption::DisableModuleErrorPopups)) connect(this, SIGNAL(popup(const QString&)), window, SLOT(popupMessageBox(const QString&))); } void ModuleLogger::error(const std::string& msg) const { const QColor red = Qt::red; auto qmsg = QString::fromStdString(msg); logSignal("<b>ERROR: " + qmsg + "</b>", red); alert(red); popup(qmsg); } void ModuleLogger::warning(const std::string& msg) const { const QColor yellow = Qt::yellow; logSignal("WARNING: " + QString::fromStdString(msg), yellow); alert(yellow); } void ModuleLogger::remark(const std::string& msg) const { const QColor blue = Qt::blue; logSignal("REMARK: " + QString::fromStdString(msg), blue); alert(blue); } void ModuleLogger::status(const std::string& msg) const { logSignal(QString::fromStdString(msg), Qt::black); }<|endoftext|>
<commit_before>/* * Copyright (C) 2019 pengjian.uestc @ gmail.com */ /* * This file is part of Scylla. * * Scylla 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. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include "bytes.hh" #include "seastar/core/sharded.hh" #include "seastar/core/shared_ptr.hh" #include <seastar/core/print.hh> #include "seastar/core/scattered_message.hh" #include "redis/exceptions.hh" using namespace seastar; namespace redis { class redis_message final { seastar::lw_shared_ptr<scattered_message<char>> _message; public: redis_message() = delete; redis_message(const redis_message&) = delete; redis_message& operator=(const redis_message&) = delete; redis_message(redis_message&& o) noexcept : _message(std::move(o._message)) {} redis_message(lw_shared_ptr<scattered_message<char>> m) noexcept : _message(m) {} static future<redis_message> ok() { auto m = make_lw_shared<scattered_message<char>> (); m->append_static("+OK\r\n"); return make_ready_future<redis_message>(m); } static future<redis_message> pong() { auto m = make_lw_shared<scattered_message<char>> (); m->append_static("+PONG\r\n"); return make_ready_future<redis_message>(m); } static future<redis_message> zero() { auto m = make_lw_shared<scattered_message<char>> (); m->append_static(":0\r\n"); return make_ready_future<redis_message>(m); } static future<redis_message> one() { auto m = make_lw_shared<scattered_message<char>> (); m->append_static(":1\r\n"); return make_ready_future<redis_message>(m); } static future<redis_message> nil() { auto m = make_lw_shared<scattered_message<char>> (); m->append_static("$-1\r\n"); return make_ready_future<redis_message>(m); } static future<redis_message> err() { return zero(); } static future<redis_message> number(size_t n) { auto m = make_lw_shared<scattered_message<char>> (); m->append(sprint(":%zu\r\n", n)); return make_ready_future<redis_message>(m); } static future<redis_message> make_list_result(std::map<bytes, bytes>& list_result) { auto m = make_lw_shared<scattered_message<char>> (); m->append(sprint("*%u\r\n", list_result.size() * 2)); for (auto r : list_result) { write_bytes(m, (bytes&)r.first); write_bytes(m, r.second); } return make_ready_future<redis_message>(m); } static future<redis_message> make_strings_result(bytes result) { auto m = make_lw_shared<scattered_message<char>> (); write_bytes(m, result); return make_ready_future<redis_message>(m); } static future<redis_message> unknown(const bytes& name) { return from_exception(make_message("-ERR unknown command '%s'\r\n", to_sstring(name))); } static future<redis_message> exception(const sstring& em) { auto m = make_lw_shared<scattered_message<char>> (); m->append(make_message("-ERR %s\r\n", em)); return make_ready_future<redis_message>(m); } static future<redis_message> exception(const redis_exception& e) { return exception(e.what_message()); } inline lw_shared_ptr<scattered_message<char>> message() { return _message; } private: static future<redis_message> from_exception(sstring data) { auto m = make_lw_shared<scattered_message<char>> (); m->append(data); return make_ready_future<redis_message>(m); } template<typename... Args> static inline sstring make_message(const char* fmt, Args&&... args) noexcept { try { return sprint(fmt, std::forward<Args>(args)...); } catch (...) { return sstring(); } } static sstring to_sstring(const bytes& b) { return sstring(reinterpret_cast<const char*>(b.data()), b.size()); } static void write_bytes(lw_shared_ptr<scattered_message<char>> m, bytes& b) { m->append(sprint("$%d\r\n", b.size())); m->append(std::string_view(reinterpret_cast<const char*>(b.data()), b.size())); m->append_static("\r\n"); } }; } <commit_msg>redis: Remove seastar namespace import from reply.hh<commit_after>/* * Copyright (C) 2019 pengjian.uestc @ gmail.com */ /* * This file is part of Scylla. * * Scylla 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. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include "bytes.hh" #include "seastar/core/sharded.hh" #include "seastar/core/shared_ptr.hh" #include <seastar/core/print.hh> #include "seastar/core/scattered_message.hh" #include "redis/exceptions.hh" namespace redis { class redis_message final { seastar::lw_shared_ptr<scattered_message<char>> _message; public: redis_message() = delete; redis_message(const redis_message&) = delete; redis_message& operator=(const redis_message&) = delete; redis_message(redis_message&& o) noexcept : _message(std::move(o._message)) {} redis_message(lw_shared_ptr<scattered_message<char>> m) noexcept : _message(m) {} static seastar::future<redis_message> ok() { auto m = make_lw_shared<scattered_message<char>> (); m->append_static("+OK\r\n"); return make_ready_future<redis_message>(m); } static seastar::future<redis_message> pong() { auto m = make_lw_shared<scattered_message<char>> (); m->append_static("+PONG\r\n"); return make_ready_future<redis_message>(m); } static seastar::future<redis_message> zero() { auto m = make_lw_shared<scattered_message<char>> (); m->append_static(":0\r\n"); return make_ready_future<redis_message>(m); } static seastar::future<redis_message> one() { auto m = make_lw_shared<scattered_message<char>> (); m->append_static(":1\r\n"); return make_ready_future<redis_message>(m); } static seastar::future<redis_message> nil() { auto m = make_lw_shared<scattered_message<char>> (); m->append_static("$-1\r\n"); return make_ready_future<redis_message>(m); } static seastar::future<redis_message> err() { return zero(); } static seastar::future<redis_message> number(size_t n) { auto m = make_lw_shared<scattered_message<char>> (); m->append(sprint(":%zu\r\n", n)); return make_ready_future<redis_message>(m); } static seastar::future<redis_message> make_list_result(std::map<bytes, bytes>& list_result) { auto m = make_lw_shared<scattered_message<char>> (); m->append(sprint("*%u\r\n", list_result.size() * 2)); for (auto r : list_result) { write_bytes(m, (bytes&)r.first); write_bytes(m, r.second); } return make_ready_future<redis_message>(m); } static seastar::future<redis_message> make_strings_result(bytes result) { auto m = make_lw_shared<scattered_message<char>> (); write_bytes(m, result); return make_ready_future<redis_message>(m); } static seastar::future<redis_message> unknown(const bytes& name) { return from_exception(make_message("-ERR unknown command '%s'\r\n", to_sstring(name))); } static seastar::future<redis_message> exception(const sstring& em) { auto m = make_lw_shared<scattered_message<char>> (); m->append(make_message("-ERR %s\r\n", em)); return make_ready_future<redis_message>(m); } static seastar::future<redis_message> exception(const redis_exception& e) { return exception(e.what_message()); } inline lw_shared_ptr<scattered_message<char>> message() { return _message; } private: static seastar::future<redis_message> from_exception(sstring data) { auto m = make_lw_shared<scattered_message<char>> (); m->append(data); return make_ready_future<redis_message>(m); } template<typename... Args> static inline sstring make_message(const char* fmt, Args&&... args) noexcept { try { return sprint(fmt, std::forward<Args>(args)...); } catch (...) { return sstring(); } } static sstring to_sstring(const bytes& b) { return sstring(reinterpret_cast<const char*>(b.data()), b.size()); } static void write_bytes(lw_shared_ptr<scattered_message<char>> m, bytes& b) { m->append(sprint("$%d\r\n", b.size())); m->append(std::string_view(reinterpret_cast<const char*>(b.data()), b.size())); m->append_static("\r\n"); } }; } <|endoftext|>