text
stringlengths
54
60.6k
<commit_before>/** * Performs dispatch for RC switch messages. * * (C) 2015 Andrew Barry <abarry@csail.mit.edu> */ #ifndef RC_SWITCH_DISPATH_HPP #define RC_SWITCH_DISPATH_HPP #include <iostream> #include <lcm/lcm-cpp.hpp> #include "../../LCM/lcmt/tvlqr_controller_action.hpp" #include "../../LCM/lcmt/rc_switch_action.hpp" #include "../../LCM/lcmt/stereo.hpp" #include "../../LCM/lcmt/timestamp.hpp" #include "../../LCM/lcmt/stereo_control.hpp" #include "../../utils/utils/RealtimeUtils.hpp" #include <bot_param/param_client.h> #include <vector> #define MAX_PARAM_SIZE 100 class RcSwitchDispatch { public: RcSwitchDispatch(lcm::LCM *lcm, std::string rc_trajectory_commands_channel, std::string stereo_channel, std::string state_machine_go_autonomous_channel, std::string stereo_control_channel, std::string arm_for_takeoff_channel); void ProcessRcMsg(const lcm::ReceiveBuffer *rbus, const std::string &chan, const lcmt::rc_switch_action *msg); private: void SendTrajectoryRequest(int traj_num) const; void SendStereoMsg(int stereo_msg_num) const; void SendGoAutonomousMsg() const; void SendArmForTakeoffMsg() const; void SendStereoWriteToDiskMsg() const; void DrakeToCameraFrame(double point_in[], double point_out[]) const; void SendStereoManyPoints(std::vector<float> x_in, std::vector<float> y_in, std::vector<float> z_in) const; int ServoMicroSecondsToSwitchPosition(int servo_value) const; std::string stereo_channel_, rc_trajectory_commands_channel_, state_machine_go_autonomous_channel_, stereo_control_channel_, arm_for_takeoff_channel_; int stable_traj_num_; int num_trajs_, num_stereo_actions_; int num_switch_positions_; int stop_stereo_pos_; int arm_for_takeoff_pos_; int switch_rc_us_[MAX_PARAM_SIZE]; int trajectory_mapping_[MAX_PARAM_SIZE]; int stereo_mapping_[MAX_PARAM_SIZE]; lcm::LCM *lcm_; BotParam *param_; BotFrames *bot_frames_; bool stabilization_mode_; // pole to the left std::vector<float> x_points0_ = {10, 10, 10, 10, 10}; std::vector<float> y_points0_ = {2, 2, 2, 2, 2}; std::vector<float> z_points0_ = {4, 2, 0, -2, -4}; // pole to the right std::vector<float> x_points1_ = {10, 10, 10, 10, 10}; std::vector<float> y_points1_ = {-2, -2, -2, -2, -2}; std::vector<float> z_points1_ = {4, 2, 0, -2, -4}; // pole below std::vector<float> x_points2_ = {10, 10, 10, 10, 10}; std::vector<float> y_points2_ = {-4, -2, 0, 2, 4}; std::vector<float> z_points2_ = {-3, -3, -3, -3, -3}; }; #endif <commit_msg>Change fake stereo data that runs from the switch to have 3 points at each location so they will not be filtered out.<commit_after>/** * Performs dispatch for RC switch messages. * * (C) 2015 Andrew Barry <abarry@csail.mit.edu> */ #ifndef RC_SWITCH_DISPATH_HPP #define RC_SWITCH_DISPATH_HPP #include <iostream> #include <lcm/lcm-cpp.hpp> #include "../../LCM/lcmt/tvlqr_controller_action.hpp" #include "../../LCM/lcmt/rc_switch_action.hpp" #include "../../LCM/lcmt/stereo.hpp" #include "../../LCM/lcmt/timestamp.hpp" #include "../../LCM/lcmt/stereo_control.hpp" #include "../../utils/utils/RealtimeUtils.hpp" #include <bot_param/param_client.h> #include <vector> #define MAX_PARAM_SIZE 100 class RcSwitchDispatch { public: RcSwitchDispatch(lcm::LCM *lcm, std::string rc_trajectory_commands_channel, std::string stereo_channel, std::string state_machine_go_autonomous_channel, std::string stereo_control_channel, std::string arm_for_takeoff_channel); void ProcessRcMsg(const lcm::ReceiveBuffer *rbus, const std::string &chan, const lcmt::rc_switch_action *msg); private: void SendTrajectoryRequest(int traj_num) const; void SendStereoMsg(int stereo_msg_num) const; void SendGoAutonomousMsg() const; void SendArmForTakeoffMsg() const; void SendStereoWriteToDiskMsg() const; void DrakeToCameraFrame(double point_in[], double point_out[]) const; void SendStereoManyPoints(std::vector<float> x_in, std::vector<float> y_in, std::vector<float> z_in) const; int ServoMicroSecondsToSwitchPosition(int servo_value) const; std::string stereo_channel_, rc_trajectory_commands_channel_, state_machine_go_autonomous_channel_, stereo_control_channel_, arm_for_takeoff_channel_; int stable_traj_num_; int num_trajs_, num_stereo_actions_; int num_switch_positions_; int stop_stereo_pos_; int arm_for_takeoff_pos_; int switch_rc_us_[MAX_PARAM_SIZE]; int trajectory_mapping_[MAX_PARAM_SIZE]; int stereo_mapping_[MAX_PARAM_SIZE]; lcm::LCM *lcm_; BotParam *param_; BotFrames *bot_frames_; bool stabilization_mode_; // pole to the left std::vector<float> x_points0_ = {10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}; std::vector<float> y_points0_ = { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2}; std::vector<float> z_points0_ = { 4, 4, 4, 2, 2, 2, 0 , 0, 0, -2, -2, -2, -4, -4, -4}; // pole to the right std::vector<float> x_points1_ = {10, 10, 10, 10, 10}; std::vector<float> y_points1_ = {-2, -2, -2, -2, -2}; std::vector<float> z_points1_ = {4, 2, 0, -2, -4}; // pole below std::vector<float> x_points2_ = {10, 10, 10, 10, 10}; std::vector<float> y_points2_ = {-4, -2, 0, 2, 4}; std::vector<float> z_points2_ = {-3, -3, -3, -3, -3}; }; #endif <|endoftext|>
<commit_before> // // This source file is part of appleseed. // Visit https://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2015-2018 Francois Beaune, The appleseedhq Organization // // 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. // // appleseed-max headers. #include "appleseedblendmtl/appleseedblendmtl.h" #include "appleseedenvmap/appleseedenvmap.h" #include "appleseeddisneymtl/appleseeddisneymtl.h" #include "appleseedglassmtl/appleseedglassmtl.h" #include "appleseedlightmtl/appleseedlightmtl.h" #include "appleseedmetalmtl/appleseedmetalmtl.h" #include "appleseedobjpropsmod/appleseedobjpropsmod.h" #include "appleseedoslplugin/oslshaderregistry.h" #include "appleseedplasticmtl/appleseedplasticmtl.h" #include "appleseedrenderelement/appleseedrenderelement.h" #include "appleseedrenderer/appleseedrenderer.h" #include "appleseedsssmtl/appleseedsssmtl.h" #include "appleseedvolumemtl/appleseedvolumemtl.h" #include "logtarget.h" #include "main.h" #include "osloutputselectormap/osloutputselector.h" #include "utilities.h" #include "version.h" // appleseed.renderer headers. #include "renderer/api/log.h" // appleseed.foundation headers. #include "foundation/core/appleseed.h" #include "foundation/platform/windows.h" // include before 3ds Max headers // appleseed.main headers. #include "main/allocator.h" // 3ds Max headers. #include <iparamb2.h> #include <plugapi.h> // Windows headers. #include <tchar.h> // Standard headers. #include <sstream> #include <string> namespace asf = foundation; namespace asr = renderer; namespace { LogTarget g_log_target; OSLShaderRegistry g_shader_registry; } extern "C" { __declspec(dllexport) const wchar_t* LibDescription() { return L"appleseed Renderer"; } __declspec(dllexport) int LibNumberClasses() { return 13 + g_shader_registry.get_size(); } __declspec(dllexport) ClassDesc2* LibClassDesc(int i) { switch (i) { case 0: return &g_appleseed_renderer_classdesc; case 1: return &g_appleseed_disneymtl_classdesc; case 2: return &g_appleseed_sssmtl_classdesc; case 3: return &g_appleseed_glassmtl_classdesc; case 4: return &g_appleseed_lightmtl_classdesc; case 5: return &g_appleseed_objpropsmod_classdesc; case 6: return &g_appleseed_envmap_classdesc; case 7: return &g_appleseed_blendmtl_classdesc; case 8: return &g_appleseed_metalmtl_classdesc; case 9: return &g_appleseed_plasticmtl_classdesc; case 10: return &g_appleseed_outputselector_classdesc; case 11: return &g_appleseed_renderelement_classdesc; case 12: return &g_appleseed_volumemtl_classdesc; // Make sure to update LibNumberClasses() if you add classes here. default: return g_shader_registry.get_class_descriptor(i - 11); } } __declspec(dllexport) ULONG LibVersion() { return VERSION_3DSMAX; } __declspec(dllexport) int LibInitialize() { start_memory_tracking(); asr::global_logger().add_target(&g_log_target); std::wstringstream sstr; sstr << "appleseed-max "; sstr << PluginVersionString; sstr << " plug-in using "; sstr << utf8_to_wide(asf::Appleseed::get_synthetic_version_string()); sstr << " loaded"; const auto title = sstr.str(); const std::wstring sep(title.size(), L'='); // We use GetCOREInterface()->Log()->LogEntry() directly rather than RENDERER_LOG_INFO() // because it seems that we are not running on the main thread (hence log messages are // enqueued to later be emitted from the main thread rather than being emitted directly) // but the Win32 message that should trigger message emission seems to get lost. GetCOREInterface()->Log()->LogEntry( SYSLOG_INFO, FALSE, L"appleseed", L"[appleseed] %s", sep.c_str()); GetCOREInterface()->Log()->LogEntry( SYSLOG_INFO, FALSE, L"appleseed", L"[appleseed] %s", title.c_str()); GetCOREInterface()->Log()->LogEntry( SYSLOG_INFO, FALSE, L"appleseed", L"[appleseed] %s", sep.c_str()); g_shader_registry.create_class_descriptors(); return TRUE; } } <commit_msg>Fix missing asAnisotropyVectorField and asAttributes shaders<commit_after> // // This source file is part of appleseed. // Visit https://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2015-2018 Francois Beaune, The appleseedhq Organization // // 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. // // appleseed-max headers. #include "appleseedblendmtl/appleseedblendmtl.h" #include "appleseedenvmap/appleseedenvmap.h" #include "appleseeddisneymtl/appleseeddisneymtl.h" #include "appleseedglassmtl/appleseedglassmtl.h" #include "appleseedlightmtl/appleseedlightmtl.h" #include "appleseedmetalmtl/appleseedmetalmtl.h" #include "appleseedobjpropsmod/appleseedobjpropsmod.h" #include "appleseedoslplugin/oslshaderregistry.h" #include "appleseedplasticmtl/appleseedplasticmtl.h" #include "appleseedrenderelement/appleseedrenderelement.h" #include "appleseedrenderer/appleseedrenderer.h" #include "appleseedsssmtl/appleseedsssmtl.h" #include "appleseedvolumemtl/appleseedvolumemtl.h" #include "logtarget.h" #include "main.h" #include "osloutputselectormap/osloutputselector.h" #include "utilities.h" #include "version.h" // appleseed.renderer headers. #include "renderer/api/log.h" // appleseed.foundation headers. #include "foundation/core/appleseed.h" #include "foundation/platform/windows.h" // include before 3ds Max headers // appleseed.main headers. #include "main/allocator.h" // 3ds Max headers. #include <iparamb2.h> #include <plugapi.h> // Windows headers. #include <tchar.h> // Standard headers. #include <sstream> #include <string> namespace asf = foundation; namespace asr = renderer; namespace { LogTarget g_log_target; OSLShaderRegistry g_shader_registry; } extern "C" { __declspec(dllexport) const wchar_t* LibDescription() { return L"appleseed Renderer"; } __declspec(dllexport) int LibNumberClasses() { return 13 + g_shader_registry.get_size(); } __declspec(dllexport) ClassDesc2* LibClassDesc(int i) { switch (i) { case 0: return &g_appleseed_renderer_classdesc; case 1: return &g_appleseed_disneymtl_classdesc; case 2: return &g_appleseed_sssmtl_classdesc; case 3: return &g_appleseed_glassmtl_classdesc; case 4: return &g_appleseed_lightmtl_classdesc; case 5: return &g_appleseed_objpropsmod_classdesc; case 6: return &g_appleseed_envmap_classdesc; case 7: return &g_appleseed_blendmtl_classdesc; case 8: return &g_appleseed_metalmtl_classdesc; case 9: return &g_appleseed_plasticmtl_classdesc; case 10: return &g_appleseed_outputselector_classdesc; case 11: return &g_appleseed_renderelement_classdesc; case 12: return &g_appleseed_volumemtl_classdesc; // Make sure to update LibNumberClasses() if you add classes here. default: return g_shader_registry.get_class_descriptor(i - 13); } } __declspec(dllexport) ULONG LibVersion() { return VERSION_3DSMAX; } __declspec(dllexport) int LibInitialize() { start_memory_tracking(); asr::global_logger().add_target(&g_log_target); std::wstringstream sstr; sstr << "appleseed-max "; sstr << PluginVersionString; sstr << " plug-in using "; sstr << utf8_to_wide(asf::Appleseed::get_synthetic_version_string()); sstr << " loaded"; const auto title = sstr.str(); const std::wstring sep(title.size(), L'='); // We use GetCOREInterface()->Log()->LogEntry() directly rather than RENDERER_LOG_INFO() // because it seems that we are not running on the main thread (hence log messages are // enqueued to later be emitted from the main thread rather than being emitted directly) // but the Win32 message that should trigger message emission seems to get lost. GetCOREInterface()->Log()->LogEntry( SYSLOG_INFO, FALSE, L"appleseed", L"[appleseed] %s", sep.c_str()); GetCOREInterface()->Log()->LogEntry( SYSLOG_INFO, FALSE, L"appleseed", L"[appleseed] %s", title.c_str()); GetCOREInterface()->Log()->LogEntry( SYSLOG_INFO, FALSE, L"appleseed", L"[appleseed] %s", sep.c_str()); g_shader_registry.create_class_descriptors(); return TRUE; } } <|endoftext|>
<commit_before>/* * Copyright (c) 2010 ARM Limited * All rights reserved * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * Copyright (c) 2007-2008 The Florida State University * 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 copyright holders 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. * * Authors: Stephen Hines */ #include "arch/arm/faults.hh" #include "arch/arm/insts/static_inst.hh" #include "base/condcodes.hh" #include "base/cprintf.hh" #include "base/loader/symtab.hh" namespace ArmISA { // Shift Rm by an immediate value int32_t ArmStaticInstBase::shift_rm_imm(uint32_t base, uint32_t shamt, uint32_t type, uint32_t cfval) const { assert(shamt < 32); ArmShiftType shiftType; shiftType = (ArmShiftType)type; switch (shiftType) { case LSL: return base << shamt; case LSR: if (shamt == 0) return 0; else return base >> shamt; case ASR: if (shamt == 0) return (int32_t)base >> 31; else return (int32_t)base >> shamt; case ROR: if (shamt == 0) return (cfval << 31) | (base >> 1); // RRX else return (base << (32 - shamt)) | (base >> shamt); default: ccprintf(std::cerr, "Unhandled shift type\n"); exit(1); break; } return 0; } // Shift Rm by Rs int32_t ArmStaticInstBase::shift_rm_rs(uint32_t base, uint32_t shamt, uint32_t type, uint32_t cfval) const { enum ArmShiftType shiftType; shiftType = (enum ArmShiftType) type; switch (shiftType) { case LSL: if (shamt >= 32) return 0; else return base << shamt; case LSR: if (shamt >= 32) return 0; else return base >> shamt; case ASR: if (shamt >= 32) return (int32_t)base >> 31; else return (int32_t)base >> shamt; case ROR: shamt = shamt & 0x1f; if (shamt == 0) return base; else return (base << (32 - shamt)) | (base >> shamt); default: ccprintf(std::cerr, "Unhandled shift type\n"); exit(1); break; } return 0; } // Generate C for a shift by immediate bool ArmStaticInstBase::shift_carry_imm(uint32_t base, uint32_t shamt, uint32_t type, uint32_t cfval) const { enum ArmShiftType shiftType; shiftType = (enum ArmShiftType) type; switch (shiftType) { case LSL: if (shamt == 0) return cfval; else return (base >> (32 - shamt)) & 1; case LSR: if (shamt == 0) return (base >> 31); else return (base >> (shamt - 1)) & 1; case ASR: if (shamt == 0) return (base >> 31); else return (base >> (shamt - 1)) & 1; case ROR: shamt = shamt & 0x1f; if (shamt == 0) return (base & 1); // RRX else return (base >> (shamt - 1)) & 1; default: ccprintf(std::cerr, "Unhandled shift type\n"); exit(1); break; } return 0; } // Generate C for a shift by Rs bool ArmStaticInstBase::shift_carry_rs(uint32_t base, uint32_t shamt, uint32_t type, uint32_t cfval) const { enum ArmShiftType shiftType; shiftType = (enum ArmShiftType) type; if (shamt == 0) return cfval; switch (shiftType) { case LSL: if (shamt > 32) return 0; else return (base >> (32 - shamt)) & 1; case LSR: if (shamt > 32) return 0; else return (base >> (shamt - 1)) & 1; case ASR: if (shamt > 32) shamt = 32; return (base >> (shamt - 1)) & 1; case ROR: shamt = shamt & 0x1f; if (shamt == 0) shamt = 32; return (base >> (shamt - 1)) & 1; default: ccprintf(std::cerr, "Unhandled shift type\n"); exit(1); break; } return 0; } // Generate the appropriate carry bit for an addition operation bool ArmStaticInstBase::arm_add_carry(int32_t result, int32_t lhs, int32_t rhs) const { return findCarry(32, result, lhs, rhs); } // Generate the appropriate carry bit for a subtraction operation bool ArmStaticInstBase::arm_sub_carry(int32_t result, int32_t lhs, int32_t rhs) const { return findCarry(32, result, lhs, ~rhs); } bool ArmStaticInstBase::arm_add_overflow(int32_t result, int32_t lhs, int32_t rhs) const { return findOverflow(32, result, lhs, rhs); } bool ArmStaticInstBase::arm_sub_overflow(int32_t result, int32_t lhs, int32_t rhs) const { return findOverflow(32, result, lhs, ~rhs); } uint32_t ArmStaticInstBase::modified_imm(uint8_t ctrlImm, uint8_t dataImm) const { uint32_t bigData = dataImm; uint32_t bigCtrl = ctrlImm; if (bigCtrl < 4) { switch (bigCtrl) { case 0: return bigData; case 1: return bigData | (bigData << 16); case 2: return (bigData << 8) | (bigData << 24); case 3: return (bigData << 0) | (bigData << 8) | (bigData << 16) | (bigData << 24); } } bigCtrl = (bigCtrl << 1) | ((bigData >> 7) & 0x1); bigData |= (1 << 7); return bigData << (32 - bigCtrl); } void ArmStaticInstBase::printReg(std::ostream &os, int reg) const { if (reg < FP_Base_DepTag) { switch (reg) { case PCReg: ccprintf(os, "pc"); break; case StackPointerReg: ccprintf(os, "sp"); break; case FramePointerReg: ccprintf(os, "fp"); break; case ReturnAddressReg: ccprintf(os, "lr"); break; default: ccprintf(os, "r%d", reg); break; } } else if (reg < Ctrl_Base_DepTag) { ccprintf(os, "f%d", reg - FP_Base_DepTag); } else { reg -= Ctrl_Base_DepTag; assert(reg < NUM_MISCREGS); ccprintf(os, "%s", ArmISA::miscRegName[reg]); } } void ArmStaticInstBase::printMnemonic(std::ostream &os, const std::string &suffix, bool withPred) const { os << " " << mnemonic; if (withPred) { unsigned condCode = machInst.condCode; switch (condCode) { case COND_EQ: os << "eq"; break; case COND_NE: os << "ne"; break; case COND_CS: os << "cs"; break; case COND_CC: os << "cc"; break; case COND_MI: os << "mi"; break; case COND_PL: os << "pl"; break; case COND_VS: os << "vs"; break; case COND_VC: os << "vc"; break; case COND_HI: os << "hi"; break; case COND_LS: os << "ls"; break; case COND_GE: os << "ge"; break; case COND_LT: os << "lt"; break; case COND_GT: os << "gt"; break; case COND_LE: os << "le"; break; case COND_AL: // This one is implicit. break; case COND_UC: // Unconditional. break; default: panic("Unrecognized condition code %d.\n", condCode); } os << suffix << " "; } } void ArmStaticInstBase::printMemSymbol(std::ostream &os, const SymbolTable *symtab, const std::string &prefix, const Addr addr, const std::string &suffix) const { Addr symbolAddr; std::string symbol; if (symtab && symtab->findNearestSymbol(addr, symbol, symbolAddr)) { ccprintf(os, "%s%s", prefix, symbol); if (symbolAddr != addr) ccprintf(os, "+%d", addr - symbolAddr); ccprintf(os, suffix); } } void ArmStaticInstBase::printShiftOperand(std::ostream &os) const { printReg(os, machInst.rm); bool immShift = (machInst.opcode4 == 0); bool done = false; unsigned shiftAmt = (machInst.shiftSize); ArmShiftType type = (ArmShiftType)(uint32_t)machInst.shift; if ((type == LSR || type == ASR) && immShift && shiftAmt == 0) shiftAmt = 32; switch (type) { case LSL: if (immShift && shiftAmt == 0) { done = true; break; } os << ", LSL"; break; case LSR: os << ", LSR"; break; case ASR: os << ", ASR"; break; case ROR: if (immShift && shiftAmt == 0) { os << ", RRX"; done = true; break; } os << ", ROR"; break; default: panic("Tried to disassemble unrecognized shift type.\n"); } if (!done) { os << " "; if (immShift) os << "#" << shiftAmt; else printReg(os, machInst.rs); } } void ArmStaticInstBase::printDataInst(std::ostream &os, bool withImm) const { printMnemonic(os, machInst.sField ? "s" : ""); //XXX It would be nice if the decoder figured this all out for us. unsigned opcode = machInst.opcode; bool firstOp = true; // Destination // Cmp, cmn, teq, and tst don't have one. if (opcode < 8 || opcode > 0xb) { firstOp = false; printReg(os, machInst.rd); } // Source 1. // Mov and Movn don't have one of these. if (opcode != 0xd && opcode != 0xf) { if (!firstOp) os << ", "; firstOp = false; printReg(os, machInst.rn); } if (!firstOp) os << ", "; if (withImm) { unsigned rotate = machInst.rotate * 2; uint32_t imm = machInst.imm; ccprintf(os, "#%#x", (imm << (32 - rotate)) | (imm >> rotate)); } else { printShiftOperand(os); } } std::string ArmStaticInstBase::generateDisassembly(Addr pc, const SymbolTable *symtab) const { std::stringstream ss; printMnemonic(ss); return ss.str(); } } <commit_msg>ARM: Add a .w to the disassembly of 32 bit thumb instructions. This isn't technically correct since the .w should only be added if there are 32 and 16 bit encodings, but always having it always is better than never having it.<commit_after>/* * Copyright (c) 2010 ARM Limited * All rights reserved * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * Copyright (c) 2007-2008 The Florida State University * 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 copyright holders 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. * * Authors: Stephen Hines */ #include "arch/arm/faults.hh" #include "arch/arm/insts/static_inst.hh" #include "base/condcodes.hh" #include "base/cprintf.hh" #include "base/loader/symtab.hh" namespace ArmISA { // Shift Rm by an immediate value int32_t ArmStaticInstBase::shift_rm_imm(uint32_t base, uint32_t shamt, uint32_t type, uint32_t cfval) const { assert(shamt < 32); ArmShiftType shiftType; shiftType = (ArmShiftType)type; switch (shiftType) { case LSL: return base << shamt; case LSR: if (shamt == 0) return 0; else return base >> shamt; case ASR: if (shamt == 0) return (int32_t)base >> 31; else return (int32_t)base >> shamt; case ROR: if (shamt == 0) return (cfval << 31) | (base >> 1); // RRX else return (base << (32 - shamt)) | (base >> shamt); default: ccprintf(std::cerr, "Unhandled shift type\n"); exit(1); break; } return 0; } // Shift Rm by Rs int32_t ArmStaticInstBase::shift_rm_rs(uint32_t base, uint32_t shamt, uint32_t type, uint32_t cfval) const { enum ArmShiftType shiftType; shiftType = (enum ArmShiftType) type; switch (shiftType) { case LSL: if (shamt >= 32) return 0; else return base << shamt; case LSR: if (shamt >= 32) return 0; else return base >> shamt; case ASR: if (shamt >= 32) return (int32_t)base >> 31; else return (int32_t)base >> shamt; case ROR: shamt = shamt & 0x1f; if (shamt == 0) return base; else return (base << (32 - shamt)) | (base >> shamt); default: ccprintf(std::cerr, "Unhandled shift type\n"); exit(1); break; } return 0; } // Generate C for a shift by immediate bool ArmStaticInstBase::shift_carry_imm(uint32_t base, uint32_t shamt, uint32_t type, uint32_t cfval) const { enum ArmShiftType shiftType; shiftType = (enum ArmShiftType) type; switch (shiftType) { case LSL: if (shamt == 0) return cfval; else return (base >> (32 - shamt)) & 1; case LSR: if (shamt == 0) return (base >> 31); else return (base >> (shamt - 1)) & 1; case ASR: if (shamt == 0) return (base >> 31); else return (base >> (shamt - 1)) & 1; case ROR: shamt = shamt & 0x1f; if (shamt == 0) return (base & 1); // RRX else return (base >> (shamt - 1)) & 1; default: ccprintf(std::cerr, "Unhandled shift type\n"); exit(1); break; } return 0; } // Generate C for a shift by Rs bool ArmStaticInstBase::shift_carry_rs(uint32_t base, uint32_t shamt, uint32_t type, uint32_t cfval) const { enum ArmShiftType shiftType; shiftType = (enum ArmShiftType) type; if (shamt == 0) return cfval; switch (shiftType) { case LSL: if (shamt > 32) return 0; else return (base >> (32 - shamt)) & 1; case LSR: if (shamt > 32) return 0; else return (base >> (shamt - 1)) & 1; case ASR: if (shamt > 32) shamt = 32; return (base >> (shamt - 1)) & 1; case ROR: shamt = shamt & 0x1f; if (shamt == 0) shamt = 32; return (base >> (shamt - 1)) & 1; default: ccprintf(std::cerr, "Unhandled shift type\n"); exit(1); break; } return 0; } // Generate the appropriate carry bit for an addition operation bool ArmStaticInstBase::arm_add_carry(int32_t result, int32_t lhs, int32_t rhs) const { return findCarry(32, result, lhs, rhs); } // Generate the appropriate carry bit for a subtraction operation bool ArmStaticInstBase::arm_sub_carry(int32_t result, int32_t lhs, int32_t rhs) const { return findCarry(32, result, lhs, ~rhs); } bool ArmStaticInstBase::arm_add_overflow(int32_t result, int32_t lhs, int32_t rhs) const { return findOverflow(32, result, lhs, rhs); } bool ArmStaticInstBase::arm_sub_overflow(int32_t result, int32_t lhs, int32_t rhs) const { return findOverflow(32, result, lhs, ~rhs); } uint32_t ArmStaticInstBase::modified_imm(uint8_t ctrlImm, uint8_t dataImm) const { uint32_t bigData = dataImm; uint32_t bigCtrl = ctrlImm; if (bigCtrl < 4) { switch (bigCtrl) { case 0: return bigData; case 1: return bigData | (bigData << 16); case 2: return (bigData << 8) | (bigData << 24); case 3: return (bigData << 0) | (bigData << 8) | (bigData << 16) | (bigData << 24); } } bigCtrl = (bigCtrl << 1) | ((bigData >> 7) & 0x1); bigData |= (1 << 7); return bigData << (32 - bigCtrl); } void ArmStaticInstBase::printReg(std::ostream &os, int reg) const { if (reg < FP_Base_DepTag) { switch (reg) { case PCReg: ccprintf(os, "pc"); break; case StackPointerReg: ccprintf(os, "sp"); break; case FramePointerReg: ccprintf(os, "fp"); break; case ReturnAddressReg: ccprintf(os, "lr"); break; default: ccprintf(os, "r%d", reg); break; } } else if (reg < Ctrl_Base_DepTag) { ccprintf(os, "f%d", reg - FP_Base_DepTag); } else { reg -= Ctrl_Base_DepTag; assert(reg < NUM_MISCREGS); ccprintf(os, "%s", ArmISA::miscRegName[reg]); } } void ArmStaticInstBase::printMnemonic(std::ostream &os, const std::string &suffix, bool withPred) const { os << " " << mnemonic; if (withPred) { unsigned condCode = machInst.condCode; switch (condCode) { case COND_EQ: os << "eq"; break; case COND_NE: os << "ne"; break; case COND_CS: os << "cs"; break; case COND_CC: os << "cc"; break; case COND_MI: os << "mi"; break; case COND_PL: os << "pl"; break; case COND_VS: os << "vs"; break; case COND_VC: os << "vc"; break; case COND_HI: os << "hi"; break; case COND_LS: os << "ls"; break; case COND_GE: os << "ge"; break; case COND_LT: os << "lt"; break; case COND_GT: os << "gt"; break; case COND_LE: os << "le"; break; case COND_AL: // This one is implicit. break; case COND_UC: // Unconditional. break; default: panic("Unrecognized condition code %d.\n", condCode); } os << suffix; if (machInst.bigThumb) os << ".w"; os << " "; } } void ArmStaticInstBase::printMemSymbol(std::ostream &os, const SymbolTable *symtab, const std::string &prefix, const Addr addr, const std::string &suffix) const { Addr symbolAddr; std::string symbol; if (symtab && symtab->findNearestSymbol(addr, symbol, symbolAddr)) { ccprintf(os, "%s%s", prefix, symbol); if (symbolAddr != addr) ccprintf(os, "+%d", addr - symbolAddr); ccprintf(os, suffix); } } void ArmStaticInstBase::printShiftOperand(std::ostream &os) const { printReg(os, machInst.rm); bool immShift = (machInst.opcode4 == 0); bool done = false; unsigned shiftAmt = (machInst.shiftSize); ArmShiftType type = (ArmShiftType)(uint32_t)machInst.shift; if ((type == LSR || type == ASR) && immShift && shiftAmt == 0) shiftAmt = 32; switch (type) { case LSL: if (immShift && shiftAmt == 0) { done = true; break; } os << ", LSL"; break; case LSR: os << ", LSR"; break; case ASR: os << ", ASR"; break; case ROR: if (immShift && shiftAmt == 0) { os << ", RRX"; done = true; break; } os << ", ROR"; break; default: panic("Tried to disassemble unrecognized shift type.\n"); } if (!done) { os << " "; if (immShift) os << "#" << shiftAmt; else printReg(os, machInst.rs); } } void ArmStaticInstBase::printDataInst(std::ostream &os, bool withImm) const { printMnemonic(os, machInst.sField ? "s" : ""); //XXX It would be nice if the decoder figured this all out for us. unsigned opcode = machInst.opcode; bool firstOp = true; // Destination // Cmp, cmn, teq, and tst don't have one. if (opcode < 8 || opcode > 0xb) { firstOp = false; printReg(os, machInst.rd); } // Source 1. // Mov and Movn don't have one of these. if (opcode != 0xd && opcode != 0xf) { if (!firstOp) os << ", "; firstOp = false; printReg(os, machInst.rn); } if (!firstOp) os << ", "; if (withImm) { unsigned rotate = machInst.rotate * 2; uint32_t imm = machInst.imm; ccprintf(os, "#%#x", (imm << (32 - rotate)) | (imm >> rotate)); } else { printShiftOperand(os); } } std::string ArmStaticInstBase::generateDisassembly(Addr pc, const SymbolTable *symtab) const { std::stringstream ss; printMnemonic(ss); return ss.str(); } } <|endoftext|>
<commit_before>/* * http://github.com/dusty-nv/jetson-inference */ // #include "gstCamera.h" #include <ros/ros.h> #include <image_transport/image_transport.h> #include <cv_bridge/cv_bridge.h> #include <sensor_msgs/image_encodings.h> #include <autobot/compound_img.h> #include <autobot/detected_img.h> #include <autobot/bounding_box.h> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include <boost/make_shared.hpp> #include <stdio.h> #include <signal.h> #include <unistd.h> #include <chrono> #include <jetson-inference/cudaMappedMemory.h> #include <jetson-inference/cudaNormalize.h> #include <jetson-inference/cudaFont.h> #include <jetson-inference/detectNet.h> #define DEFAULT_CAMERA -1 // -1 for onboard camera, or change to index of /dev/video V4L2 camera (>=0) using namespace std; bool signal_recieved = false; //void sig_handler(int signo) //{ //if( signo == SIGINT ) //{ //printf("received SIGINT\n"); //signal_recieved = true; //} //} static const std::string OPENCV_WINDOW = "Image post bridge conversion"; static const std::string OPENCV_WINDOW2 = "Image post bit depth conversion"; static const std::string OPENCV_WINDOW3 = "Image post color conversion"; static const std::string OPENCV_WINDOW4 = "Image window"; class ObjectDetector { ros::NodeHandle nh_; image_transport::ImageTransport it_; ros::Subscriber image_sub_; ros::Publisher detect_img_pub; cv::Mat cv_im; cv_bridge::CvImagePtr cv_ptr; std::chrono::steady_clock::time_point prev; image_transport::Subscriber dummysub; float confidence = 0.0f; float* bbCPU = NULL; float* bbCUDA = NULL; float* confCPU = NULL; float* confCUDA = NULL; detectNet* net = NULL; uint32_t maxBoxes = 0; uint32_t classes = 0; float4* gpu_data = NULL; uint32_t imgWidth; uint32_t imgHeight; size_t imgSize; bool displayToScreen = false; public: ObjectDetector(int argc, char** argv, bool display) : it_(nh_) { // Subscrive to input video feed and publish output video feed // image_sub_ = it_.subscribe("/left/image_rect_color", 2, // &ObjectDetector::imageCb, this); image_sub_ = nh_.subscribe("/compound_img", 2, &ObjectDetector::imageCb, this); detect_img_pub = nh_.advertise<autobot::detected_img>("/detected_image", 2); dummysub = it_.subscribe("depth/depth_registered", 1, &ObjectDetector::dummy, this); displayToScreen = display; if (displayToScreen) { cv::namedWindow(OPENCV_WINDOW); cout << "Named a window" << endl; prev = std::chrono::steady_clock::now(); } /* * create detectNet */ net = detectNet::Create(argc, argv); cout << "Created DetectNet" << endl; if( !net ) { printf("obj_detect: failed to initialize imageNet\n"); } maxBoxes = net->GetMaxBoundingBoxes(); printf("maximum bounding boxes: %u\n", maxBoxes); classes = net->GetNumClasses(); /* * allocate memory for output bounding boxes and class confidence */ if( !cudaAllocMapped((void**)&bbCPU, (void**)&bbCUDA, maxBoxes * sizeof(float4)) || !cudaAllocMapped((void**)&confCPU, (void**)&confCUDA, maxBoxes * classes * sizeof(float)) ) { printf("detectnet-console: failed to alloc output memory\n"); } cout << "Allocated CUDA mem" << endl; maxBoxes = net->GetMaxBoundingBoxes(); printf("maximum bounding boxes: %u\n", maxBoxes); classes = net->GetNumClasses(); cout << "Constructor operations complete" << endl; } ~ObjectDetector() { if (displayToScreen) { cv::destroyWindow(OPENCV_WINDOW); } } void dummy(const sensor_msgs::ImageConstPtr& msg) { } void imageCb(const autobot::compound_img& cp_msg) { //ROS_INFO("callback called"); //boost::shared_ptr<sensor_msgs::Image> cp_shared(&cp_msg.depthImg); //sensor_msgs::ImageConstPtr msg = cp_shared; try { cv_ptr = cv_bridge::toCvCopy(cp_msg.img, sensor_msgs::image_encodings::BGR8); cv_im = cv_ptr->image; cv_im.convertTo(cv_im,CV_32FC3); // convert color cv::cvtColor(cv_im,cv_im,CV_BGR2RGBA); } catch (cv_bridge::Exception& e) { ROS_ERROR("cv_bridge exception: %s", e.what()); return; } // allocate GPU data if necessary if (!gpu_data) { ROS_INFO("first allocation"); CUDA(cudaMalloc(&gpu_data, cv_im.rows*cv_im.cols * sizeof(float4))); } else if (imgHeight != cv_im.rows || imgWidth != cv_im.cols) { ROS_INFO("re allocation"); // reallocate for a new image size if necessary CUDA(cudaFree(gpu_data)); CUDA(cudaMalloc(&gpu_data, cv_im.rows*cv_im.cols * sizeof(float4))); } imgHeight = cv_im.rows; imgWidth = cv_im.cols; imgSize = cv_im.rows*cv_im.cols * sizeof(float4); float4* cpu_data = (float4*)(cv_im.data); // copy to device CUDA(cudaMemcpy(gpu_data, cpu_data, imgSize, cudaMemcpyHostToDevice)); void* imgCUDA = NULL; // find object with detectNet int numBoundingBoxes = maxBoxes; if (net->Detect((float*)gpu_data, imgWidth, imgHeight, bbCPU, &numBoundingBoxes, confCPU)) { //printf("%i bounding boxes detected\n", numBoundingBoxes); int lastClass = 0; int lastStart = 0; for( int n=0; n < numBoundingBoxes; n++ ) { const int nc = confCPU[n*2+1]; float* bb = bbCPU + (n * 4); printf("bounding box %i (%f, %f) (%f, %f) w=%f h=%f\n", n, bb[0], bb[1], bb[2], bb[3], bb[2] - bb[0], bb[3] - bb[1]); cv::rectangle( cv_im, cv::Point( bb[0], bb[1] ), cv::Point( bb[2], bb[3]), cv::Scalar( 255, 55, 0 ), +1, 4 ); } if (displayToScreen) { std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now(); float fps = 1000.0 / std::chrono::duration_cast<std::chrono::milliseconds>(now - prev).count() ; prev = now; char str[256]; sprintf(str, "TensorRT build %x | %s | %04.1f FPS", NV_GIE_VERSION, net->HasFP16() ? "FP16" : "FP32", fps); cv::setWindowTitle(OPENCV_WINDOW, str); } } // update image back to original cv_im.convertTo(cv_im,CV_8UC3); cv::cvtColor(cv_im,cv_im,CV_RGBA2BGR); // Update GUI Window if (displayToScreen) { cv::imshow(OPENCV_WINDOW, cv_im); cv::waitKey(1); } for( int n=0; n < numBoundingBoxes; n++ ) { const int nc = confCPU[n*2+1]; float* bb = bbCPU + (n * 4); sensor_msgs::ImagePtr msg; float crop_width = bb[2] - bb[0]; float crop_height = bb[3] - bb[1]; float origin_x = bb[0]; float origin_y = bb[1]; printf("imgWidth: %u imgHeight: %u\n",imgWidth,imgHeight); printf("BEFORE: origin_x: %f origin_y: %f crop_width: %f crop_height: %f\n",origin_x, origin_y, crop_width, crop_height); if (crop_width < crop_height) { float diff = crop_height - crop_width; printf("diff: %f\n",diff); origin_x = origin_x - (diff / 2.0); crop_width = crop_width + (diff / 2.0); } else if (crop_width > crop_height) { float diff = crop_width - crop_height; printf("diff: %f\n",diff); origin_y = origin_y - (diff / 2.0); crop_height = crop_height + (diff / 2.0); } printf("MIDDLE: origin_x: %f origin_y: %f crop_width: %f crop_height: %f\n",origin_x, origin_y, crop_width, crop_height); if (origin_x < 0.0) { origin_x = 0.0; } if (origin_y < 0.0) { origin_y = 0.0; } if (origin_x + crop_width >= (float)imgWidth ) { crop_width = (float)imgWidth - origin_x - 1.0; } if (origin_y + crop_height >= (float)imgHeight) { crop_height = (float)imgHeight - origin_y - 1.0; } printf("AFTER : origin_x: %f origin_y: %f crop_width: %f crop_height: %f\n",origin_x, origin_y, crop_width, crop_height); cv::Mat croppedImage = cv_im(cv::Rect(origin_x, origin_y, crop_width, crop_height)); sensor_msgs::ImagePtr img_msg = cv_bridge::CvImage(std_msgs::Header(), "bgr8", croppedImage).toImageMsg(); boost::shared_ptr<autobot::detected_img> detected_img = boost::make_shared<autobot::detected_img>(); boost::shared_ptr<autobot::bounding_box> bbox = boost::make_shared<autobot::bounding_box>(); bbox->origin_x = origin_x; bbox->origin_y = origin_y; bbox->height = crop_height; bbox->width = crop_width; detected_img->img = *img_msg.get(); detected_img->depthImg = cp_msg.depthImg; detected_img->box = *bbox.get(); detect_img_pub.publish<autobot::detected_img>(detected_img); if (displayToScreen) { cv::imshow("crop", croppedImage); cv::waitKey(1); } } } }; int main( int argc, char** argv ) { cout << "starting node" << endl; printf("obj_detect\n args (%i): ", argc); ros::init(argc, argv, "obj_detector"); ros::NodeHandle nh; bool displayToScreen = false; for( int i=0; i < argc; i++ ) { printf("%i [%s] ", i, argv[i]); if (strcmp(argv[i], "--DISPLAY") == 0) { displayToScreen = true; } } printf("\n\n"); ObjectDetector ic(argc, argv, displayToScreen); ros::spin(); return 0; } <commit_msg>properly square the cropped photo of object of interest and remove extraneous cropped image imshow display function<commit_after>/* * http://github.com/dusty-nv/jetson-inference */ // #include "gstCamera.h" #include <ros/ros.h> #include <image_transport/image_transport.h> #include <cv_bridge/cv_bridge.h> #include <sensor_msgs/image_encodings.h> #include <autobot/compound_img.h> #include <autobot/detected_img.h> #include <autobot/bounding_box.h> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include <boost/make_shared.hpp> #include <stdio.h> #include <signal.h> #include <unistd.h> #include <chrono> #include <jetson-inference/cudaMappedMemory.h> #include <jetson-inference/cudaNormalize.h> #include <jetson-inference/cudaFont.h> #include <jetson-inference/detectNet.h> #define DEFAULT_CAMERA -1 // -1 for onboard camera, or change to index of /dev/video V4L2 camera (>=0) using namespace std; bool signal_recieved = false; //void sig_handler(int signo) //{ //if( signo == SIGINT ) //{ //printf("received SIGINT\n"); //signal_recieved = true; //} //} static const std::string OPENCV_WINDOW = "Image post bridge conversion"; static const std::string OPENCV_WINDOW2 = "Image post bit depth conversion"; static const std::string OPENCV_WINDOW3 = "Image post color conversion"; static const std::string OPENCV_WINDOW4 = "Image window"; class ObjectDetector { ros::NodeHandle nh_; image_transport::ImageTransport it_; ros::Subscriber image_sub_; ros::Publisher detect_img_pub; cv::Mat cv_im; cv_bridge::CvImagePtr cv_ptr; std::chrono::steady_clock::time_point prev; image_transport::Subscriber dummysub; float confidence = 0.0f; float* bbCPU = NULL; float* bbCUDA = NULL; float* confCPU = NULL; float* confCUDA = NULL; detectNet* net = NULL; uint32_t maxBoxes = 0; uint32_t classes = 0; float4* gpu_data = NULL; uint32_t imgWidth; uint32_t imgHeight; size_t imgSize; bool displayToScreen = false; public: ObjectDetector(int argc, char** argv, bool display) : it_(nh_) { // Subscrive to input video feed and publish output video feed // image_sub_ = it_.subscribe("/left/image_rect_color", 2, // &ObjectDetector::imageCb, this); image_sub_ = nh_.subscribe("/compound_img", 2, &ObjectDetector::imageCb, this); detect_img_pub = nh_.advertise<autobot::detected_img>("/detected_image", 2); dummysub = it_.subscribe("depth/depth_registered", 1, &ObjectDetector::dummy, this); displayToScreen = display; if (displayToScreen) { cv::namedWindow(OPENCV_WINDOW); cout << "Named a window" << endl; prev = std::chrono::steady_clock::now(); } /* * create detectNet */ net = detectNet::Create(argc, argv); cout << "Created DetectNet" << endl; if( !net ) { printf("obj_detect: failed to initialize imageNet\n"); } maxBoxes = net->GetMaxBoundingBoxes(); printf("maximum bounding boxes: %u\n", maxBoxes); classes = net->GetNumClasses(); /* * allocate memory for output bounding boxes and class confidence */ if( !cudaAllocMapped((void**)&bbCPU, (void**)&bbCUDA, maxBoxes * sizeof(float4)) || !cudaAllocMapped((void**)&confCPU, (void**)&confCUDA, maxBoxes * classes * sizeof(float)) ) { printf("detectnet-console: failed to alloc output memory\n"); } cout << "Allocated CUDA mem" << endl; maxBoxes = net->GetMaxBoundingBoxes(); printf("maximum bounding boxes: %u\n", maxBoxes); classes = net->GetNumClasses(); cout << "Constructor operations complete" << endl; } ~ObjectDetector() { if (displayToScreen) { cv::destroyWindow(OPENCV_WINDOW); } } void dummy(const sensor_msgs::ImageConstPtr& msg) { } void imageCb(const autobot::compound_img& cp_msg) { //ROS_INFO("callback called"); //boost::shared_ptr<sensor_msgs::Image> cp_shared(&cp_msg.depthImg); //sensor_msgs::ImageConstPtr msg = cp_shared; try { cv_ptr = cv_bridge::toCvCopy(cp_msg.img, sensor_msgs::image_encodings::BGR8); cv_im = cv_ptr->image; cv_im.convertTo(cv_im,CV_32FC3); // convert color cv::cvtColor(cv_im,cv_im,CV_BGR2RGBA); } catch (cv_bridge::Exception& e) { ROS_ERROR("cv_bridge exception: %s", e.what()); return; } // allocate GPU data if necessary if (!gpu_data) { ROS_INFO("first allocation"); CUDA(cudaMalloc(&gpu_data, cv_im.rows*cv_im.cols * sizeof(float4))); } else if (imgHeight != cv_im.rows || imgWidth != cv_im.cols) { ROS_INFO("re allocation"); // reallocate for a new image size if necessary CUDA(cudaFree(gpu_data)); CUDA(cudaMalloc(&gpu_data, cv_im.rows*cv_im.cols * sizeof(float4))); } imgHeight = cv_im.rows; imgWidth = cv_im.cols; imgSize = cv_im.rows*cv_im.cols * sizeof(float4); float4* cpu_data = (float4*)(cv_im.data); // copy to device CUDA(cudaMemcpy(gpu_data, cpu_data, imgSize, cudaMemcpyHostToDevice)); void* imgCUDA = NULL; // find object with detectNet int numBoundingBoxes = maxBoxes; if (net->Detect((float*)gpu_data, imgWidth, imgHeight, bbCPU, &numBoundingBoxes, confCPU)) { //printf("%i bounding boxes detected\n", numBoundingBoxes); int lastClass = 0; int lastStart = 0; for( int n=0; n < numBoundingBoxes; n++ ) { const int nc = confCPU[n*2+1]; float* bb = bbCPU + (n * 4); printf("bounding box %i (%f, %f) (%f, %f) w=%f h=%f\n", n, bb[0], bb[1], bb[2], bb[3], bb[2] - bb[0], bb[3] - bb[1]); //cv::rectangle( cv_im, cv::Point( bb[0], bb[1] ), cv::Point( bb[2], bb[3]), cv::Scalar( 255, 55, 0 ), +1, 4 ); } if (displayToScreen) { std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now(); float fps = 1000.0 / std::chrono::duration_cast<std::chrono::milliseconds>(now - prev).count() ; prev = now; char str[256]; sprintf(str, "TensorRT build %x | %s | %04.1f FPS", NV_GIE_VERSION, net->HasFP16() ? "FP16" : "FP32", fps); cv::setWindowTitle(OPENCV_WINDOW, str); } } // update image back to original cv_im.convertTo(cv_im,CV_8UC3); cv::cvtColor(cv_im,cv_im,CV_RGBA2BGR); for( int n=0; n < numBoundingBoxes; n++ ) { const int nc = confCPU[n*2+1]; float* bb = bbCPU + (n * 4); sensor_msgs::ImagePtr msg; float crop_width = bb[2] - bb[0]; float crop_height = bb[3] - bb[1]; float origin_x = bb[0]; float origin_y = bb[1]; printf("imgWidth: %u imgHeight: %u\n",imgWidth,imgHeight); printf("BEFORE: origin_x: %f origin_y: %f crop_width: %f crop_height: %f\n",origin_x, origin_y, crop_width, crop_height); if (crop_width < crop_height) { float diff = crop_height - crop_width; printf("diff: %f\n",diff); origin_x = origin_x - (diff / 2.0); crop_width = crop_height; } else if (crop_width > crop_height) { float diff = crop_width - crop_height; printf("diff: %f\n",diff); origin_y = origin_y - (diff / 2.0); crop_height = crop_width; } printf("MIDDLE: origin_x: %f origin_y: %f crop_width: %f crop_height: %f\n",origin_x, origin_y, crop_width, crop_height); if (origin_x < 0.0) { origin_x = 0.0; } if (origin_y < 0.0) { origin_y = 0.0; } if (origin_x + crop_width >= (float)imgWidth ) { crop_width = (float)imgWidth - origin_x - 1.0; } if (origin_y + crop_height >= (float)imgHeight) { crop_height = (float)imgHeight - origin_y - 1.0; } printf("AFTER : origin_x: %f origin_y: %f crop_width: %f crop_height: %f\n",origin_x, origin_y, crop_width, crop_height); cv::Mat croppedImage = cv_im(cv::Rect(origin_x, origin_y, crop_width, crop_height)) ; sensor_msgs::ImagePtr img_msg = cv_bridge::CvImage(std_msgs::Header(), "bgr8", croppedImage).toImageMsg(); boost::shared_ptr<autobot::detected_img> detected_img = boost::make_shared<autobot::detected_img>(); boost::shared_ptr<autobot::bounding_box> bbox = boost::make_shared<autobot::bounding_box>(); bbox->origin_x = origin_x; bbox->origin_y = origin_y; bbox->height = crop_height; bbox->width = crop_width; detected_img->img = *img_msg.get(); detected_img->depthImg = cp_msg.depthImg; detected_img->box = *bbox.get(); detect_img_pub.publish<autobot::detected_img>(detected_img); if (displayToScreen) { //cv::imshow("crop", croppedImage); cv::waitKey(1); } } for( int n=0; n < numBoundingBoxes; n++ ) { float* bb = bbCPU + (n * 4); cv::rectangle( cv_im, cv::Point( bb[0], bb[1] ), cv::Point( bb[2], bb[3]), cv::Scalar( 255, 55, 0 ), +1, 4 ); } // Update GUI Window if (displayToScreen) { cv::imshow(OPENCV_WINDOW, cv_im); cv::waitKey(1); } } }; int main( int argc, char** argv ) { cout << "starting node" << endl; printf("obj_detect\n args (%i): ", argc); ros::init(argc, argv, "obj_detector"); ros::NodeHandle nh; bool displayToScreen = false; for( int i=0; i < argc; i++ ) { printf("%i [%s] ", i, argv[i]); if (strcmp(argv[i], "--DISPLAY") == 0) { displayToScreen = true; } } printf("\n\n"); ObjectDetector ic(argc, argv, displayToScreen); ros::spin(); return 0; } <|endoftext|>
<commit_before>#pragma once #include "blackhole/config.hpp" #include "blackhole/detail/thread/lock.hpp" #include "blackhole/detail/config/noncopyable.hpp" #include "blackhole/forwards.hpp" #include "blackhole/record.hpp" #include "blackhole/config.hpp" namespace blackhole { template<class Wrapper> struct unwrap { typedef Wrapper wrapper_type; typedef typename unwrap< typename wrapper_type::underlying_type >::logger_type logger_type; static logger_type& log(wrapper_type& wrapper) { return unwrap< typename wrapper_type::underlying_type >::log(*wrapper.wrapped); } static const logger_type& log(const wrapper_type& wrapper) { return unwrap< typename wrapper_type::underlying_type >::log(*wrapper.wrapped); } }; template<> struct unwrap<logger_base_t> { typedef logger_base_t wrapper_type; typedef logger_base_t logger_type; static logger_type& log(logger_type& log) { return log; } static const logger_type& log(const logger_type& log) { return log; } }; template<typename Level> struct unwrap<verbose_logger_t<Level>> { typedef verbose_logger_t<Level> wrapper_type; typedef verbose_logger_t<Level> logger_type; static logger_type& log(logger_type& log) { return log; } static const logger_type& log(const logger_type& log) { return log; } }; template<class Wrapped> class wrapper_t { BLACKHOLE_DECLARE_NONCOPYABLE(wrapper_t); template<class> friend struct unwrap; public: typedef Wrapped underlying_type; typedef typename unwrap<underlying_type>::logger_type logger_type; private: underlying_type* wrapped; attribute::set_t attributes; mutable std::mutex mutex; public: wrapper_t(underlying_type& wrapped, attribute::set_t attributes) : wrapped(&wrapped), attributes(std::move(attributes)) {} wrapper_t(const wrapper_t& wrapper, const attribute::set_t& attributes) : wrapped(wrapper.wrapped), attributes(wrapper.attributes) { std::copy(attributes.begin(), attributes.end(), std::back_inserter(this->attributes)); } wrapper_t(wrapper_t&& other) { *this = std::move(other); } wrapper_t& operator=(wrapper_t&& other) { if (this != &other) { auto lock = detail::thread::make_multi_lock_t(mutex, other.mutex); wrapped = other.wrapped; other.wrapped = nullptr; attributes = std::move(other.attributes); } return *this; } /*! * Return non-const reference to the underlying logger. */ logger_type& log() { return unwrap<wrapper_t>::log(*this); } /*! * Return const reference to the underlying logger. */ const logger_type& log() const { return unwrap<wrapper_t>::log(*this); } record_t open_record() const { return wrapped->open_record(attributes); } record_t open_record(attribute::pair_t attribute) const { attribute::set_t attributes = this->attributes; attributes.emplace_back(attribute); return wrapped->open_record(std::move(attributes)); } record_t open_record(attribute::set_t attributes) const { std::copy(this->attributes.begin(), this->attributes.end(), std::back_inserter(attributes)); return wrapped->open_record(std::move(attributes)); } template<typename Level> record_t open_record(Level level, attribute::set_t attributes = attribute::set_t()) const { // TODO: Move inserter is better. std::copy(this->attributes.begin(), this->attributes.end(), std::back_inserter(attributes)); return wrapped->open_record(level, std::move(attributes)); } void push(record_t&& record) const { wrapped->push(std::move(record)); } }; } // namespace blackhole <commit_msg>[Planning] Another planning stuff.<commit_after>#pragma once #include "blackhole/config.hpp" #include "blackhole/detail/thread/lock.hpp" #include "blackhole/detail/config/noncopyable.hpp" #include "blackhole/forwards.hpp" #include "blackhole/record.hpp" #include "blackhole/config.hpp" namespace blackhole { template<class Wrapper> struct unwrap { typedef Wrapper wrapper_type; typedef typename unwrap< typename wrapper_type::underlying_type >::logger_type logger_type; static logger_type& log(wrapper_type& wrapper) { return unwrap< typename wrapper_type::underlying_type >::log(*wrapper.wrapped); } static const logger_type& log(const wrapper_type& wrapper) { return unwrap< typename wrapper_type::underlying_type >::log(*wrapper.wrapped); } }; template<> struct unwrap<logger_base_t> { typedef logger_base_t wrapper_type; typedef logger_base_t logger_type; static logger_type& log(logger_type& log) { return log; } static const logger_type& log(const logger_type& log) { return log; } }; template<typename Level> struct unwrap<verbose_logger_t<Level>> { typedef verbose_logger_t<Level> wrapper_type; typedef verbose_logger_t<Level> logger_type; static logger_type& log(logger_type& log) { return log; } static const logger_type& log(const logger_type& log) { return log; } }; template<class Wrapped> class wrapper_t { BLACKHOLE_DECLARE_NONCOPYABLE(wrapper_t); template<class> friend struct unwrap; public: typedef Wrapped underlying_type; typedef typename unwrap<underlying_type>::logger_type logger_type; private: underlying_type* wrapped; attribute::set_t attributes; // TODO: Class isn't completely thread-safe. mutable std::mutex mutex; public: wrapper_t(underlying_type& wrapped, attribute::set_t attributes) : wrapped(&wrapped), attributes(std::move(attributes)) {} wrapper_t(const wrapper_t& wrapper, const attribute::set_t& attributes) : wrapped(wrapper.wrapped), attributes(wrapper.attributes) { std::copy(attributes.begin(), attributes.end(), std::back_inserter(this->attributes)); } wrapper_t(wrapper_t&& other) { *this = std::move(other); } wrapper_t& operator=(wrapper_t&& other) { if (this != &other) { auto lock = detail::thread::make_multi_lock_t(mutex, other.mutex); wrapped = other.wrapped; other.wrapped = nullptr; attributes = std::move(other.attributes); } return *this; } /*! * Return non-const reference to the underlying logger. */ logger_type& log() { return unwrap<wrapper_t>::log(*this); } /*! * Return const reference to the underlying logger. */ const logger_type& log() const { return unwrap<wrapper_t>::log(*this); } record_t open_record() const { return wrapped->open_record(attributes); } record_t open_record(attribute::pair_t attribute) const { attribute::set_t attributes = this->attributes; attributes.emplace_back(attribute); return wrapped->open_record(std::move(attributes)); } record_t open_record(attribute::set_t attributes) const { std::copy(this->attributes.begin(), this->attributes.end(), std::back_inserter(attributes)); return wrapped->open_record(std::move(attributes)); } template<typename Level> record_t open_record(Level level, attribute::set_t attributes = attribute::set_t()) const { // TODO: Move inserter is better. std::copy(this->attributes.begin(), this->attributes.end(), std::back_inserter(attributes)); return wrapped->open_record(level, std::move(attributes)); } void push(record_t&& record) const { wrapped->push(std::move(record)); } }; } // namespace blackhole <|endoftext|>
<commit_before>/* bzflag * Copyright (c) 1993 - 2005 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #include <string> #include "SilenceDefaultKey.h" #include "KeyManager.h" #include "LocalPlayer.h" #include "HUDRenderer.h" #include "Roster.h" #include "playing.h" // THIS IS TEMPORARY..TO BE REMOVED..BABY STEPS // // Choose person to silence SilenceDefaultKey::SilenceDefaultKey() { } bool SilenceDefaultKey::keyPress(const BzfKeyEvent& key) { bool sendIt; LocalPlayer *myTank = LocalPlayer::getMyTank(); if (KEYMGR.get(key, true) == "jump") { // jump while typing myTank->setJump(); } if (myTank->getInputMethod() != LocalPlayer::Keyboard) { if ((key.button == BzfKeyEvent::Up) || (key.button == BzfKeyEvent::Down) || (key.button == BzfKeyEvent::Left) || (key.button == BzfKeyEvent::Right)) return true; } switch (key.ascii) { case 3: // ^C case 27: // escape // case 127: // delete sendIt = false; // finished composing -- don't send break; case 4: // ^D case 13: // return sendIt = true; break; default: return false; } if (sendIt) { std::string message = hud->getComposeString(); // find the name of the person to silence, // either by picking through arrow keys or by compose const char* name = NULL; if (message.size() == 0) { // silence just by picking arrowkeys const Player * silenceMe = myTank->getRecipient(); if (silenceMe) { name = silenceMe->getCallSign(); } } else if (message.size() > 0) { // typed in name name = message.c_str(); } // if name is NULL we skip if (name != NULL) { // bad indent :) int inListPos = -1; for (unsigned int i = 0; i < silencePlayers.size(); i++) { if (strcmp(silencePlayers[i].c_str(),name) == 0) { inListPos = i; } } bool isInList = (inListPos != -1); Player *loudmouth = getPlayerByName(name); if (loudmouth) { // we know this person exists if (!isInList) { // exists and not in silence list silencePlayers.push_back(name); std::string message = "Silenced "; message += (name); addMessage(NULL, message); } else { // exists and in list --> remove from list silencePlayers.erase(silencePlayers.begin() + inListPos); std::string message = "Unsilenced "; message += (name); addMessage(NULL, message); } } else { // person does not exist, but may be in silence list if (isInList) { // does not exist but is in list --> remove silencePlayers.erase(silencePlayers.begin() + inListPos); std::string message = "Unsilenced "; message += (name); if (strcmp (name, "*") == 0) { // to make msg fancier message = "Unblocked Msgs"; } addMessage(NULL, message); } else { // does not exist and not in list -- duh if (name != NULL) { if (strcmp (name,"*") == 0) { // check for * case silencePlayers.push_back(name); std::string message = "Silenced All Msgs"; addMessage(NULL, message); } else { std::string message = name; message += (" Does not exist"); addMessage(NULL, message); } } } } } } hud->setComposing(std::string()); HUDui::setDefaultKey(NULL); return true; } bool SilenceDefaultKey::keyRelease(const BzfKeyEvent& key) { LocalPlayer *myTank = LocalPlayer::getMyTank(); if (myTank->getInputMethod() != LocalPlayer::Keyboard) { if (key.button == BzfKeyEvent::Up || key.button==BzfKeyEvent::Down ||key.button==BzfKeyEvent::Left||key.button==BzfKeyEvent::Right) { // exclude robots from silence recipient list they don't talk selectNextRecipient(key.button == BzfKeyEvent::Up || key.button == BzfKeyEvent::Right, false); const Player *recipient = myTank->getRecipient(); if (recipient) { const std::string name = recipient->getCallSign(); bool isInList = false; for (unsigned int i = 0; i < silencePlayers.size(); i++) { if (silencePlayers[i] == name) { isInList = true; break; } } std::string composePrompt = "Silence -->"; if (isInList) composePrompt = "Un" + composePrompt; composePrompt += name; // Set the prompt and disable editing/composing hud->setComposing(composePrompt, false); } return false; } } return keyPress(key); } <commit_msg>Let silence work even without being in a game (was segv before)<commit_after>/* bzflag * Copyright (c) 1993 - 2005 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #include <string> #include "SilenceDefaultKey.h" #include "KeyManager.h" #include "LocalPlayer.h" #include "HUDRenderer.h" #include "Roster.h" #include "playing.h" // THIS IS TEMPORARY..TO BE REMOVED..BABY STEPS // // Choose person to silence SilenceDefaultKey::SilenceDefaultKey() { } bool SilenceDefaultKey::keyPress(const BzfKeyEvent& key) { bool sendIt; LocalPlayer *myTank = LocalPlayer::getMyTank(); if (myTank && KEYMGR.get(key, true) == "jump") { // jump while typing myTank->setJump(); } if (myTank && myTank->getInputMethod() != LocalPlayer::Keyboard) { if ((key.button == BzfKeyEvent::Up) || (key.button == BzfKeyEvent::Down) || (key.button == BzfKeyEvent::Left) || (key.button == BzfKeyEvent::Right)) return true; } switch (key.ascii) { case 3: // ^C case 27: // escape // case 127: // delete sendIt = false; // finished composing -- don't send break; case 4: // ^D case 13: // return sendIt = true; break; default: return false; } if (sendIt) { std::string message = hud->getComposeString(); // find the name of the person to silence, // either by picking through arrow keys or by compose const char* name = NULL; if (myTank && message.size() == 0) { // silence just by picking arrowkeys const Player * silenceMe = myTank->getRecipient(); if (silenceMe) { name = silenceMe->getCallSign(); } } else if (message.size() > 0) { // typed in name name = message.c_str(); } // if name is NULL we skip if (name != NULL) { // bad indent :) int inListPos = -1; for (unsigned int i = 0; i < silencePlayers.size(); i++) { if (strcmp(silencePlayers[i].c_str(),name) == 0) { inListPos = i; } } bool isInList = (inListPos != -1); Player *loudmouth = getPlayerByName(name); if (loudmouth) { // we know this person exists if (!isInList) { // exists and not in silence list silencePlayers.push_back(name); std::string message = "Silenced "; message += (name); addMessage(NULL, message); } else { // exists and in list --> remove from list silencePlayers.erase(silencePlayers.begin() + inListPos); std::string message = "Unsilenced "; message += (name); addMessage(NULL, message); } } else { // person does not exist, but may be in silence list if (isInList) { // does not exist but is in list --> remove silencePlayers.erase(silencePlayers.begin() + inListPos); std::string message = "Unsilenced "; message += (name); if (strcmp (name, "*") == 0) { // to make msg fancier message = "Unblocked Msgs"; } addMessage(NULL, message); } else { // does not exist and not in list -- duh if (name != NULL) { if (strcmp (name,"*") == 0) { // check for * case silencePlayers.push_back(name); std::string message = "Silenced All Msgs"; addMessage(NULL, message); } else { std::string message = name; message += (" Does not exist"); addMessage(NULL, message); } } } } } } hud->setComposing(std::string()); HUDui::setDefaultKey(NULL); return true; } bool SilenceDefaultKey::keyRelease(const BzfKeyEvent& key) { LocalPlayer *myTank = LocalPlayer::getMyTank(); if (!myTank) return false; if (myTank->getInputMethod() != LocalPlayer::Keyboard) { if (key.button == BzfKeyEvent::Up || key.button==BzfKeyEvent::Down ||key.button==BzfKeyEvent::Left||key.button==BzfKeyEvent::Right) { // exclude robots from silence recipient list they don't talk selectNextRecipient(key.button == BzfKeyEvent::Up || key.button == BzfKeyEvent::Right, false); const Player *recipient = myTank->getRecipient(); if (recipient) { const std::string name = recipient->getCallSign(); bool isInList = false; for (unsigned int i = 0; i < silencePlayers.size(); i++) { if (silencePlayers[i] == name) { isInList = true; break; } } std::string composePrompt = "Silence -->"; if (isInList) composePrompt = "Un" + composePrompt; composePrompt += name; // Set the prompt and disable editing/composing hud->setComposing(composePrompt, false); } return false; } } return keyPress(key); } <|endoftext|>
<commit_before>//===----------------------------------------------------------------------===// // // Peloton // // abstract_catalog.cpp // // Identification: src/catalog/abstract_catalog.cpp // // Copyright (c) 2015-17, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include "catalog/abstract_catalog.h" #include "catalog/catalog.h" #include "planner/create_plan.h" #include "optimizer/simple_optimizer.h" #include "parser/postgresparser.h" #include "common/statement.h" #include "planner/seq_scan_plan.h" #include "executor/seq_scan_executor.h" namespace peloton { namespace catalog { AbstractCatalog::AbstractCatalog(oid_t catalog_table_oid, std::string catalog_table_name, catalog::Schema *catalog_table_schema, storage::Database *pg_catalog) { // Create catalog_table_ catalog_table_ = storage::TableFactory::GetDataTable( CATALOG_DATABASE_OID, catalog_table_oid, catalog_table_schema, catalog_table_name, DEFAULT_TUPLES_PER_TILEGROUP, true, false, true); // Add catalog_table_ into pg_catalog database pg_catalog->AddTable(catalog_table_, true); } AbstractCatalog::AbstractCatalog(const std::string &catalog_table_ddl, concurrency::Transaction *txn) { // get catalog table schema auto &peloton_parser = parser::PostgresParser::GetInstance(); auto create_plan = std::dynamic_pointer_cast<planner::CreatePlan>( optimizer::SimpleOptimizer().BuildPelotonPlanTree( peloton_parser.BuildParseTree(catalog_table_ddl))); auto catalog_table_schema = create_plan->GetSchema(); auto catalog_table_name = create_plan->GetTableName(); // create catalog table Catalog::GetInstance()->CreateTable( CATALOG_DATABASE_NAME, catalog_table_name, std::unique_ptr<catalog::Schema>(catalog_table_schema), txn); // get catalog table oid oid_t catalog_table_oid = TableCatalog::GetInstance()->GetTableOid( catalog_table_name, CATALOG_DATABASE_OID, txn); // set catalog_table_ catalog_table_ = Catalog::GetInstance()->GetTableWithOid(CATALOG_DATABASE_OID, catalog_table_oid); } /*@brief insert tuple(reord) helper function * @param tuple tuple to be inserted * @param txn Transaction * @return Whether insertion is Successful */ bool AbstractCatalog::InsertTuple(std::unique_ptr<storage::Tuple> tuple, concurrency::Transaction *txn) { if (txn == nullptr) throw CatalogException("Insert tuple requires transaction"); std::unique_ptr<executor::ExecutorContext> context( new executor::ExecutorContext(txn)); planner::InsertPlan node(catalog_table_, std::move(tuple)); executor::InsertExecutor executor(&node, context.get()); executor.Init(); bool status = executor.Execute(); return status; } /*@brief Delete a tuple using index scan * @param index_offset Offset of index for scan * @param values Values for search * @param txn Transaction * @return Whether deletion is Successful */ bool AbstractCatalog::DeleteWithIndexScan(oid_t index_offset, std::vector<type::Value> values, concurrency::Transaction *txn) { if (txn == nullptr) throw CatalogException("Delete tuple requires transaction"); std::unique_ptr<executor::ExecutorContext> context( new executor::ExecutorContext(txn)); // Delete node planner::DeletePlan delete_node(catalog_table_, false); executor::DeleteExecutor delete_executor(&delete_node, context.get()); // Index scan as child node std::vector<oid_t> column_offsets; // No projection auto index = catalog_table_->GetIndex(index_offset); PL_ASSERT(index != nullptr); std::vector<oid_t> key_column_offsets = index->GetMetadata()->GetKeySchema()->GetIndexedColumns(); PL_ASSERT(values.size() == key_column_offsets.size()); std::vector<ExpressionType> expr_types(values.size(), ExpressionType::COMPARE_EQUAL); std::vector<expression::AbstractExpression *> runtime_keys; planner::IndexScanPlan::IndexScanDesc index_scan_desc( index, key_column_offsets, expr_types, values, runtime_keys); std::unique_ptr<planner::IndexScanPlan> index_scan_node( new planner::IndexScanPlan(catalog_table_, nullptr, column_offsets, index_scan_desc)); executor::IndexScanExecutor index_scan_executor(index_scan_node.get(), context.get()); // Parent-Child relationship delete_node.AddChild(std::move(index_scan_node)); delete_executor.AddChild(&index_scan_executor); delete_executor.Init(); bool status = delete_executor.Execute(); return status; } /*@brief Index scan helper function * @param column_offsets Column ids for search (projection) * @param index_offset Offset of index for scan * @param values Values for search * @param txn Transaction * @return Unique pointer of vector of logical tiles */ std::unique_ptr<std::vector<std::unique_ptr<executor::LogicalTile>>> AbstractCatalog::GetResultWithIndexScan(std::vector<oid_t> column_offsets, oid_t index_offset, std::vector<type::Value> values, concurrency::Transaction *txn) { if (txn == nullptr) throw CatalogException("Scan table requires transaction"); // Index scan std::unique_ptr<executor::ExecutorContext> context( new executor::ExecutorContext(txn)); auto index = catalog_table_->GetIndex(index_offset); std::vector<oid_t> key_column_offsets = index->GetMetadata()->GetKeySchema()->GetIndexedColumns(); PL_ASSERT(values.size() == key_column_offsets.size()); std::vector<ExpressionType> expr_types(values.size(), ExpressionType::COMPARE_EQUAL); std::vector<expression::AbstractExpression *> runtime_keys; planner::IndexScanPlan::IndexScanDesc index_scan_desc( index, key_column_offsets, expr_types, values, runtime_keys); planner::IndexScanPlan index_scan_node(catalog_table_, nullptr, column_offsets, index_scan_desc); executor::IndexScanExecutor index_scan_executor(&index_scan_node, context.get()); // Execute index_scan_executor.Init(); std::unique_ptr<std::vector<std::unique_ptr<executor::LogicalTile>>> result_tiles(new std::vector<std::unique_ptr<executor::LogicalTile>>()); while (index_scan_executor.Execute()) { result_tiles->push_back(std::unique_ptr<executor::LogicalTile>( index_scan_executor.GetOutput())); } return result_tiles; } /*@brief Sequential scan helper function * NOTE: try to use efficient index scan instead of sequential scan, but you * shouldn't build too many indexes on one catalog table * @param column_offsets Column ids for search (projection) * @param predicate predicate for this sequential scan query * @param txn Transaction * * @return Unique pointer of vector of logical tiles */ std::unique_ptr<std::vector<std::unique_ptr<executor::LogicalTile>>> AbstractCatalog::GetResultWithSeqScan(std::vector<oid_t> column_offsets, expression::AbstractExpression *predicate, concurrency::Transaction *txn) { if (txn == nullptr) throw CatalogException("Scan table requires transaction"); // Sequential scan std::unique_ptr<executor::ExecutorContext> context( new executor::ExecutorContext(txn)); planner::SeqScanPlan seq_scan_node(catalog_table_, predicate, column_offsets); executor::SeqScanExecutor seq_scan_executor(&seq_scan_node, context.get()); // Execute seq_scan_executor.Init(); std::unique_ptr<std::vector<std::unique_ptr<executor::LogicalTile>>> result_tiles(new std::vector<std::unique_ptr<executor::LogicalTile>>()); while (seq_scan_executor.Execute()) { result_tiles->push_back( std::unique_ptr<executor::LogicalTile>(seq_scan_executor.GetOutput())); } return result_tiles; } /*@brief Add index on catalog table * @param key_attrs indexed column offset(position) * @param index_oid index id(global unique) * @param index_name index name(global unique) * @param index_constraint index constraints * @return Unique pointer of vector of logical tiles * Note: Use catalog::Catalog::CreateIndex() if you can, only ColumnCatalog and * IndexCatalog should need this */ void AbstractCatalog::AddIndex(const std::vector<oid_t> &key_attrs, oid_t index_oid, const std::string &index_name, IndexConstraintType index_constraint) { auto schema = catalog_table_->GetSchema(); auto key_schema = catalog::Schema::CopySchema(schema, key_attrs); key_schema->SetIndexedColumns(key_attrs); bool unique_keys = (index_constraint == IndexConstraintType::PRIMARY_KEY) || (index_constraint == IndexConstraintType::UNIQUE); auto index_metadata = new index::IndexMetadata( index_name, index_oid, catalog_table_->GetOid(), CATALOG_DATABASE_OID, IndexType::BWTREE, index_constraint, schema, key_schema, key_attrs, unique_keys); std::shared_ptr<index::Index> key_index( index::IndexFactory::GetIndex(index_metadata)); catalog_table_->AddIndex(key_index); // If you called AddIndex(), you need to insert the index record by yourself! // insert index record into index_catalog(pg_index) table // IndexCatalog::GetInstance()->InsertIndex( // index_oid, index_name, COLUMN_CATALOG_OID, IndexType::BWTREE, // index_constraint, unique_keys, pool_.get(), nullptr); LOG_TRACE("Successfully created index '%s' for table '%d'", index_name.c_str(), (int)catalog_table_->GetOid()); } } // End catalog namespace } // End peloton namespace <commit_msg>is_catalog in abstract catalog<commit_after>//===----------------------------------------------------------------------===// // // Peloton // // abstract_catalog.cpp // // Identification: src/catalog/abstract_catalog.cpp // // Copyright (c) 2015-17, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include "catalog/abstract_catalog.h" #include "catalog/catalog.h" #include "planner/create_plan.h" #include "optimizer/simple_optimizer.h" #include "parser/postgresparser.h" #include "common/statement.h" #include "planner/seq_scan_plan.h" #include "executor/seq_scan_executor.h" namespace peloton { namespace catalog { AbstractCatalog::AbstractCatalog(oid_t catalog_table_oid, std::string catalog_table_name, catalog::Schema *catalog_table_schema, storage::Database *pg_catalog) { // Create catalog_table_ catalog_table_ = storage::TableFactory::GetDataTable( CATALOG_DATABASE_OID, catalog_table_oid, catalog_table_schema, catalog_table_name, DEFAULT_TUPLES_PER_TILEGROUP, true, false, true); // Add catalog_table_ into pg_catalog database pg_catalog->AddTable(catalog_table_, true); } AbstractCatalog::AbstractCatalog(const std::string &catalog_table_ddl, concurrency::Transaction *txn) { // get catalog table schema auto &peloton_parser = parser::PostgresParser::GetInstance(); auto create_plan = std::dynamic_pointer_cast<planner::CreatePlan>( optimizer::SimpleOptimizer().BuildPelotonPlanTree( peloton_parser.BuildParseTree(catalog_table_ddl))); auto catalog_table_schema = create_plan->GetSchema(); auto catalog_table_name = create_plan->GetTableName(); // create catalog table Catalog::GetInstance()->CreateTable( CATALOG_DATABASE_NAME, catalog_table_name, std::unique_ptr<catalog::Schema>(catalog_table_schema), txn, true); // get catalog table oid oid_t catalog_table_oid = TableCatalog::GetInstance()->GetTableOid( catalog_table_name, CATALOG_DATABASE_OID, txn); // set catalog_table_ catalog_table_ = Catalog::GetInstance()->GetTableWithOid(CATALOG_DATABASE_OID, catalog_table_oid); } /*@brief insert tuple(reord) helper function * @param tuple tuple to be inserted * @param txn Transaction * @return Whether insertion is Successful */ bool AbstractCatalog::InsertTuple(std::unique_ptr<storage::Tuple> tuple, concurrency::Transaction *txn) { if (txn == nullptr) throw CatalogException("Insert tuple requires transaction"); std::unique_ptr<executor::ExecutorContext> context( new executor::ExecutorContext(txn)); planner::InsertPlan node(catalog_table_, std::move(tuple)); executor::InsertExecutor executor(&node, context.get()); executor.Init(); bool status = executor.Execute(); return status; } /*@brief Delete a tuple using index scan * @param index_offset Offset of index for scan * @param values Values for search * @param txn Transaction * @return Whether deletion is Successful */ bool AbstractCatalog::DeleteWithIndexScan(oid_t index_offset, std::vector<type::Value> values, concurrency::Transaction *txn) { if (txn == nullptr) throw CatalogException("Delete tuple requires transaction"); std::unique_ptr<executor::ExecutorContext> context( new executor::ExecutorContext(txn)); // Delete node planner::DeletePlan delete_node(catalog_table_, false); executor::DeleteExecutor delete_executor(&delete_node, context.get()); // Index scan as child node std::vector<oid_t> column_offsets; // No projection auto index = catalog_table_->GetIndex(index_offset); PL_ASSERT(index != nullptr); std::vector<oid_t> key_column_offsets = index->GetMetadata()->GetKeySchema()->GetIndexedColumns(); PL_ASSERT(values.size() == key_column_offsets.size()); std::vector<ExpressionType> expr_types(values.size(), ExpressionType::COMPARE_EQUAL); std::vector<expression::AbstractExpression *> runtime_keys; planner::IndexScanPlan::IndexScanDesc index_scan_desc( index, key_column_offsets, expr_types, values, runtime_keys); std::unique_ptr<planner::IndexScanPlan> index_scan_node( new planner::IndexScanPlan(catalog_table_, nullptr, column_offsets, index_scan_desc)); executor::IndexScanExecutor index_scan_executor(index_scan_node.get(), context.get()); // Parent-Child relationship delete_node.AddChild(std::move(index_scan_node)); delete_executor.AddChild(&index_scan_executor); delete_executor.Init(); bool status = delete_executor.Execute(); return status; } /*@brief Index scan helper function * @param column_offsets Column ids for search (projection) * @param index_offset Offset of index for scan * @param values Values for search * @param txn Transaction * @return Unique pointer of vector of logical tiles */ std::unique_ptr<std::vector<std::unique_ptr<executor::LogicalTile>>> AbstractCatalog::GetResultWithIndexScan(std::vector<oid_t> column_offsets, oid_t index_offset, std::vector<type::Value> values, concurrency::Transaction *txn) { if (txn == nullptr) throw CatalogException("Scan table requires transaction"); // Index scan std::unique_ptr<executor::ExecutorContext> context( new executor::ExecutorContext(txn)); auto index = catalog_table_->GetIndex(index_offset); std::vector<oid_t> key_column_offsets = index->GetMetadata()->GetKeySchema()->GetIndexedColumns(); PL_ASSERT(values.size() == key_column_offsets.size()); std::vector<ExpressionType> expr_types(values.size(), ExpressionType::COMPARE_EQUAL); std::vector<expression::AbstractExpression *> runtime_keys; planner::IndexScanPlan::IndexScanDesc index_scan_desc( index, key_column_offsets, expr_types, values, runtime_keys); planner::IndexScanPlan index_scan_node(catalog_table_, nullptr, column_offsets, index_scan_desc); executor::IndexScanExecutor index_scan_executor(&index_scan_node, context.get()); // Execute index_scan_executor.Init(); std::unique_ptr<std::vector<std::unique_ptr<executor::LogicalTile>>> result_tiles(new std::vector<std::unique_ptr<executor::LogicalTile>>()); while (index_scan_executor.Execute()) { result_tiles->push_back(std::unique_ptr<executor::LogicalTile>( index_scan_executor.GetOutput())); } return result_tiles; } /*@brief Sequential scan helper function * NOTE: try to use efficient index scan instead of sequential scan, but you * shouldn't build too many indexes on one catalog table * @param column_offsets Column ids for search (projection) * @param predicate predicate for this sequential scan query * @param txn Transaction * * @return Unique pointer of vector of logical tiles */ std::unique_ptr<std::vector<std::unique_ptr<executor::LogicalTile>>> AbstractCatalog::GetResultWithSeqScan(std::vector<oid_t> column_offsets, expression::AbstractExpression *predicate, concurrency::Transaction *txn) { if (txn == nullptr) throw CatalogException("Scan table requires transaction"); // Sequential scan std::unique_ptr<executor::ExecutorContext> context( new executor::ExecutorContext(txn)); planner::SeqScanPlan seq_scan_node(catalog_table_, predicate, column_offsets); executor::SeqScanExecutor seq_scan_executor(&seq_scan_node, context.get()); // Execute seq_scan_executor.Init(); std::unique_ptr<std::vector<std::unique_ptr<executor::LogicalTile>>> result_tiles(new std::vector<std::unique_ptr<executor::LogicalTile>>()); while (seq_scan_executor.Execute()) { result_tiles->push_back( std::unique_ptr<executor::LogicalTile>(seq_scan_executor.GetOutput())); } return result_tiles; } /*@brief Add index on catalog table * @param key_attrs indexed column offset(position) * @param index_oid index id(global unique) * @param index_name index name(global unique) * @param index_constraint index constraints * @return Unique pointer of vector of logical tiles * Note: Use catalog::Catalog::CreateIndex() if you can, only ColumnCatalog and * IndexCatalog should need this */ void AbstractCatalog::AddIndex(const std::vector<oid_t> &key_attrs, oid_t index_oid, const std::string &index_name, IndexConstraintType index_constraint) { auto schema = catalog_table_->GetSchema(); auto key_schema = catalog::Schema::CopySchema(schema, key_attrs); key_schema->SetIndexedColumns(key_attrs); bool unique_keys = (index_constraint == IndexConstraintType::PRIMARY_KEY) || (index_constraint == IndexConstraintType::UNIQUE); auto index_metadata = new index::IndexMetadata( index_name, index_oid, catalog_table_->GetOid(), CATALOG_DATABASE_OID, IndexType::BWTREE, index_constraint, schema, key_schema, key_attrs, unique_keys); std::shared_ptr<index::Index> key_index( index::IndexFactory::GetIndex(index_metadata)); catalog_table_->AddIndex(key_index); // If you called AddIndex(), you need to insert the index record by yourself! // insert index record into index_catalog(pg_index) table // IndexCatalog::GetInstance()->InsertIndex( // index_oid, index_name, COLUMN_CATALOG_OID, IndexType::BWTREE, // index_constraint, unique_keys, pool_.get(), nullptr); LOG_TRACE("Successfully created index '%s' for table '%d'", index_name.c_str(), (int)catalog_table_->GetOid()); } } // End catalog namespace } // End peloton namespace <|endoftext|>
<commit_before>/* Copyright © 2001-2014, Canal TP and/or its affiliates. All rights reserved. This file is part of Navitia, the software to build cool stuff with public transport. Hope you'll enjoy and contribute to this project, powered by Canal TP (www.canaltp.fr). Help us simplify mobility and open public transport: a non ending quest to the responsive locomotion way of traveling! LICENCE: 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/>. Stay tuned using twitter @navitia IRC #navitia on freenode https://groups.google.com/d/forum/navitia www.navitia.io */ #include "route_schedules.h" #include "thermometer.h" #include "request_handle.h" #include "type/pb_converter.h" #include "ptreferential/ptreferential.h" #include "utils/paginate.h" #include "type/datetime.h" #include "routing/best_stoptime.h" #include <boost/range/adaptor/reversed.hpp> namespace pt = boost::posix_time; namespace navitia { namespace timetables { std::vector<std::vector<datetime_stop_time> > get_all_stop_times(const vector_idx &journey_patterns, const DateTime &dateTime, const DateTime &max_datetime, const type::Data &d, bool disruption_active) { std::vector<std::vector<datetime_stop_time> > result; //On cherche les premiers journey_pattern_points //de tous les journey_patterns std::vector<type::idx_t> first_journey_pattern_points; for(type::idx_t jp_idx : journey_patterns) { auto jpp = d.pt_data->journey_patterns[jp_idx]; auto first_jpp_idx = jpp->journey_pattern_point_list.front()->idx; first_journey_pattern_points.push_back(first_jpp_idx); } //On fait un best_stop_time sur ces journey_pattern points auto first_dt_st = get_stop_times(first_journey_pattern_points, dateTime, max_datetime, std::numeric_limits<int>::max(), d, disruption_active); //On va chercher tous les prochains horaires for(auto ho : first_dt_st) { result.push_back(std::vector<datetime_stop_time>()); DateTime dt = ho.first; for(const type::StopTime* stop_time : ho.second->vehicle_journey->stop_time_list) { if(!stop_time->is_frequency()) { DateTimeUtils::update(dt, stop_time->departure_time); } else { DateTimeUtils::update(dt, routing::f_departure_time(dt, stop_time)); } result.back().push_back(std::make_pair(dt, stop_time)); } } return result; } std::vector<datetime_stop_time>::const_iterator get_first_dt_st_after( const std::vector<datetime_stop_time>& v, size_t order) { if (order < v.size()) { return std::find_if(v.begin() + order, v.end(), [](datetime_stop_time dt_st) { return dt_st.second != nullptr; }); } return v.end(); } std::vector<datetime_stop_time>::const_iterator get_first_dt_st_before( const std::vector<datetime_stop_time>& v, size_t order) { if (order < v.size()) { for (auto it = v.rbegin()+order; it != v.rend(); ++ it) { if (it->second != nullptr) { return it.base() - 1; } } } return v.end(); } /* * We want to compare the first filled dt_st of v1, named d1 with order o1 * with the first filled dt_st of v2 having an order >= o1 * If cannot find such an element in v2, we will compare with the last filled * dt_st in v2. * We want to compare v2, with the first st in v1 before o2. */ bool compare(const std::vector<datetime_stop_time>& v1, const std::vector<datetime_stop_time>& v2) { if (v1.empty()) { return false; } if (v2.empty()) { return true; } auto first_st_a_it = get_first_dt_st_after(v1, 0); if (first_st_a_it == v1.end()) { return false; } auto first_st_b_it = v2.end(); size_t order = std::distance(first_st_a_it, v1.begin()); if (order < v2.size()) { first_st_b_it = get_first_dt_st_after(v2, order); } if (first_st_b_it == v2.end()) { first_st_b_it = get_first_dt_st_before(v2, 0); if (first_st_b_it == v2.end()) { return true; } } auto r_first_st_b_it = std::reverse_iterator<std::vector<datetime_stop_time>::const_iterator>(first_st_b_it); size_t distance = std::distance(v2.rbegin(), r_first_st_b_it); // Even if r_first_st_b_it == v2.rbegin(), distance will be 1... So we need to decrease it. --distance; first_st_a_it = get_first_dt_st_before(v1, distance); return first_st_a_it->first < first_st_b_it->first; } std::vector<std::vector<datetime_stop_time> > make_matrice(const std::vector<std::vector<datetime_stop_time> >& stop_times, const Thermometer &thermometer, const type::Data &) { // result group stop_times by stop_point, tmp by vj. std::vector<std::vector<datetime_stop_time> > result, tmp; const size_t thermometer_size = thermometer.get_thermometer().size(); for (size_t i=0; i < stop_times.size(); ++i) { tmp.push_back(std::vector<datetime_stop_time>(thermometer_size)); } // We match every stop_time with the journey pattern int y=0; for(std::vector<datetime_stop_time> vec : stop_times) { auto jpp = *vec.front().second->vehicle_journey->journey_pattern; std::vector<uint32_t> orders = thermometer.match_journey_pattern(jpp); int order = 0; for(datetime_stop_time dt_stop_time : vec) { tmp[y][orders[order]] = dt_stop_time; ++order; } ++y; } std::sort(tmp.begin(), tmp.end(), compare); for(unsigned int i=0; i<thermometer_size; ++i) { result.push_back(std::vector<datetime_stop_time>()); result.back().resize(stop_times.size()); } // We rotate the matrice, so it can be handle more easily in route_schedule for (size_t i=0; i<tmp.size(); ++i) { for (size_t j=0; j<tmp[i].size(); ++j) { result[j][i] = tmp[i][j]; } } return result; } pbnavitia::Response route_schedule(const std::string& filter, const std::vector<std::string>& forbidden_uris, const pt::ptime datetime, uint32_t duration, uint32_t interface_version, const uint32_t max_depth, int count, int start_page, const type::Data &d, bool disruption_active, const bool show_codes) { RequestHandle handler("ROUTE_SCHEDULE", filter, forbidden_uris, datetime, duration, d, {}); if(handler.pb_response.has_error()) { return handler.pb_response; } auto now = pt::second_clock::local_time(); auto pt_datetime = to_posix_time(handler.date_time, d); auto pt_max_datetime = to_posix_time(handler.max_datetime, d); pt::time_period action_period(pt_datetime, pt_max_datetime); Thermometer thermometer; auto routes_idx = ptref::make_query(type::Type_e::Route, filter, forbidden_uris, d); size_t total_result = routes_idx.size(); routes_idx = paginate(routes_idx, count, start_page); for(type::idx_t route_idx : routes_idx) { auto route = d.pt_data->routes[route_idx]; auto jps = ptref::make_query(type::Type_e::JourneyPattern, filter+" and route.uri="+route->uri, forbidden_uris, d); //On récupère les stop_times auto stop_times = get_all_stop_times(jps, handler.date_time, handler.max_datetime, d, disruption_active); std::vector<vector_idx> stop_points; for(auto jp_idx : jps) { auto jp = d.pt_data->journey_patterns[jp_idx]; stop_points.push_back(vector_idx()); for(auto jpp : jp->journey_pattern_point_list) { stop_points.back().push_back(jpp->stop_point->idx); } } thermometer.generate_thermometer(stop_points); //On génère la matrice auto matrice = make_matrice(stop_times, thermometer, d); auto schedule = handler.pb_response.add_route_schedules(); pbnavitia::Table *table = schedule->mutable_table(); auto m_pt_display_informations = schedule->mutable_pt_display_informations(); fill_pb_object(route, d, m_pt_display_informations, 0, now, action_period); std::vector<bool> is_vj_set(stop_times.size(), false); for(unsigned int i=0; i < thermometer.get_thermometer().size(); ++i) { type::idx_t spidx=thermometer.get_thermometer()[i]; const type::StopPoint* sp = d.pt_data->stop_points[spidx]; //version v1 pbnavitia::RouteScheduleRow* row = table->add_rows(); fill_pb_object(sp, d, row->mutable_stop_point(), max_depth, now, action_period, show_codes); for(unsigned int j=0; j<stop_times.size(); ++j) { datetime_stop_time dt_stop_time = matrice[i][j]; if (!is_vj_set[j] && dt_stop_time.second != nullptr) { pbnavitia::Header* header = table->add_headers(); pbnavitia::PtDisplayInfo* vj_display_information = header->mutable_pt_display_informations(); pbnavitia::addInfoVehicleJourney* add_info_vehicle_journey = header->mutable_add_info_vehicle_journey(); auto vj = dt_stop_time.second->vehicle_journey; fill_pb_object(vj, d, vj_display_information, 0, now, action_period); fill_pb_object(vj, d, {}, add_info_vehicle_journey, 0, now, action_period); is_vj_set[j] = true; } if(interface_version == 1) { auto pb_dt = row->add_date_times(); fill_pb_object(dt_stop_time.second, d, pb_dt, max_depth, now, action_period, dt_stop_time.first); } else if(interface_version == 0) { row->add_stop_times(navitia::iso_string(dt_stop_time.first, d)); } } } fill_pb_object(route->shape, schedule->mutable_geojson()); } auto pagination = handler.pb_response.mutable_pagination(); pagination->set_totalresult(total_result); pagination->set_startpage(start_page); pagination->set_itemsperpage(count); pagination->set_itemsonpage(handler.pb_response.route_schedules_size()); return handler.pb_response; } }} <commit_msg>Kraken: use of const ref<commit_after>/* Copyright © 2001-2014, Canal TP and/or its affiliates. All rights reserved. This file is part of Navitia, the software to build cool stuff with public transport. Hope you'll enjoy and contribute to this project, powered by Canal TP (www.canaltp.fr). Help us simplify mobility and open public transport: a non ending quest to the responsive locomotion way of traveling! LICENCE: 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/>. Stay tuned using twitter @navitia IRC #navitia on freenode https://groups.google.com/d/forum/navitia www.navitia.io */ #include "route_schedules.h" #include "thermometer.h" #include "request_handle.h" #include "type/pb_converter.h" #include "ptreferential/ptreferential.h" #include "utils/paginate.h" #include "type/datetime.h" #include "routing/best_stoptime.h" #include <boost/range/adaptor/reversed.hpp> namespace pt = boost::posix_time; namespace navitia { namespace timetables { std::vector<std::vector<datetime_stop_time> > get_all_stop_times(const vector_idx &journey_patterns, const DateTime &dateTime, const DateTime &max_datetime, const type::Data &d, bool disruption_active) { std::vector<std::vector<datetime_stop_time> > result; //On cherche les premiers journey_pattern_points //de tous les journey_patterns std::vector<type::idx_t> first_journey_pattern_points; for(type::idx_t jp_idx : journey_patterns) { auto jpp = d.pt_data->journey_patterns[jp_idx]; auto first_jpp_idx = jpp->journey_pattern_point_list.front()->idx; first_journey_pattern_points.push_back(first_jpp_idx); } //On fait un best_stop_time sur ces journey_pattern points auto first_dt_st = get_stop_times(first_journey_pattern_points, dateTime, max_datetime, std::numeric_limits<int>::max(), d, disruption_active); //On va chercher tous les prochains horaires for(auto ho : first_dt_st) { result.push_back(std::vector<datetime_stop_time>()); DateTime dt = ho.first; for(const type::StopTime* stop_time : ho.second->vehicle_journey->stop_time_list) { if(!stop_time->is_frequency()) { DateTimeUtils::update(dt, stop_time->departure_time); } else { DateTimeUtils::update(dt, routing::f_departure_time(dt, stop_time)); } result.back().push_back(std::make_pair(dt, stop_time)); } } return result; } std::vector<datetime_stop_time>::const_iterator get_first_dt_st_after( const std::vector<datetime_stop_time>& v, size_t order) { if (order < v.size()) { return std::find_if(v.begin() + order, v.end(), [](datetime_stop_time dt_st) { return dt_st.second != nullptr; }); } return v.end(); } std::vector<datetime_stop_time>::const_iterator get_first_dt_st_before( const std::vector<datetime_stop_time>& v, size_t order) { if (order < v.size()) { for (auto it = v.rbegin()+order; it != v.rend(); ++ it) { if (it->second != nullptr) { return it.base() - 1; } } } return v.end(); } /* * We want to compare the first filled dt_st of v1, named d1 with order o1 * with the first filled dt_st of v2 having an order >= o1 * If cannot find such an element in v2, we will compare with the last filled * dt_st in v2. * We want to compare v2, with the first st in v1 before o2. */ bool compare(const std::vector<datetime_stop_time>& v1, const std::vector<datetime_stop_time>& v2) { if (v1.empty()) { return false; } if (v2.empty()) { return true; } auto first_st_a_it = get_first_dt_st_after(v1, 0); if (first_st_a_it == v1.end()) { return false; } auto first_st_b_it = v2.end(); size_t order = std::distance(first_st_a_it, v1.begin()); if (order < v2.size()) { first_st_b_it = get_first_dt_st_after(v2, order); } if (first_st_b_it == v2.end()) { first_st_b_it = get_first_dt_st_before(v2, 0); if (first_st_b_it == v2.end()) { return true; } } auto r_first_st_b_it = std::reverse_iterator<std::vector<datetime_stop_time>::const_iterator>(first_st_b_it); size_t distance = std::distance(v2.rbegin(), r_first_st_b_it); // Even if r_first_st_b_it == v2.rbegin(), distance will be 1... So we need to decrease it. --distance; first_st_a_it = get_first_dt_st_before(v1, distance); return first_st_a_it->first < first_st_b_it->first; } std::vector<std::vector<datetime_stop_time> > make_matrice(const std::vector<std::vector<datetime_stop_time> >& stop_times, const Thermometer &thermometer, const type::Data &) { // result group stop_times by stop_point, tmp by vj. std::vector<std::vector<datetime_stop_time> > result, tmp; const size_t thermometer_size = thermometer.get_thermometer().size(); for (size_t i=0; i < stop_times.size(); ++i) { tmp.push_back(std::vector<datetime_stop_time>(thermometer_size)); } // We match every stop_time with the journey pattern int y=0; for(const std::vector<datetime_stop_time>& vec : stop_times) { auto jpp = *vec.front().second->vehicle_journey->journey_pattern; std::vector<uint32_t> orders = thermometer.match_journey_pattern(jpp); int order = 0; for(datetime_stop_time dt_stop_time : vec) { tmp[y][orders[order]] = dt_stop_time; ++order; } ++y; } std::sort(tmp.begin(), tmp.end(), compare); for(unsigned int i=0; i<thermometer_size; ++i) { result.push_back(std::vector<datetime_stop_time>()); result.back().resize(stop_times.size()); } // We rotate the matrice, so it can be handle more easily in route_schedule for (size_t i=0; i<tmp.size(); ++i) { for (size_t j=0; j<tmp[i].size(); ++j) { result[j][i] = tmp[i][j]; } } return result; } pbnavitia::Response route_schedule(const std::string& filter, const std::vector<std::string>& forbidden_uris, const pt::ptime datetime, uint32_t duration, uint32_t interface_version, const uint32_t max_depth, int count, int start_page, const type::Data &d, bool disruption_active, const bool show_codes) { RequestHandle handler("ROUTE_SCHEDULE", filter, forbidden_uris, datetime, duration, d, {}); if(handler.pb_response.has_error()) { return handler.pb_response; } auto now = pt::second_clock::local_time(); auto pt_datetime = to_posix_time(handler.date_time, d); auto pt_max_datetime = to_posix_time(handler.max_datetime, d); pt::time_period action_period(pt_datetime, pt_max_datetime); Thermometer thermometer; auto routes_idx = ptref::make_query(type::Type_e::Route, filter, forbidden_uris, d); size_t total_result = routes_idx.size(); routes_idx = paginate(routes_idx, count, start_page); for(type::idx_t route_idx : routes_idx) { auto route = d.pt_data->routes[route_idx]; auto jps = ptref::make_query(type::Type_e::JourneyPattern, filter+" and route.uri="+route->uri, forbidden_uris, d); //On récupère les stop_times auto stop_times = get_all_stop_times(jps, handler.date_time, handler.max_datetime, d, disruption_active); std::vector<vector_idx> stop_points; for(auto jp_idx : jps) { auto jp = d.pt_data->journey_patterns[jp_idx]; stop_points.push_back(vector_idx()); for(auto jpp : jp->journey_pattern_point_list) { stop_points.back().push_back(jpp->stop_point->idx); } } thermometer.generate_thermometer(stop_points); //On génère la matrice auto matrice = make_matrice(stop_times, thermometer, d); auto schedule = handler.pb_response.add_route_schedules(); pbnavitia::Table *table = schedule->mutable_table(); auto m_pt_display_informations = schedule->mutable_pt_display_informations(); fill_pb_object(route, d, m_pt_display_informations, 0, now, action_period); std::vector<bool> is_vj_set(stop_times.size(), false); for(unsigned int i=0; i < thermometer.get_thermometer().size(); ++i) { type::idx_t spidx=thermometer.get_thermometer()[i]; const type::StopPoint* sp = d.pt_data->stop_points[spidx]; //version v1 pbnavitia::RouteScheduleRow* row = table->add_rows(); fill_pb_object(sp, d, row->mutable_stop_point(), max_depth, now, action_period, show_codes); for(unsigned int j=0; j<stop_times.size(); ++j) { datetime_stop_time dt_stop_time = matrice[i][j]; if (!is_vj_set[j] && dt_stop_time.second != nullptr) { pbnavitia::Header* header = table->add_headers(); pbnavitia::PtDisplayInfo* vj_display_information = header->mutable_pt_display_informations(); pbnavitia::addInfoVehicleJourney* add_info_vehicle_journey = header->mutable_add_info_vehicle_journey(); auto vj = dt_stop_time.second->vehicle_journey; fill_pb_object(vj, d, vj_display_information, 0, now, action_period); fill_pb_object(vj, d, {}, add_info_vehicle_journey, 0, now, action_period); is_vj_set[j] = true; } if(interface_version == 1) { auto pb_dt = row->add_date_times(); fill_pb_object(dt_stop_time.second, d, pb_dt, max_depth, now, action_period, dt_stop_time.first); } else if(interface_version == 0) { row->add_stop_times(navitia::iso_string(dt_stop_time.first, d)); } } } fill_pb_object(route->shape, schedule->mutable_geojson()); } auto pagination = handler.pb_response.mutable_pagination(); pagination->set_totalresult(total_result); pagination->set_startpage(start_page); pagination->set_itemsperpage(count); pagination->set_itemsonpage(handler.pb_response.route_schedules_size()); return handler.pb_response; } }} <|endoftext|>
<commit_before>#include "navigation/walk_to_ball_server.hpp" WalkToBallAction::WalkToBallAction(std::string name) : as_(nh_, name, boost::bind(&WalkToBallAction::executeCB, this, _1), false), action_name_(name) { // as_.registerGoalCallback(boost::bind(&WalkToBallAction::goalCB, this)); ball_pos_sub_ = nh_.subscribe("/vision/ball_targ_pos", 1, &WalkToBallAction::goalCB, this); get_pose_client_ = nh_.serviceClient<motion_msgs::GetRobotPosition>( "/motion/get_robot_position", true); get_pose_client_.waitForExistence(); move_toward_client_ = nh_.serviceClient<motion_msgs::MoveToward>( "/motion/move_toward", true); move_toward_client_.waitForExistence(); stop_move_client_ = nh_.serviceClient<std_srvs::Empty>( "/motion/stop_move", true); stop_move_client_.waitForExistence(); move_init_client_ = nh_.serviceClient<std_srvs::Empty>( "/motion/move_init", true); move_init_client_.waitForExistence(); start_position_.request.use_sensors = true; get_pose_srv_.request.use_sensors = true; ROS_INFO("Starting WalkToBall server"); target_distance = 0.0f; target_theta = 0.0f; theta_scalar = 1.0f; dist_scalar = 3.0f; theta_thresh = 0.2f; dist_thresh = 0.05f; as_.start(); } WalkToBallAction::~WalkToBallAction(void) { } void WalkToBallAction::goalCB(const vision_msgs::BallDetection::ConstPtr& msg) { ROS_INFO("New Goal Received"); target_distance = msg->pos_robot.x; target_theta = msg->pos_robot.z; } void WalkToBallAction::executeCB( const navigation_msgs::WalkToBallGoalConstPtr& goal) { bool going = true; bool success = true; ROS_INFO("Executing goal for %s", action_name_.c_str()); get_pose_client_.call(start_position_); if (target_distance == 0.0f && target_theta == 0.0f) { target_distance = goal->ball_pose.x; target_theta = goal->ball_pose.theta; ROS_ERROR("Ball position not available, using agent goal %f, %f", target_distance, target_theta); } // ROTATE FIRST, THEN STRAIGHT TO GOAL // move_toward_srv_.request.control_points.resize(2); // move_toward_srv_.request.control_points[0].x = 0.0f; // move_toward_srv_.request.control_points[0].y = 0.0f; // move_toward_srv_.request.control_points[0].theta = goal->target_pose.theta; // move_toward_srv_.request.control_points[1].x = goal->target_pose.x; // move_toward_srv_.request.control_points[1].y = 0.0f; // move_toward_srv_.request.control_points[1].theta = 0.0f; // move_toward_client_.call(move_toward_srv_); while (going == true) { if (as_.isPreemptRequested() || !ros::ok()) { ROS_INFO("%s: Preempted", action_name_.c_str()); as_.setPreempted(); success = false; going = false; } get_pose_client_.call(get_pose_srv_); feedback_.curr_pose.x = get_pose_srv_.response.position.x - start_position_.response.position.x; feedback_.curr_pose.y = get_pose_srv_.response.position.y - start_position_.response.position.y; feedback_.curr_pose.theta = get_pose_srv_.response.position.theta - start_position_.response.position.theta; as_.publishFeedback(feedback_); ROS_INFO("Current pos: %f, %f, %f", feedback_.curr_pose.x, feedback_.curr_pose.y, feedback_.curr_pose.theta); ROS_INFO("Target dis: %f, Target theta %f", target_distance, target_theta); float distance = sqrt(pow(feedback_.curr_pose.x, 2) + pow(feedback_.curr_pose.y, 2) ); // float distance_error = target_distance - distance; // Absolute // float theta_error = target_theta - feedback_.curr_pose.theta; // Absolute float distance_error = target_distance; // Relative float theta_error = target_theta; // Relative ROS_INFO("Distance_error: %f, Theta error: %f", distance_error, theta_error); // ROTATE FIRST, THEN STRAIGHT TO GOAL move_toward_srv_.request.norm_velocity.x = 0.0f; move_toward_srv_.request.norm_velocity.theta = 0.0f; if (fabs(theta_error) > theta_thresh) { if (theta_error < 0) { ROS_INFO("Right"); } else { ROS_INFO("Left"); } float theta_vel = theta_error * theta_scalar; if (theta_vel < -1.0) {theta_vel = -1.0;} else if (theta_vel > 1.0) {theta_vel = 1.0;} move_toward_srv_.request.norm_velocity.theta = theta_vel; ROS_INFO("Rot. Speed: %f", move_toward_srv_.request.norm_velocity.theta); move_toward_client_.call(move_toward_srv_); } else if (fabs(distance_error) > dist_thresh) { if (distance_error > 0) { ROS_INFO("Forward"); } float forw_vel = distance_error * dist_scalar; if (forw_vel < -1.0) {forw_vel = -1.0;} else if (forw_vel > 1.0) {forw_vel = 1.0;} move_toward_srv_.request.norm_velocity.x = forw_vel; ROS_INFO("Dist. Speed: %f", move_toward_srv_.request.norm_velocity.x); move_toward_client_.call(move_toward_srv_); } if ((fabs(distance_error) < dist_thresh) && (fabs(theta_error) < theta_thresh)) { ROS_INFO("%s: Arrived", action_name_.c_str()); going = false; } } stop_move_client_.call(stop_move_srv_); if (success) { result_.success = true; ROS_INFO("%s: Succeeded!", action_name_.c_str()); as_.setSucceeded(result_); } else { result_.success = false; ROS_INFO("%s: Failed!", action_name_.c_str()); as_.setSucceeded(result_); } move_init_client_.call(move_init_srv_); } <commit_msg>Fix Walk to ball action listening to the wrong topic, remove warn<commit_after>#include "navigation/walk_to_ball_server.hpp" WalkToBallAction::WalkToBallAction(std::string name) : as_(nh_, name, boost::bind(&WalkToBallAction::executeCB, this, _1), false), action_name_(name) { // as_.registerGoalCallback(boost::bind(&WalkToBallAction::goalCB, this)); ball_pos_sub_ = nh_.subscribe("/vision/ball", 1, &WalkToBallAction::goalCB, this); get_pose_client_ = nh_.serviceClient<motion_msgs::GetRobotPosition>( "/motion/get_robot_position", true); get_pose_client_.waitForExistence(); move_toward_client_ = nh_.serviceClient<motion_msgs::MoveToward>( "/motion/move_toward", true); move_toward_client_.waitForExistence(); stop_move_client_ = nh_.serviceClient<std_srvs::Empty>( "/motion/stop_move", true); stop_move_client_.waitForExistence(); move_init_client_ = nh_.serviceClient<std_srvs::Empty>( "/motion/move_init", true); move_init_client_.waitForExistence(); start_position_.request.use_sensors = true; get_pose_srv_.request.use_sensors = true; ROS_INFO("Starting WalkToBall server"); target_distance = 0.0f; target_theta = 0.0f; theta_scalar = 1.0f; dist_scalar = 3.0f; theta_thresh = 0.2f; dist_thresh = 0.05f; as_.start(); } WalkToBallAction::~WalkToBallAction(void) { } void WalkToBallAction::goalCB(const vision_msgs::BallDetection::ConstPtr& msg) { ROS_INFO("New Goal Received"); target_distance = msg->pos_robot.x; target_theta = msg->pos_robot.z; } void WalkToBallAction::executeCB( const navigation_msgs::WalkToBallGoalConstPtr& goal) { bool going = true; bool success = true; ROS_INFO("Executing goal for %s", action_name_.c_str()); get_pose_client_.call(start_position_); if (target_distance == 0.0f && target_theta == 0.0f) { target_distance = goal->ball_pose.x; target_theta = goal->ball_pose.theta; ROS_ERROR("Ball position not available, using agent goal %f, %f", target_distance, target_theta); } // ROTATE FIRST, THEN STRAIGHT TO GOAL // move_toward_srv_.request.control_points.resize(2); // move_toward_srv_.request.control_points[0].x = 0.0f; // move_toward_srv_.request.control_points[0].y = 0.0f; // move_toward_srv_.request.control_points[0].theta = goal->target_pose.theta; // move_toward_srv_.request.control_points[1].x = goal->target_pose.x; // move_toward_srv_.request.control_points[1].y = 0.0f; // move_toward_srv_.request.control_points[1].theta = 0.0f; // move_toward_client_.call(move_toward_srv_); while (going == true) { if (as_.isPreemptRequested() || !ros::ok()) { ROS_INFO("%s: Preempted", action_name_.c_str()); as_.setPreempted(); success = false; going = false; } get_pose_client_.call(get_pose_srv_); feedback_.curr_pose.x = get_pose_srv_.response.position.x - start_position_.response.position.x; feedback_.curr_pose.y = get_pose_srv_.response.position.y - start_position_.response.position.y; feedback_.curr_pose.theta = get_pose_srv_.response.position.theta - start_position_.response.position.theta; as_.publishFeedback(feedback_); ROS_INFO("Current pos: %f, %f, %f", feedback_.curr_pose.x, feedback_.curr_pose.y, feedback_.curr_pose.theta); ROS_INFO("Target dis: %f, Target theta %f", target_distance, target_theta); // float distance = sqrt(pow(feedback_.curr_pose.x, 2) + // pow(feedback_.curr_pose.y, 2) ); // float distance_error = target_distance - distance; // Absolute // float theta_error = target_theta - feedback_.curr_pose.theta; // Absolute float distance_error = target_distance; // Relative float theta_error = target_theta; // Relative ROS_INFO("Distance_error: %f, Theta error: %f", distance_error, theta_error); // ROTATE FIRST, THEN STRAIGHT TO GOAL move_toward_srv_.request.norm_velocity.x = 0.0f; move_toward_srv_.request.norm_velocity.theta = 0.0f; if (fabs(theta_error) > theta_thresh) { if (theta_error < 0) { ROS_INFO("Right"); } else { ROS_INFO("Left"); } float theta_vel = theta_error * theta_scalar; if (theta_vel < -1.0) {theta_vel = -1.0;} else if (theta_vel > 1.0) {theta_vel = 1.0;} move_toward_srv_.request.norm_velocity.theta = theta_vel; ROS_INFO("Rot. Speed: %f", move_toward_srv_.request.norm_velocity.theta); move_toward_client_.call(move_toward_srv_); } else if (fabs(distance_error) > dist_thresh) { if (distance_error > 0) { ROS_INFO("Forward"); } float forw_vel = distance_error * dist_scalar; if (forw_vel < -1.0) {forw_vel = -1.0;} else if (forw_vel > 1.0) {forw_vel = 1.0;} move_toward_srv_.request.norm_velocity.x = forw_vel; ROS_INFO("Dist. Speed: %f", move_toward_srv_.request.norm_velocity.x); move_toward_client_.call(move_toward_srv_); } if ((fabs(distance_error) < dist_thresh) && (fabs(theta_error) < theta_thresh)) { ROS_INFO("%s: Arrived", action_name_.c_str()); going = false; } } stop_move_client_.call(stop_move_srv_); if (success) { result_.success = true; ROS_INFO("%s: Succeeded!", action_name_.c_str()); as_.setSucceeded(result_); } else { result_.success = false; ROS_INFO("%s: Failed!", action_name_.c_str()); as_.setSucceeded(result_); } move_init_client_.call(move_init_srv_); } <|endoftext|>
<commit_before>/// Eepromscope driver /// /// (c) Koheron #ifndef __DRIVERS_CORE_EEPROM_HPP__ #define __DRIVERS_CORE_EEPROM_HPP__ #include <vector> #include <drivers/lib/dev_mem.hpp> #include <drivers/addresses.hpp> #include <thread> #include <chrono> // http://www.atmel.com/images/Atmel-5193-SEEPROM-AT93C46D-Datasheet.pdf #define WRITE_OPCODE 1 #define READ_OPCODE 2 #define ERASE_OPCODE 3 #define EWDS 0 #define WRAL 1 #define ERAL 2 #define EWEN 3 using namespace std::chrono_literals; class Eeprom { public: Eeprom(Klib::DevMem& dvm_) : dvm(dvm_) { config_map = dvm.AddMemoryMap(CONFIG_ADDR, CONFIG_RANGE); status_map = dvm.AddMemoryMap(STATUS_ADDR, STATUS_RANGE, PROT_READ); } int Open() {return dvm.is_ok() ? 0 : -1;} uint32_t read(uint32_t addr) { dvm.write32(config_map, SPI_IN_OFF, (READ_OPCODE << 7) + (addr << 1)); dvm.set_bit(config_map, SPI_IN_OFF, 0); std::this_thread::sleep_for(100us); return dvm.read32(status_map, SPI_OUT_OFF); } void write_enable() { dvm.write32(config_map, SPI_IN_OFF, (EWEN << 5)); dvm.set_bit(config_map, SPI_IN_OFF, 0); } void erase(uint32_t addr) { dvm.write32(config_map, SPI_IN_OFF, (ERASE_OPCODE << 7) + (addr << 1)); dvm.set_bit(config_map, SPI_IN_OFF, 0); } void write(uint32_t addr, uint32_t data_in) { dvm.write32(config_map, SPI_IN_OFF, (data_in << 16) + (WRITE_OPCODE << 7) + (addr << 1)); dvm.set_bit(config_map, SPI_IN_OFF, 0); } void erase_all() { dvm.write32(config_map, SPI_IN_OFF, (ERAL << 5)); dvm.set_bit(config_map, SPI_IN_OFF, 0); } void write_all(uint32_t data_in) { dvm.write32(config_map, SPI_IN_OFF, (data_in << 16) + (WRAL << 5)); dvm.set_bit(config_map, SPI_IN_OFF, 0); } void erase_write_disable() { dvm.write32(config_map, SPI_IN_OFF, (EWDS << 5)); dvm.set_bit(config_map, SPI_IN_OFF, 0); } #pragma tcp-server is_failed bool IsFailed() const {return dvm.IsFailed();} private: Klib::DevMem& dvm; Klib::MemMapID config_map; Klib::MemMapID status_map; }; // class Eeprom #endif // __DRIVERS_CORE_EEPROM_HPP__ <commit_msg>style (#170)<commit_after>/// Eepromscope driver /// /// (c) Koheron #ifndef __DRIVERS_CORE_EEPROM_HPP__ #define __DRIVERS_CORE_EEPROM_HPP__ #include <vector> #include <thread> #include <chrono> #include <drivers/lib/dev_mem.hpp> #include <drivers/addresses.hpp> // http://www.atmel.com/images/Atmel-5193-SEEPROM-AT93C46D-Datasheet.pdf #define WRITE_OPCODE 1 #define READ_OPCODE 2 #define ERASE_OPCODE 3 #define EWDS 0 #define WRAL 1 #define ERAL 2 #define EWEN 3 using namespace std::chrono_literals; class Eeprom { public: Eeprom(Klib::DevMem& dvm_) : dvm(dvm_) { config_map = dvm.AddMemoryMap(CONFIG_ADDR, CONFIG_RANGE); status_map = dvm.AddMemoryMap(STATUS_ADDR, STATUS_RANGE, PROT_READ); } int Open() {return dvm.is_ok() ? 0 : -1;} uint32_t read(uint32_t addr) { dvm.write32(config_map, SPI_IN_OFF, (READ_OPCODE << 7) + (addr << 1)); dvm.set_bit(config_map, SPI_IN_OFF, 0); std::this_thread::sleep_for(100us); return dvm.read32(status_map, SPI_OUT_OFF); } void write_enable() { dvm.write32(config_map, SPI_IN_OFF, (EWEN << 5)); dvm.set_bit(config_map, SPI_IN_OFF, 0); } void erase(uint32_t addr) { dvm.write32(config_map, SPI_IN_OFF, (ERASE_OPCODE << 7) + (addr << 1)); dvm.set_bit(config_map, SPI_IN_OFF, 0); } void write(uint32_t addr, uint32_t data_in) { dvm.write32(config_map, SPI_IN_OFF, (data_in << 16) + (WRITE_OPCODE << 7) + (addr << 1)); dvm.set_bit(config_map, SPI_IN_OFF, 0); } void erase_all() { dvm.write32(config_map, SPI_IN_OFF, (ERAL << 5)); dvm.set_bit(config_map, SPI_IN_OFF, 0); } void write_all(uint32_t data_in) { dvm.write32(config_map, SPI_IN_OFF, (data_in << 16) + (WRAL << 5)); dvm.set_bit(config_map, SPI_IN_OFF, 0); } void erase_write_disable() { dvm.write32(config_map, SPI_IN_OFF, (EWDS << 5)); dvm.set_bit(config_map, SPI_IN_OFF, 0); } #pragma tcp-server is_failed bool IsFailed() const {return dvm.IsFailed();} private: Klib::DevMem& dvm; Klib::MemMapID config_map; Klib::MemMapID status_map; }; // class Eeprom #endif // __DRIVERS_CORE_EEPROM_HPP__ <|endoftext|>
<commit_before>/* This file is part of Ingen. * Copyright (C) 2007-2009 Dave Robillard <http://drobilla.net> * * Ingen 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. * * Ingen 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 details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "OSCClientReceiver.hpp" #include "raul/AtomLiblo.hpp" #include <list> #include <cassert> #include <cstring> #include <iostream> #include <sstream> using namespace std; using namespace Raul; namespace Ingen { namespace Client { using namespace Shared; OSCClientReceiver::OSCClientReceiver(int listen_port, SharedPtr<Shared::ClientInterface> target) : _target(target) , _listen_port(listen_port) , _st(NULL) { start(true); // true = dump, false = shutup } OSCClientReceiver::~OSCClientReceiver() { stop(); } void OSCClientReceiver::start(bool dump_osc) { if (_st != NULL) return; // Attempt preferred port if (_listen_port != 0) { char port_str[8]; snprintf(port_str, 8, "%d", _listen_port); _st = lo_server_thread_new(port_str, lo_error_cb); } // Find a free port if (!_st) { _st = lo_server_thread_new(NULL, lo_error_cb); _listen_port = lo_server_thread_get_port(_st); } if (_st == NULL) { cerr << "[OSCClientReceiver] Could not start OSC listener. Aborting." << endl; exit(EXIT_FAILURE); } else { cout << "[OSCClientReceiver] Started OSC listener on port " << lo_server_thread_get_port(_st) << endl; } // Print all incoming messages if (dump_osc) lo_server_thread_add_method(_st, NULL, NULL, generic_cb, NULL); setup_callbacks(); // Display any uncaught messages to the console //lo_server_thread_add_method(_st, NULL, NULL, unknown_cb, NULL); lo_server_thread_start(_st); } void OSCClientReceiver::stop() { if (_st != NULL) { //unregister_client(); lo_server_thread_free(_st); _st = NULL; } } int OSCClientReceiver::generic_cb(const char* path, const char* types, lo_arg** argv, int argc, void* data, void* user_data) { printf("[OSCMsg] %s (%s)\t", path, types); for (int i=0; i < argc; ++i) { lo_arg_pp(lo_type(types[i]), argv[i]); printf("\t"); } printf("\n"); /*for (int i=0; i < argc; ++i) { printf(" '%c' ", types[i]); lo_arg_pp(lo_type(types[i]), argv[i]); printf("\n"); } printf("\n");*/ return 1; // not handled } void OSCClientReceiver::lo_error_cb(int num, const char* msg, const char* path) { cerr << "Got error from server: " << msg << endl; } int OSCClientReceiver::unknown_cb(const char* path, const char* types, lo_arg** argv, int argc, void* data, void* user_data) { std::string msg = "Received unknown OSC message: "; msg += path; cerr << msg << endl; return 0; } void OSCClientReceiver::setup_callbacks() { lo_server_thread_add_method(_st, "/ingen/ok", "i", response_ok_cb, this); lo_server_thread_add_method(_st, "/ingen/error", "is", response_error_cb, this); lo_server_thread_add_method(_st, "/ingen/plugin", "sss", plugin_cb, this); lo_server_thread_add_method(_st, "/ingen/put", NULL, put_cb, this); lo_server_thread_add_method(_st, "/ingen/move", "ss", move_cb, this); lo_server_thread_add_method(_st, "/ingen/delete", "s", del_cb, this); lo_server_thread_add_method(_st, "/ingen/clear_patch", "s", clear_patch_cb, this); lo_server_thread_add_method(_st, "/ingen/new_connection", "ss", connection_cb, this); lo_server_thread_add_method(_st, "/ingen/disconnection", "ss", disconnection_cb, this); lo_server_thread_add_method(_st, "/ingen/new_port", "sisi", new_port_cb, this); lo_server_thread_add_method(_st, "/ingen/set_property", NULL, set_property_cb, this); lo_server_thread_add_method(_st, "/ingen/set_port_value", "sf", set_port_value_cb, this); lo_server_thread_add_method(_st, "/ingen/set_voice_value", "sif", set_voice_value_cb, this); lo_server_thread_add_method(_st, "/ingen/activity", "s", activity_cb, this); } /** Catches errors that aren't a direct result of a client request. */ int OSCClientReceiver::_error_cb(const char* path, const char* types, lo_arg** argv, int argc, lo_message msg) { _target->error((char*)argv[0]); return 0; } int OSCClientReceiver::_del_cb(const char* path, const char* types, lo_arg** argv, int argc, lo_message msg) { _target->del((const char*)&argv[0]->s); return 0; } int OSCClientReceiver::_clear_patch_cb(const char* path, const char* types, lo_arg** argv, int argc, lo_message msg) { _target->clear_patch((const char*)&argv[0]->s); return 0; } int OSCClientReceiver::_put_cb(const char* path, const char* types, lo_arg** argv, int argc, lo_message msg) { const char* obj_path = &argv[0]->s; Resource::Properties prop; for (int i = 1; i < argc-1; i += 2) prop.insert(make_pair(&argv[i]->s, AtomLiblo::lo_arg_to_atom(types[i+1], argv[i+1]))); _target->put(obj_path, prop); return 0; } int OSCClientReceiver::_move_cb(const char* path, const char* types, lo_arg** argv, int argc, lo_message msg) { _target->move((const char*)&argv[0]->s, (const char*)&argv[1]->s); return 0; } int OSCClientReceiver::_connection_cb(const char* path, const char* types, lo_arg** argv, int argc, lo_message msg) { const char* const src_port_path = &argv[0]->s; const char* const dst_port_path = &argv[1]->s; _target->connect(src_port_path, dst_port_path); return 0; } int OSCClientReceiver::_disconnection_cb(const char* path, const char* types, lo_arg** argv, int argc, lo_message msg) { const char* src_port_path = &argv[0]->s; const char* dst_port_path = &argv[1]->s; _target->disconnect(src_port_path, dst_port_path); return 0; } /** Notification of a new or updated property. */ int OSCClientReceiver::_set_property_cb(const char* path, const char* types, lo_arg** argv, int argc, lo_message msg) { if (argc != 3 || types[0] != 's' || types[1] != 's') return 1; const char* obj_uri = &argv[0]->s; const char* key = &argv[1]->s; Atom value = AtomLiblo::lo_arg_to_atom(types[2], argv[2]); _target->set_property(obj_uri, key, value); return 0; } int OSCClientReceiver::_set_port_value_cb(const char* path, const char* types, lo_arg** argv, int argc, lo_message msg) { const char* const port_path = &argv[0]->s; const float value = argv[1]->f; _target->set_port_value(port_path, value); return 0; } int OSCClientReceiver::_set_voice_value_cb(const char* path, const char* types, lo_arg** argv, int argc, lo_message msg) { const char* const port_path = &argv[0]->s; const int voice = argv[1]->i; const float value = argv[2]->f; _target->set_voice_value(port_path, voice, value); return 0; } int OSCClientReceiver::_activity_cb(const char* path, const char* types, lo_arg** argv, int argc, lo_message msg) { const char* const port_path = &argv[0]->s; _target->activity(port_path); return 0; } int OSCClientReceiver::_response_ok_cb(const char* path, const char* types, lo_arg** argv, int argc, lo_message msg) { assert(!strcmp(types, "i")); _target->response_ok(argv[0]->i); return 0; } int OSCClientReceiver::_response_error_cb(const char* path, const char* types, lo_arg** argv, int argc, lo_message msg) { assert(!strcmp(types, "is")); _target->response_error(argv[0]->i, &argv[1]->s); return 0; } } // namespace Client } // namespace Ingen <commit_msg>Turn off OSC debugging.<commit_after>/* This file is part of Ingen. * Copyright (C) 2007-2009 Dave Robillard <http://drobilla.net> * * Ingen 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. * * Ingen 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 details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "OSCClientReceiver.hpp" #include "raul/AtomLiblo.hpp" #include <list> #include <cassert> #include <cstring> #include <iostream> #include <sstream> using namespace std; using namespace Raul; namespace Ingen { namespace Client { using namespace Shared; OSCClientReceiver::OSCClientReceiver(int listen_port, SharedPtr<Shared::ClientInterface> target) : _target(target) , _listen_port(listen_port) , _st(NULL) { start(false); // true = dump, false = shutup } OSCClientReceiver::~OSCClientReceiver() { stop(); } void OSCClientReceiver::start(bool dump_osc) { if (_st != NULL) return; // Attempt preferred port if (_listen_port != 0) { char port_str[8]; snprintf(port_str, 8, "%d", _listen_port); _st = lo_server_thread_new(port_str, lo_error_cb); } // Find a free port if (!_st) { _st = lo_server_thread_new(NULL, lo_error_cb); _listen_port = lo_server_thread_get_port(_st); } if (_st == NULL) { cerr << "[OSCClientReceiver] Could not start OSC listener. Aborting." << endl; exit(EXIT_FAILURE); } else { cout << "[OSCClientReceiver] Started OSC listener on port " << lo_server_thread_get_port(_st) << endl; } // Print all incoming messages if (dump_osc) lo_server_thread_add_method(_st, NULL, NULL, generic_cb, NULL); setup_callbacks(); // Display any uncaught messages to the console //lo_server_thread_add_method(_st, NULL, NULL, unknown_cb, NULL); lo_server_thread_start(_st); } void OSCClientReceiver::stop() { if (_st != NULL) { //unregister_client(); lo_server_thread_free(_st); _st = NULL; } } int OSCClientReceiver::generic_cb(const char* path, const char* types, lo_arg** argv, int argc, void* data, void* user_data) { printf("[OSCMsg] %s (%s)\t", path, types); for (int i=0; i < argc; ++i) { lo_arg_pp(lo_type(types[i]), argv[i]); printf("\t"); } printf("\n"); /*for (int i=0; i < argc; ++i) { printf(" '%c' ", types[i]); lo_arg_pp(lo_type(types[i]), argv[i]); printf("\n"); } printf("\n");*/ return 1; // not handled } void OSCClientReceiver::lo_error_cb(int num, const char* msg, const char* path) { cerr << "Got error from server: " << msg << endl; } int OSCClientReceiver::unknown_cb(const char* path, const char* types, lo_arg** argv, int argc, void* data, void* user_data) { std::string msg = "Received unknown OSC message: "; msg += path; cerr << msg << endl; return 0; } void OSCClientReceiver::setup_callbacks() { lo_server_thread_add_method(_st, "/ingen/ok", "i", response_ok_cb, this); lo_server_thread_add_method(_st, "/ingen/error", "is", response_error_cb, this); lo_server_thread_add_method(_st, "/ingen/plugin", "sss", plugin_cb, this); lo_server_thread_add_method(_st, "/ingen/put", NULL, put_cb, this); lo_server_thread_add_method(_st, "/ingen/move", "ss", move_cb, this); lo_server_thread_add_method(_st, "/ingen/delete", "s", del_cb, this); lo_server_thread_add_method(_st, "/ingen/clear_patch", "s", clear_patch_cb, this); lo_server_thread_add_method(_st, "/ingen/new_connection", "ss", connection_cb, this); lo_server_thread_add_method(_st, "/ingen/disconnection", "ss", disconnection_cb, this); lo_server_thread_add_method(_st, "/ingen/new_port", "sisi", new_port_cb, this); lo_server_thread_add_method(_st, "/ingen/set_property", NULL, set_property_cb, this); lo_server_thread_add_method(_st, "/ingen/set_port_value", "sf", set_port_value_cb, this); lo_server_thread_add_method(_st, "/ingen/set_voice_value", "sif", set_voice_value_cb, this); lo_server_thread_add_method(_st, "/ingen/activity", "s", activity_cb, this); } /** Catches errors that aren't a direct result of a client request. */ int OSCClientReceiver::_error_cb(const char* path, const char* types, lo_arg** argv, int argc, lo_message msg) { _target->error((char*)argv[0]); return 0; } int OSCClientReceiver::_del_cb(const char* path, const char* types, lo_arg** argv, int argc, lo_message msg) { _target->del((const char*)&argv[0]->s); return 0; } int OSCClientReceiver::_clear_patch_cb(const char* path, const char* types, lo_arg** argv, int argc, lo_message msg) { _target->clear_patch((const char*)&argv[0]->s); return 0; } int OSCClientReceiver::_put_cb(const char* path, const char* types, lo_arg** argv, int argc, lo_message msg) { const char* obj_path = &argv[0]->s; Resource::Properties prop; for (int i = 1; i < argc-1; i += 2) prop.insert(make_pair(&argv[i]->s, AtomLiblo::lo_arg_to_atom(types[i+1], argv[i+1]))); _target->put(obj_path, prop); return 0; } int OSCClientReceiver::_move_cb(const char* path, const char* types, lo_arg** argv, int argc, lo_message msg) { _target->move((const char*)&argv[0]->s, (const char*)&argv[1]->s); return 0; } int OSCClientReceiver::_connection_cb(const char* path, const char* types, lo_arg** argv, int argc, lo_message msg) { const char* const src_port_path = &argv[0]->s; const char* const dst_port_path = &argv[1]->s; _target->connect(src_port_path, dst_port_path); return 0; } int OSCClientReceiver::_disconnection_cb(const char* path, const char* types, lo_arg** argv, int argc, lo_message msg) { const char* src_port_path = &argv[0]->s; const char* dst_port_path = &argv[1]->s; _target->disconnect(src_port_path, dst_port_path); return 0; } /** Notification of a new or updated property. */ int OSCClientReceiver::_set_property_cb(const char* path, const char* types, lo_arg** argv, int argc, lo_message msg) { if (argc != 3 || types[0] != 's' || types[1] != 's') return 1; const char* obj_uri = &argv[0]->s; const char* key = &argv[1]->s; Atom value = AtomLiblo::lo_arg_to_atom(types[2], argv[2]); _target->set_property(obj_uri, key, value); return 0; } int OSCClientReceiver::_set_port_value_cb(const char* path, const char* types, lo_arg** argv, int argc, lo_message msg) { const char* const port_path = &argv[0]->s; const float value = argv[1]->f; _target->set_port_value(port_path, value); return 0; } int OSCClientReceiver::_set_voice_value_cb(const char* path, const char* types, lo_arg** argv, int argc, lo_message msg) { const char* const port_path = &argv[0]->s; const int voice = argv[1]->i; const float value = argv[2]->f; _target->set_voice_value(port_path, voice, value); return 0; } int OSCClientReceiver::_activity_cb(const char* path, const char* types, lo_arg** argv, int argc, lo_message msg) { const char* const port_path = &argv[0]->s; _target->activity(port_path); return 0; } int OSCClientReceiver::_response_ok_cb(const char* path, const char* types, lo_arg** argv, int argc, lo_message msg) { assert(!strcmp(types, "i")); _target->response_ok(argv[0]->i); return 0; } int OSCClientReceiver::_response_error_cb(const char* path, const char* types, lo_arg** argv, int argc, lo_message msg) { assert(!strcmp(types, "is")); _target->response_error(argv[0]->i, &argv[1]->s); return 0; } } // namespace Client } // namespace Ingen <|endoftext|>
<commit_before>#include "ingamescene.h" #include <QPixmap> #include <QtGlobal> #include "../dice.h" #include <QTimeLine> #include <QEasingCurve> #include "block.h" #include "localgame.h" IngameScene::IngameScene(qreal x, qreal y, qreal width, qreal height, QObject *parent) : QGraphicsScene(x,y,width,height,parent), window(dynamic_cast<MainWindow*>(parent)) { Q_CHECK_PTR(window); setBackgroundPixmap(":/images/ingame/board/board_back.png"); LocalGame * game = LocalGame::getInst(); board = new Board(this,window); board->setPos(200,720 - board->boundingRect().size().height()); board->setZValue(2); Player * player = new Player(board,1); player->setImage(":/images/ingame/pieces/blue.png"); player->setPos(BlockCoords::corner_coord[0]); player->setZValue(3); game->addPlayer(player); player = new Player(board,2); player->setImage(":/images/ingame/pieces/red.png"); player->setPos(BlockCoords::corner_coord[0]); player->setZValue(3); player->setEnergy(0); player->addBlock(board->getBlock(10)); player->addBlock(board->getBlock(11)); player->addBlock(board->getBlock(13)); game->addPlayer(player); game->init(board,Dice::getInst()); // double graphic: hide double_graphic = new QGameItem(this, window); double_graphic->setImage(":images/ingame/double.png"); double_graphic->setPos(440, 300); double_graphic->setZValue(4); double_graphic->hide(false, 0); // timeline for double graphic double_timeline = new QTimeLine(1500); connect(double_timeline, SIGNAL(finished()), this, SLOT(hideDouble())); //주사위 그래픽 dice_graphic = new DiceGraphicItem(this,window); dice_graphic->setPos(800,400); dice_graphic->setZValue(2); //주사위 패널 첫번째 first_dice_panel = new DiceValuePanel(this,window); first_dice_panel->setPos(400,400); first_dice_panel->setZValue(2); //주사위 패널 두번째 second_dice_panel = new DiceValuePanel(this,window); second_dice_panel->setPos(500,400); second_dice_panel->setZValue(2); status1 = new QGameItem(this, window); status1->setImage(":images/ingame/status/status1.png"); status1->setPos(350, 160); status2 = new QGameItem(this, window); status2->setImage(":images/ingame/status/status2.png"); status2->setPos(660, 160); //Signal / Slots connection Dice * dice = Dice::getInst(); connect(dice, SIGNAL(diceDouble()), this, SLOT(showDouble())); connect(dice,SIGNAL(firstDiceRolled(int)),first_dice_panel,SLOT(setValue(int))); connect(dice,SIGNAL(secondDiceRolled(int)),second_dice_panel,SLOT(setValue(int))); } IngameScene::~IngameScene(){ delete first_dice_panel; delete second_dice_panel; delete dice_graphic; delete background; } QGraphicsPixmapItem* IngameScene::setBackgroundPixmap(const char * filename){ background = this->addPixmap(QPixmap(filename)); return background; } QGraphicsPixmapItem* IngameScene::backgroundPixmap(){ return background; } void IngameScene::showDouble() { qDebug() << "Show Double"; double_graphic->show(true, 0.3); double_timeline->start(); } void IngameScene::hideDouble() { qDebug() << "Hide Double"; double_graphic->hide(true, 0.3); } void IngameScene::showPhotoGenic() { } void IngameScene::hidePhotoGenic() { } // DiceGrahicItem DiceGraphicItem::DiceGraphicItem(QGraphicsScene *scene, MainWindow *window) : QGameItem(scene,window){ //버튼 초기상태 이미지 this->setImage(":/images/ingame/button.png"); } void DiceGraphicItem::mousePressEvent(QGraphicsSceneMouseEvent *event){ //버튼이 눌렸을 때의 이미지로 바꿈 this->setImage(":/images/ingame/button2_pushed.png"); //QGameItem::mousePressEvent(event); } void DiceGraphicItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event){ //마우스에서 땠을 경우 다시 초기상태 이미지로 바꿈 this->setImage(":/images/ingame/button.png"); //여기에 게임 스테이트 머신을 추가해서 롤할지 안할지 결정하게 해야함 Dice * dice = Dice::getInst(); dice->roll(); } // DiceValuePanel DiceValuePanel::DiceValuePanel(QGraphicsScene *scene, MainWindow *window) : QGameItem(scene,window) { setImage(":/images/ingame/dice/dice3.png"); //default image timeline = new QTimeLine(1500); //spin for 1.5 second timeline->setFrameRange(0,50); // 50 spins timeline->setEasingCurve(QEasingCurve::InOutCirc); connect(this->timeline,SIGNAL(frameChanged(int)),this,SLOT(spinValue(int))); connect(timeline,SIGNAL(finished()),this,SLOT(endSpin())); } void DiceValuePanel::endSpin(){ //finally fix dice image to diceValue switch(diceValue){ case 1: this->setImage(":/images/ingame/dice/dice1.png"); break; case 2: this->setImage(":/images/ingame/dice/dice2.png"); break; case 3: this->setImage(":/images/ingame/dice/dice3.png"); break; case 4: this->setImage(":/images/ingame/dice/dice4.png"); break; case 5: this->setImage(":/images/ingame/dice/dice5.png"); break; case 6: this->setImage(":/images/ingame/dice/dice6.png"); break; } } void DiceValuePanel::setValue(int value){ diceValue = value; timeline->start(); } void DiceValuePanel::spinValue(int frame){ int value = rand() % 6 + 1; switch(value){ case 1: this->setImage(":/images/ingame/dice/dice1.png"); break; case 2: this->setImage(":/images/ingame/dice/dice2.png"); break; case 3: this->setImage(":/images/ingame/dice/dice3.png"); break; case 4: this->setImage(":/images/ingame/dice/dice4.png"); break; case 5: this->setImage(":/images/ingame/dice/dice5.png"); break; case 6: this->setImage(":/images/ingame/dice/dice6.png"); break; } } void DiceValuePanel::mousePressEvent(QGraphicsSceneMouseEvent *event){ } void DiceValuePanel::mouseReleaseEvent(QGraphicsSceneMouseEvent *event){ } PhotoGenicItem::PhotoGenicItem(QGraphicsScene *scene, MainWindow *window) : QGameItem(scene,window){ } void PhotoGenicItem::showPhotos(){ timeline = new QTimeLine(3000); //spin for 3 second timeline->setFrameRange(0,5); // 3 spins timeline->setEasingCurve(QEasingCurve::Linear); connect(this->timeline,SIGNAL(frameChanged(int)),this,SLOT(slidePhoto(int))); connect(this->timeline,SIGNAL(finished()),this,SLOT(slideFinish())); timeline->start(); setZValue(10); } PhotoGenicItem::~PhotoGenicItem() { qDebug()<<"photogenic item destoyed."<<endl; } void PhotoGenicItem::slidePhoto(int frame){ switch(frame){ case 1: setImage(":/images/ourphotos/photo1.png"); break; case 2: setImage(":/images/ourphotos/photo2.png"); break; case 3: setImage(":/images/ourphotos/photo3.png"); break; } } void PhotoGenicItem::slideFinish(){ delete this; } <commit_msg>Photogenic: position to center<commit_after>#include "ingamescene.h" #include <QPixmap> #include <QtGlobal> #include "../dice.h" #include <QTimeLine> #include <QEasingCurve> #include "block.h" #include "localgame.h" IngameScene::IngameScene(qreal x, qreal y, qreal width, qreal height, QObject *parent) : QGraphicsScene(x,y,width,height,parent), window(dynamic_cast<MainWindow*>(parent)) { Q_CHECK_PTR(window); setBackgroundPixmap(":/images/ingame/board/board_back.png"); LocalGame * game = LocalGame::getInst(); board = new Board(this,window); board->setPos(200,720 - board->boundingRect().size().height()); board->setZValue(2); Player * player = new Player(board,1); player->setImage(":/images/ingame/pieces/blue.png"); player->setPos(BlockCoords::corner_coord[0]); player->setZValue(3); game->addPlayer(player); player = new Player(board,2); player->setImage(":/images/ingame/pieces/red.png"); player->setPos(BlockCoords::corner_coord[0]); player->setZValue(3); player->setEnergy(0); player->addBlock(board->getBlock(10)); player->addBlock(board->getBlock(11)); player->addBlock(board->getBlock(13)); game->addPlayer(player); game->init(board,Dice::getInst()); // double graphic: hide double_graphic = new QGameItem(this, window); double_graphic->setImage(":images/ingame/double.png"); double_graphic->setPos(440, 300); double_graphic->setZValue(4); double_graphic->hide(false, 0); // timeline for double graphic double_timeline = new QTimeLine(1500); connect(double_timeline, SIGNAL(finished()), this, SLOT(hideDouble())); //주사위 그래픽 dice_graphic = new DiceGraphicItem(this,window); dice_graphic->setPos(800,400); dice_graphic->setZValue(2); //주사위 패널 첫번째 first_dice_panel = new DiceValuePanel(this,window); first_dice_panel->setPos(400,400); first_dice_panel->setZValue(2); //주사위 패널 두번째 second_dice_panel = new DiceValuePanel(this,window); second_dice_panel->setPos(500,400); second_dice_panel->setZValue(2); status1 = new QGameItem(this, window); status1->setImage(":images/ingame/status/status1.png"); status1->setPos(350, 160); status2 = new QGameItem(this, window); status2->setImage(":images/ingame/status/status2.png"); status2->setPos(660, 160); //Signal / Slots connection Dice * dice = Dice::getInst(); connect(dice, SIGNAL(diceDouble()), this, SLOT(showDouble())); connect(dice,SIGNAL(firstDiceRolled(int)),first_dice_panel,SLOT(setValue(int))); connect(dice,SIGNAL(secondDiceRolled(int)),second_dice_panel,SLOT(setValue(int))); } IngameScene::~IngameScene(){ delete first_dice_panel; delete second_dice_panel; delete dice_graphic; delete background; } QGraphicsPixmapItem* IngameScene::setBackgroundPixmap(const char * filename){ background = this->addPixmap(QPixmap(filename)); return background; } QGraphicsPixmapItem* IngameScene::backgroundPixmap(){ return background; } void IngameScene::showDouble() { qDebug() << "Show Double"; double_graphic->show(true, 0.3); double_timeline->start(); } void IngameScene::hideDouble() { qDebug() << "Hide Double"; double_graphic->hide(true, 0.3); } void IngameScene::showPhotoGenic() { } void IngameScene::hidePhotoGenic() { } // DiceGrahicItem DiceGraphicItem::DiceGraphicItem(QGraphicsScene *scene, MainWindow *window) : QGameItem(scene,window){ //버튼 초기상태 이미지 this->setImage(":/images/ingame/button.png"); } void DiceGraphicItem::mousePressEvent(QGraphicsSceneMouseEvent *event){ //버튼이 눌렸을 때의 이미지로 바꿈 this->setImage(":/images/ingame/button2_pushed.png"); //QGameItem::mousePressEvent(event); } void DiceGraphicItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event){ //마우스에서 땠을 경우 다시 초기상태 이미지로 바꿈 this->setImage(":/images/ingame/button.png"); //여기에 게임 스테이트 머신을 추가해서 롤할지 안할지 결정하게 해야함 Dice * dice = Dice::getInst(); dice->roll(); } // DiceValuePanel DiceValuePanel::DiceValuePanel(QGraphicsScene *scene, MainWindow *window) : QGameItem(scene,window) { setImage(":/images/ingame/dice/dice3.png"); //default image timeline = new QTimeLine(1500); //spin for 1.5 second timeline->setFrameRange(0,50); // 50 spins timeline->setEasingCurve(QEasingCurve::InOutCirc); connect(this->timeline,SIGNAL(frameChanged(int)),this,SLOT(spinValue(int))); connect(timeline,SIGNAL(finished()),this,SLOT(endSpin())); } void DiceValuePanel::endSpin(){ //finally fix dice image to diceValue switch(diceValue){ case 1: this->setImage(":/images/ingame/dice/dice1.png"); break; case 2: this->setImage(":/images/ingame/dice/dice2.png"); break; case 3: this->setImage(":/images/ingame/dice/dice3.png"); break; case 4: this->setImage(":/images/ingame/dice/dice4.png"); break; case 5: this->setImage(":/images/ingame/dice/dice5.png"); break; case 6: this->setImage(":/images/ingame/dice/dice6.png"); break; } } void DiceValuePanel::setValue(int value){ diceValue = value; timeline->start(); } void DiceValuePanel::spinValue(int frame){ int value = rand() % 6 + 1; switch(value){ case 1: this->setImage(":/images/ingame/dice/dice1.png"); break; case 2: this->setImage(":/images/ingame/dice/dice2.png"); break; case 3: this->setImage(":/images/ingame/dice/dice3.png"); break; case 4: this->setImage(":/images/ingame/dice/dice4.png"); break; case 5: this->setImage(":/images/ingame/dice/dice5.png"); break; case 6: this->setImage(":/images/ingame/dice/dice6.png"); break; } } void DiceValuePanel::mousePressEvent(QGraphicsSceneMouseEvent *event){ } void DiceValuePanel::mouseReleaseEvent(QGraphicsSceneMouseEvent *event){ } PhotoGenicItem::PhotoGenicItem(QGraphicsScene *scene, MainWindow *window) : QGameItem(scene,window){ } void PhotoGenicItem::showPhotos(){ timeline = new QTimeLine(3000); //spin for 3 second timeline->setFrameRange(0,5); // 3 spins timeline->setEasingCurve(QEasingCurve::Linear); connect(this->timeline,SIGNAL(frameChanged(int)),this,SLOT(slidePhoto(int))); connect(this->timeline,SIGNAL(finished()),this,SLOT(slideFinish())); timeline->start(); setZValue(10); setPos(QPointF(1280/2,720/2) + QPointF(-200,-150)); } PhotoGenicItem::~PhotoGenicItem() { qDebug()<<"photogenic item destoyed."<<endl; } void PhotoGenicItem::slidePhoto(int frame){ switch(frame){ case 1: setImage(":/images/ourphotos/photo1.png"); break; case 2: setImage(":/images/ourphotos/photo2.png"); break; case 3: setImage(":/images/ourphotos/photo3.png"); break; } } void PhotoGenicItem::slideFinish(){ delete this; } <|endoftext|>
<commit_before>// Copyright 2015-2020 Elviss Strazdins. All rights reserved. #ifndef OUZEL_GRAPHICS_OGLPROCEDUREGETTER_HPP #define OUZEL_GRAPHICS_OGLPROCEDUREGETTER_HPP #include "../../core/Setup.h" #if OUZEL_COMPILE_OPENGL #include <algorithm> #include <stdexcept> #include "OGL.h" #if OUZEL_OPENGLES # include "GLES/gl.h" # include "GLES2/gl2.h" # include "GLES2/gl2ext.h" # include "GLES3/gl3.h" #else # include "GL/glcorearb.h" # include "GL/glext.h" #endif #if OUZEL_OPENGL_INTERFACE_EGL # include "EGL/egl.h" #elif OUZEL_OPENGL_INTERFACE_WGL # include "GL/wglext.h" #endif #include "../../core/Engine.hpp" #include "../../utils/Utils.hpp" namespace ouzel::graphics::opengl { class ProcedureGetter final { public: ProcedureGetter(ApiVersion version): apiVersion(version) { const auto glGetErrorProc = getProcAddress<PFNGLGETERRORPROC>("glGetError", ApiVersion(1, 0)); if (apiVersion >= ApiVersion(3, 0)) { const auto glGetIntegervProc = getProcAddress<PFNGLGETINTEGERVPROC>("glGetIntegerv", ApiVersion(1, 0)); const auto glGetStringiProc = getProcAddress<PFNGLGETSTRINGIPROC>("glGetStringi", ApiVersion(3, 0)); GLint extensionCount; glGetIntegervProc(GL_NUM_EXTENSIONS, &extensionCount); if (const auto error = glGetErrorProc(); error != GL_NO_ERROR) logger.log(Log::Level::warning) << "Failed to get OpenGL extension count, error: " + std::to_string(error); else for (GLuint i = 0; i < static_cast<GLuint>(extensionCount); ++i) { const auto extensionPtr = glGetStringiProc(GL_EXTENSIONS, i); if (const auto getStringError = glGetErrorProc(); getStringError != GL_NO_ERROR) logger.log(Log::Level::warning) << "Failed to get OpenGL extension, error: " + std::to_string(getStringError); else if (!extensionPtr) logger.log(Log::Level::warning) << "Failed to get OpenGL extension"; else extensions.emplace_back(reinterpret_cast<const char*>(extensionPtr)); } } else { const auto glGetStringProc = getProcAddress<PFNGLGETSTRINGPROC>("glGetString", ApiVersion(1, 0)); const auto extensionsPtr = glGetStringProc(GL_EXTENSIONS); if (const auto error = glGetErrorProc(); error != GL_NO_ERROR || !extensionsPtr) logger.log(Log::Level::warning) << "Failed to get OpenGL extensions, error: " + std::to_string(error); else extensions = explodeString(reinterpret_cast<const char*>(extensionsPtr), ' '); } logger.log(Log::Level::all) << "Supported OpenGL extensions: " << extensions; } template <typename T> T get(const char* name, ApiVersion procApiVersion) const noexcept { return (apiVersion >= procApiVersion) ? getProcAddress<T>(name, procApiVersion) : nullptr; } template <typename T> T get(const char* name, const char* extension) const noexcept { return hasExtension(extension) ? getProcAddress<T>(name) : nullptr; } template <typename T> T get(const char* name, ApiVersion procApiVersion, const std::map<const char*, const char*>& procExtensions) const noexcept { if (apiVersion >= procApiVersion) return getProcAddress<T>(name, procApiVersion); else for (const auto& extension : procExtensions) if (auto result = get<T>(extension.first, extension.second)) return result; return nullptr; } bool hasExtension(const char* ext) const noexcept { auto i = std::find(extensions.begin(), extensions.end(), ext); return i != extensions.end(); } private: template <typename T> T getProcAddress(const char* name, ApiVersion procApiVersion) const noexcept { #if OUZEL_OPENGL_INTERFACE_EGL # if OUZEL_OPENGLES return procApiVersion >= ApiVersion(3, 0) ? reinterpret_cast<T>(eglGetProcAddress(name)) : reinterpret_cast<T>(reinterpret_cast<std::uintptr_t>(dlsym(RTLD_DEFAULT, name))); # else (void)procApiVersion; return reinterpret_cast<T>(eglGetProcAddress(name)); # endif #elif OUZEL_OPENGL_INTERFACE_WGL return procApiVersion > ApiVersion(1, 1) ? reinterpret_cast<T>(wglGetProcAddress(name)) : reinterpret_cast<T>(GetProcAddress(module.getModule(), name)); #else (void)procApiVersion; return reinterpret_cast<T>(reinterpret_cast<std::uintptr_t>(dlsym(RTLD_DEFAULT, name))); #endif } template <typename T> T getProcAddress(const char* name) const noexcept { #if OUZEL_OPENGL_INTERFACE_EGL return reinterpret_cast<T>(eglGetProcAddress(name)); #elif OUZEL_OPENGL_INTERFACE_WGL return reinterpret_cast<T>(wglGetProcAddress(name)); #else return reinterpret_cast<T>(reinterpret_cast<std::uintptr_t>(dlsym(RTLD_DEFAULT, name))); #endif } ApiVersion apiVersion; std::vector<std::string> extensions; #if OUZEL_OPENGL_INTERFACE_WGL class Module final { public: Module(): module(LoadLibraryW(L"opengl32.dll")) { if (!module) throw std::system_error(GetLastError(), std::system_category(), "Failed to load opengl32.dll"); } ~Module() { if (module) FreeLibrary(module); } Module(const Module&) = delete; Module& operator=(const Module&) = delete; Module(Module&& other) noexcept: module{other.module} { other.module = nullptr; } Module& operator=(Module&& other) noexcept { if (this == &other) return *this; if (module) FreeLibrary(module); module = other.module; other.module = nullptr; return *this; } HMODULE getModule() const noexcept { return module; } private: HMODULE module = nullptr; } module; #endif }; } #endif #endif // OUZEL_GRAPHICS_OGLPROCEDUREGETTER_HPP <commit_msg>Print the error code only if the error is set<commit_after>// Copyright 2015-2020 Elviss Strazdins. All rights reserved. #ifndef OUZEL_GRAPHICS_OGLPROCEDUREGETTER_HPP #define OUZEL_GRAPHICS_OGLPROCEDUREGETTER_HPP #include "../../core/Setup.h" #if OUZEL_COMPILE_OPENGL #include <algorithm> #include <stdexcept> #include "OGL.h" #if OUZEL_OPENGLES # include "GLES/gl.h" # include "GLES2/gl2.h" # include "GLES2/gl2ext.h" # include "GLES3/gl3.h" #else # include "GL/glcorearb.h" # include "GL/glext.h" #endif #if OUZEL_OPENGL_INTERFACE_EGL # include "EGL/egl.h" #elif OUZEL_OPENGL_INTERFACE_WGL # include "GL/wglext.h" #endif #include "../../core/Engine.hpp" #include "../../utils/Utils.hpp" namespace ouzel::graphics::opengl { class ProcedureGetter final { public: ProcedureGetter(ApiVersion version): apiVersion(version) { const auto glGetErrorProc = getProcAddress<PFNGLGETERRORPROC>("glGetError", ApiVersion(1, 0)); if (apiVersion >= ApiVersion(3, 0)) { const auto glGetIntegervProc = getProcAddress<PFNGLGETINTEGERVPROC>("glGetIntegerv", ApiVersion(1, 0)); const auto glGetStringiProc = getProcAddress<PFNGLGETSTRINGIPROC>("glGetStringi", ApiVersion(3, 0)); GLint extensionCount; glGetIntegervProc(GL_NUM_EXTENSIONS, &extensionCount); if (const auto error = glGetErrorProc(); error != GL_NO_ERROR) logger.log(Log::Level::warning) << "Failed to get OpenGL extension count, error: " + std::to_string(error); else for (GLuint i = 0; i < static_cast<GLuint>(extensionCount); ++i) { const auto extensionPtr = glGetStringiProc(GL_EXTENSIONS, i); if (const auto getStringError = glGetErrorProc(); getStringError != GL_NO_ERROR) logger.log(Log::Level::warning) << "Failed to get OpenGL extension, error: " + std::to_string(getStringError); else if (!extensionPtr) logger.log(Log::Level::warning) << "Failed to get OpenGL extension"; else extensions.emplace_back(reinterpret_cast<const char*>(extensionPtr)); } } else { const auto glGetStringProc = getProcAddress<PFNGLGETSTRINGPROC>("glGetString", ApiVersion(1, 0)); const auto extensionsPtr = glGetStringProc(GL_EXTENSIONS); if (const auto error = glGetErrorProc(); error != GL_NO_ERROR) logger.log(Log::Level::warning) << "Failed to get OpenGL extensions, error: " + std::to_string(error); else if (!extensionsPtr) logger.log(Log::Level::warning) << "Failed to get OpenGL extensions"; else extensions = explodeString(reinterpret_cast<const char*>(extensionsPtr), ' '); } logger.log(Log::Level::all) << "Supported OpenGL extensions: " << extensions; } template <typename T> T get(const char* name, ApiVersion procApiVersion) const noexcept { return (apiVersion >= procApiVersion) ? getProcAddress<T>(name, procApiVersion) : nullptr; } template <typename T> T get(const char* name, const char* extension) const noexcept { return hasExtension(extension) ? getProcAddress<T>(name) : nullptr; } template <typename T> T get(const char* name, ApiVersion procApiVersion, const std::map<const char*, const char*>& procExtensions) const noexcept { if (apiVersion >= procApiVersion) return getProcAddress<T>(name, procApiVersion); else for (const auto& extension : procExtensions) if (auto result = get<T>(extension.first, extension.second)) return result; return nullptr; } bool hasExtension(const char* ext) const noexcept { auto i = std::find(extensions.begin(), extensions.end(), ext); return i != extensions.end(); } private: template <typename T> T getProcAddress(const char* name, ApiVersion procApiVersion) const noexcept { #if OUZEL_OPENGL_INTERFACE_EGL # if OUZEL_OPENGLES return procApiVersion >= ApiVersion(3, 0) ? reinterpret_cast<T>(eglGetProcAddress(name)) : reinterpret_cast<T>(reinterpret_cast<std::uintptr_t>(dlsym(RTLD_DEFAULT, name))); # else (void)procApiVersion; return reinterpret_cast<T>(eglGetProcAddress(name)); # endif #elif OUZEL_OPENGL_INTERFACE_WGL return procApiVersion > ApiVersion(1, 1) ? reinterpret_cast<T>(wglGetProcAddress(name)) : reinterpret_cast<T>(GetProcAddress(module.getModule(), name)); #else (void)procApiVersion; return reinterpret_cast<T>(reinterpret_cast<std::uintptr_t>(dlsym(RTLD_DEFAULT, name))); #endif } template <typename T> T getProcAddress(const char* name) const noexcept { #if OUZEL_OPENGL_INTERFACE_EGL return reinterpret_cast<T>(eglGetProcAddress(name)); #elif OUZEL_OPENGL_INTERFACE_WGL return reinterpret_cast<T>(wglGetProcAddress(name)); #else return reinterpret_cast<T>(reinterpret_cast<std::uintptr_t>(dlsym(RTLD_DEFAULT, name))); #endif } ApiVersion apiVersion; std::vector<std::string> extensions; #if OUZEL_OPENGL_INTERFACE_WGL class Module final { public: Module(): module(LoadLibraryW(L"opengl32.dll")) { if (!module) throw std::system_error(GetLastError(), std::system_category(), "Failed to load opengl32.dll"); } ~Module() { if (module) FreeLibrary(module); } Module(const Module&) = delete; Module& operator=(const Module&) = delete; Module(Module&& other) noexcept: module{other.module} { other.module = nullptr; } Module& operator=(Module&& other) noexcept { if (this == &other) return *this; if (module) FreeLibrary(module); module = other.module; other.module = nullptr; return *this; } HMODULE getModule() const noexcept { return module; } private: HMODULE module = nullptr; } module; #endif }; } #endif #endif // OUZEL_GRAPHICS_OGLPROCEDUREGETTER_HPP <|endoftext|>
<commit_before>/* -*- C++ -*- * * kPPP: A pppd front end for the KDE project * * $Id$ * * Copyright (C) 1997 Bernd Johannes Wuebben * wuebben@math.cornell.edu * * This file contributed by: Mario Weilguni, <mweilguni@sime.com> * Thanks Mario! * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <unistd.h> #include <sys/stat.h> #include <sys/types.h> #include <qdir.h> #include <qfile.h> #include <qdatetime.h> #include <qregexp.h> #include <qlabel.h> #include <kprogress.h> #include <kglobal.h> #include <kstddirs.h> #include <time.h> #include "accounting.h" #include "kpppconfig.h" #include "pppdata.h" #include "pppstats.h" #include "log.h" // defines the maximum duration until the current costs // are saved again (to prevent loss due to "kill") // specifying -1 disables the features #define UPDATE_TIME (5*60*1000) extern PPPData gpppdata; extern PPPStats stats; ///////////////////////////////////////////////////////////////////////////// // // Helper functions // ///////////////////////////////////////////////////////////////////////////// QString timet2qstring(time_t t) { QString s; s.sprintf("%lu", t); return s; } ///////////////////////////////////////////////////////////////////////////// // // The base class for the accounting system provides a base set of usefull // and common functions, but does not do any accounting by itself. The // accounting is accomplished withing its derived classes // ///////////////////////////////////////////////////////////////////////////// AccountingBase::AccountingBase(QObject *parent) : QObject(parent), _total(0), _session(0) { QDate dt = QDate::currentDate(); LogFileName = QString("%1-%2.log") .arg(dt.monthName(dt.month())) .arg(dt.year(), 4); LogFileName = KGlobal::dirs()->getSaveLocation("appdata", "Log") + LogFileName; debug("LogFileName: %s", LogFileName.latin1()); } AccountingBase::~AccountingBase() { if(running()) slotStop(); } double AccountingBase::total() { return _total + _session; } double AccountingBase::session() { return _session; } // set costs back to zero ( typically once per month) void AccountingBase::resetCosts(const char *accountname){ QString prev_account = gpppdata.accname(); gpppdata.setAccount(accountname); gpppdata.setTotalCosts(""); gpppdata.setAccount(prev_account); } void AccountingBase::resetVolume(const char *accountname){ QString prev_account = gpppdata.accname(); gpppdata.setAccount(accountname); gpppdata.setTotalBytes(0); gpppdata.setAccount(prev_account); } void AccountingBase::logMessage(QString s, bool newline) { int old_umask = umask(0077); QFile f(LogFileName); bool result = f.open(IO_ReadWrite); if(result) { // move to eof, and place \n if necessary if(f.size() > 0) { if(newline) { f.at(f.size()); char c = 0; f.readBlock(&c, 1); if(c != '\n') f.writeBlock("\n", 1); } else f.at(f.size()); } f.writeBlock(s.data(), s.length()); f.close(); } // restore umask umask(old_umask); } QString AccountingBase::getCosts(const char* accountname) { QString prev_account = gpppdata.accname(); gpppdata.setAccount(accountname); QString val = gpppdata.totalCosts(); gpppdata.setAccount(prev_account); return val; } bool AccountingBase::saveCosts() { if(!_name.isNull() && _name.length() > 0) { QString val; val.setNum(total()); gpppdata.setTotalCosts(val); gpppdata.save(); return TRUE; } else return FALSE; } bool AccountingBase::loadCosts() { QString val = gpppdata.totalCosts(); if(val.isNull()) // QString will segfault if isnull and toDouble called _total = 0.0; else { bool ok; _total = val.toDouble(&ok); if(!ok) _total = 0.0; } return TRUE; } QString AccountingBase::getAccountingFile(const QString &accountname) { QString f = "kppp/Rules/"; f += accountname; QString d = locate("data", f); if(d.isNull()) return ""; else return d; } ///////////////////////////////////////////////////////////////////////////// // // Accounting class for ruleset files // ///////////////////////////////////////////////////////////////////////////// Accounting::Accounting(QObject *parent) : AccountingBase(parent), acct_timer_id(0), update_timer_id(0) { } bool Accounting::running() { return (bool)(acct_timer_id != 0); } void Accounting::timerEvent(QTimerEvent *t) { if(t->timerId() == acct_timer_id) { double newCosts; double newLen; double connect_time = difftime(time(0), start_time); rules.getActiveRule(QDateTime::currentDateTime(), connect_time, newCosts, newLen); if(newLen < 1) { // changed to < 1 slotStop(); return; // no default rule found } // check if we have a new rule. If yes, // kill the timer and restart it with new // duration if((newCosts != _lastcosts) || (newLen != _lastlen)) { Debug("SWITCHING RULES, new costs = %0.2f, new len = %0.2f\n", newCosts, newLen); killTimer(acct_timer_id); if(newLen > 0) acct_timer_id = startTimer((int)(newLen * 1000.0)); _lastlen = newLen; _lastcosts = newCosts; } // emit changed() signal if necessary if(newCosts != 0) { _session += newCosts; emit changed(rules.currencyString(total()), rules.currencyString(session())); } } // if(t->timerId() == acct_timer_id)... if(t->timerId() == update_timer_id) { // just to be sure, save the current costs // every n seconds (see UPDATE_TIME) saveCosts(); } } void Accounting::slotStart() { if(!running()) { loadCosts(); _lastcosts = 0.0; _lastlen = 0.0; _session = rules.perConnectionCosts(); rules.setStartTime(QDateTime::currentDateTime()); acct_timer_id = startTimer(1); if(UPDATE_TIME > 0) update_timer_id = startTimer(UPDATE_TIME); start_time = time(0); QString s; s = timet2qstring(start_time); s += ":"; s += gpppdata.accname(); s += ":"; s += rules.currencySymbol(); logMessage(s, TRUE); } } void Accounting::slotStop() { if(running()) { killTimer(acct_timer_id); if(update_timer_id != 0) killTimer(update_timer_id); acct_timer_id = 0; update_timer_id = 0; QString s; s.sprintf(":%s:%0.4e:%0.4e:%u:%u\n", timet2qstring(time(0)).data(), session(), total(), stats.ibytes, stats.obytes); logMessage(s, FALSE); saveCosts(); } } bool Accounting::loadRuleSet(const char *name) { if(strlen(name) == 0) { rules.load(""); // delete old rules return TRUE; } QString d = AccountingBase::getAccountingFile(name); QFileInfo fg(d); if(fg.exists()) { int ret = rules.load(d.data()); _name = rules.name(); return (bool)(ret == 0); } return FALSE; } double Accounting::total() { if(rules.minimumCosts() <= _session) return _total + _session; else return _total + rules.minimumCosts(); } double Accounting::session() { if(rules.minimumCosts() <= _session) return _session; else return rules.minimumCosts(); } ExecutableAccounting::ExecutableAccounting(QObject *parent) : AccountingBase(parent), proc(0) { } bool ExecutableAccounting::running() { return (proc != 0) || proc->isRunning(); } bool ExecutableAccounting::loadRuleSet(const char *) { QString s = AccountingBase::getAccountingFile(gpppdata.accountingFile()); return (access(s.data(), X_OK) == 0); } void ExecutableAccounting::gotData(KProcess */*proc*/, char *buffer, int /*buflen*/) { QString field[8]; int nFields = 0; int pos, last_pos = 0; // split string QString b(buffer); pos = b.find(':'); while(pos != -1 && nFields < 8) { field[nFields++] = b.mid(last_pos, pos-last_pos); last_pos = pos+1; pos = b.find(':', last_pos); } for(int i = 0; i < nFields;i++) fprintf(stderr, "FIELD[%d] = %s\n", i, field[i].data()); QString __total, __session; QString s(buffer); int del1, del2, del3; del1 = s.find(':'); del2 = s.find(':', del1+1); del3 = s.find(':', del2+1); if(del1 == -1 || del2 == -1 || del3 == -1) { // TODO: do something usefull here return; } provider = s.left(del1); currency = s.mid(del1, del2-del1); __total = s.mid(del2, del2-del1); __session = s.mid(del3, s.length()-del3+1); bool ok1, ok2; _total = __total.toDouble(&ok1); _session = __session.toDouble(&ok2); if(!ok1 || !ok2) { // TODO: do something usefull here return; } printf("PROVIDER=%s, CURRENCY=%s, TOTAL=%0.3e, SESSION=%0.3e\n", provider.data(), currency.data(), _total, _session); } void ExecutableAccounting::slotStart() { if(proc != 0) slotStop(); // just to make sure loadCosts(); QString s = AccountingBase::getAccountingFile(gpppdata.accountingFile()); proc = new KProcess; QString s_total; s_total.sprintf("%0.8f", total()); *proc << s.data() << s_total.data(); connect(proc, SIGNAL(receivedStdout(KProcess *, char *, int)), this, SLOT(gotData(KProcess *, char *, int))); proc->start(); time_t start_time = time(0); s = timet2qstring(start_time); s += ":"; s += gpppdata.accname(); s += ":"; s += currency; logMessage(s, TRUE); } void ExecutableAccounting::slotStop() { if(proc != 0) { proc->kill(); delete proc; proc = 0; QString s; s.sprintf(":%s:%0.4e:%0.4e:%u:%u\n", timet2qstring(time(0)).data(), session(), total(), stats.ibytes, stats.obytes); logMessage(s, FALSE); saveCosts(); } } #include "accounting.moc" <commit_msg>.kde/share/apps/kppp/LogSep-1999.log and .kde/share/apps/kppp/Log/Sep-1999.log are different ;). Added missing slash.<commit_after>/* -*- C++ -*- * * kPPP: A pppd front end for the KDE project * * $Id$ * * Copyright (C) 1997 Bernd Johannes Wuebben * wuebben@math.cornell.edu * * This file contributed by: Mario Weilguni, <mweilguni@sime.com> * Thanks Mario! * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <unistd.h> #include <sys/stat.h> #include <sys/types.h> #include <qdir.h> #include <qfile.h> #include <qdatetime.h> #include <qregexp.h> #include <qlabel.h> #include <kprogress.h> #include <kglobal.h> #include <kstddirs.h> #include <time.h> #include "accounting.h" #include "kpppconfig.h" #include "pppdata.h" #include "pppstats.h" #include "log.h" // defines the maximum duration until the current costs // are saved again (to prevent loss due to "kill") // specifying -1 disables the features #define UPDATE_TIME (5*60*1000) extern PPPData gpppdata; extern PPPStats stats; ///////////////////////////////////////////////////////////////////////////// // // Helper functions // ///////////////////////////////////////////////////////////////////////////// QString timet2qstring(time_t t) { QString s; s.sprintf("%lu", t); return s; } ///////////////////////////////////////////////////////////////////////////// // // The base class for the accounting system provides a base set of usefull // and common functions, but does not do any accounting by itself. The // accounting is accomplished withing its derived classes // ///////////////////////////////////////////////////////////////////////////// AccountingBase::AccountingBase(QObject *parent) : QObject(parent), _total(0), _session(0) { QDate dt = QDate::currentDate(); LogFileName = QString("%1-%2.log") .arg(dt.monthName(dt.month())) .arg(dt.year(), 4); LogFileName = KGlobal::dirs()->getSaveLocation("appdata", "Log") + "/" + LogFileName; debug("LogFileName: %s", LogFileName.latin1()); } AccountingBase::~AccountingBase() { if(running()) slotStop(); } double AccountingBase::total() { return _total + _session; } double AccountingBase::session() { return _session; } // set costs back to zero ( typically once per month) void AccountingBase::resetCosts(const char *accountname){ QString prev_account = gpppdata.accname(); gpppdata.setAccount(accountname); gpppdata.setTotalCosts(""); gpppdata.setAccount(prev_account); } void AccountingBase::resetVolume(const char *accountname){ QString prev_account = gpppdata.accname(); gpppdata.setAccount(accountname); gpppdata.setTotalBytes(0); gpppdata.setAccount(prev_account); } void AccountingBase::logMessage(QString s, bool newline) { int old_umask = umask(0077); QFile f(LogFileName); bool result = f.open(IO_ReadWrite); if(result) { // move to eof, and place \n if necessary if(f.size() > 0) { if(newline) { f.at(f.size()); char c = 0; f.readBlock(&c, 1); if(c != '\n') f.writeBlock("\n", 1); } else f.at(f.size()); } f.writeBlock(s.data(), s.length()); f.close(); } // restore umask umask(old_umask); } QString AccountingBase::getCosts(const char* accountname) { QString prev_account = gpppdata.accname(); gpppdata.setAccount(accountname); QString val = gpppdata.totalCosts(); gpppdata.setAccount(prev_account); return val; } bool AccountingBase::saveCosts() { if(!_name.isNull() && _name.length() > 0) { QString val; val.setNum(total()); gpppdata.setTotalCosts(val); gpppdata.save(); return TRUE; } else return FALSE; } bool AccountingBase::loadCosts() { QString val = gpppdata.totalCosts(); if(val.isNull()) // QString will segfault if isnull and toDouble called _total = 0.0; else { bool ok; _total = val.toDouble(&ok); if(!ok) _total = 0.0; } return TRUE; } QString AccountingBase::getAccountingFile(const QString &accountname) { QString f = "kppp/Rules/"; f += accountname; QString d = locate("data", f); if(d.isNull()) return ""; else return d; } ///////////////////////////////////////////////////////////////////////////// // // Accounting class for ruleset files // ///////////////////////////////////////////////////////////////////////////// Accounting::Accounting(QObject *parent) : AccountingBase(parent), acct_timer_id(0), update_timer_id(0) { } bool Accounting::running() { return (bool)(acct_timer_id != 0); } void Accounting::timerEvent(QTimerEvent *t) { if(t->timerId() == acct_timer_id) { double newCosts; double newLen; double connect_time = difftime(time(0), start_time); rules.getActiveRule(QDateTime::currentDateTime(), connect_time, newCosts, newLen); if(newLen < 1) { // changed to < 1 slotStop(); return; // no default rule found } // check if we have a new rule. If yes, // kill the timer and restart it with new // duration if((newCosts != _lastcosts) || (newLen != _lastlen)) { Debug("SWITCHING RULES, new costs = %0.2f, new len = %0.2f\n", newCosts, newLen); killTimer(acct_timer_id); if(newLen > 0) acct_timer_id = startTimer((int)(newLen * 1000.0)); _lastlen = newLen; _lastcosts = newCosts; } // emit changed() signal if necessary if(newCosts != 0) { _session += newCosts; emit changed(rules.currencyString(total()), rules.currencyString(session())); } } // if(t->timerId() == acct_timer_id)... if(t->timerId() == update_timer_id) { // just to be sure, save the current costs // every n seconds (see UPDATE_TIME) saveCosts(); } } void Accounting::slotStart() { if(!running()) { loadCosts(); _lastcosts = 0.0; _lastlen = 0.0; _session = rules.perConnectionCosts(); rules.setStartTime(QDateTime::currentDateTime()); acct_timer_id = startTimer(1); if(UPDATE_TIME > 0) update_timer_id = startTimer(UPDATE_TIME); start_time = time(0); QString s; s = timet2qstring(start_time); s += ":"; s += gpppdata.accname(); s += ":"; s += rules.currencySymbol(); logMessage(s, TRUE); } } void Accounting::slotStop() { if(running()) { killTimer(acct_timer_id); if(update_timer_id != 0) killTimer(update_timer_id); acct_timer_id = 0; update_timer_id = 0; QString s; s.sprintf(":%s:%0.4e:%0.4e:%u:%u\n", timet2qstring(time(0)).data(), session(), total(), stats.ibytes, stats.obytes); logMessage(s, FALSE); saveCosts(); } } bool Accounting::loadRuleSet(const char *name) { if(strlen(name) == 0) { rules.load(""); // delete old rules return TRUE; } QString d = AccountingBase::getAccountingFile(name); QFileInfo fg(d); if(fg.exists()) { int ret = rules.load(d.data()); _name = rules.name(); return (bool)(ret == 0); } return FALSE; } double Accounting::total() { if(rules.minimumCosts() <= _session) return _total + _session; else return _total + rules.minimumCosts(); } double Accounting::session() { if(rules.minimumCosts() <= _session) return _session; else return rules.minimumCosts(); } ExecutableAccounting::ExecutableAccounting(QObject *parent) : AccountingBase(parent), proc(0) { } bool ExecutableAccounting::running() { return (proc != 0) || proc->isRunning(); } bool ExecutableAccounting::loadRuleSet(const char *) { QString s = AccountingBase::getAccountingFile(gpppdata.accountingFile()); return (access(s.data(), X_OK) == 0); } void ExecutableAccounting::gotData(KProcess */*proc*/, char *buffer, int /*buflen*/) { QString field[8]; int nFields = 0; int pos, last_pos = 0; // split string QString b(buffer); pos = b.find(':'); while(pos != -1 && nFields < 8) { field[nFields++] = b.mid(last_pos, pos-last_pos); last_pos = pos+1; pos = b.find(':', last_pos); } for(int i = 0; i < nFields;i++) fprintf(stderr, "FIELD[%d] = %s\n", i, field[i].data()); QString __total, __session; QString s(buffer); int del1, del2, del3; del1 = s.find(':'); del2 = s.find(':', del1+1); del3 = s.find(':', del2+1); if(del1 == -1 || del2 == -1 || del3 == -1) { // TODO: do something usefull here return; } provider = s.left(del1); currency = s.mid(del1, del2-del1); __total = s.mid(del2, del2-del1); __session = s.mid(del3, s.length()-del3+1); bool ok1, ok2; _total = __total.toDouble(&ok1); _session = __session.toDouble(&ok2); if(!ok1 || !ok2) { // TODO: do something usefull here return; } printf("PROVIDER=%s, CURRENCY=%s, TOTAL=%0.3e, SESSION=%0.3e\n", provider.data(), currency.data(), _total, _session); } void ExecutableAccounting::slotStart() { if(proc != 0) slotStop(); // just to make sure loadCosts(); QString s = AccountingBase::getAccountingFile(gpppdata.accountingFile()); proc = new KProcess; QString s_total; s_total.sprintf("%0.8f", total()); *proc << s.data() << s_total.data(); connect(proc, SIGNAL(receivedStdout(KProcess *, char *, int)), this, SLOT(gotData(KProcess *, char *, int))); proc->start(); time_t start_time = time(0); s = timet2qstring(start_time); s += ":"; s += gpppdata.accname(); s += ":"; s += currency; logMessage(s, TRUE); } void ExecutableAccounting::slotStop() { if(proc != 0) { proc->kill(); delete proc; proc = 0; QString s; s.sprintf(":%s:%0.4e:%0.4e:%u:%u\n", timet2qstring(time(0)).data(), session(), total(), stats.ibytes, stats.obytes); logMessage(s, FALSE); saveCosts(); } } #include "accounting.moc" <|endoftext|>
<commit_before>#ifndef ITER_ACCUMULATE_H_ #define ITER_ACCUMULATE_H_ #include "internal/iterbase.hpp" #include <utility> #include <iterator> #include <initializer_list> #include <functional> #include <type_traits> #include <memory> namespace iter { namespace impl { template <typename Container, typename AccumulateFunc> class Accumulator; } template <typename Container, typename AccumulateFunc> impl::Accumulator<Container, AccumulateFunc> accumulate( Container&&, AccumulateFunc); template <typename T, typename AccumulateFunc> impl::Accumulator<std::initializer_list<T>, AccumulateFunc> accumulate( std::initializer_list<T>, AccumulateFunc); } template <typename Container, typename AccumulateFunc> class iter::impl::Accumulator { private: Container container; AccumulateFunc accumulate_func; friend Accumulator iter::accumulate<Container, AccumulateFunc>( Container&&, AccumulateFunc); template <typename T, typename AF> friend Accumulator<std::initializer_list<T>, AF> iter::accumulate( std::initializer_list<T>, AF); // AccumVal must be default constructible using AccumVal = typename std::remove_reference<typename std::result_of<AccumulateFunc( iterator_deref<Container>, iterator_deref<Container>)>::type>::type; Accumulator(Container&& in_container, AccumulateFunc in_accumulate_func) : container(std::forward<Container>(in_container)), accumulate_func(in_accumulate_func) {} public: Accumulator(Accumulator&&) = default; class Iterator : public std::iterator<std::input_iterator_tag, AccumVal> { private: iterator_type<Container> sub_iter; iterator_type<Container> sub_end; AccumulateFunc* accumulate_func; std::unique_ptr<AccumVal> acc_val; public: Iterator(iterator_type<Container>&& iter, iterator_type<Container>&& end, AccumulateFunc& in_accumulate_fun) : sub_iter{std::move(iter)}, sub_end{std::move(end)}, accumulate_func(&in_accumulate_fun), // only get first value if not an end iterator acc_val{!(iter != end) ? nullptr : new AccumVal(*iter)} {} Iterator(const Iterator& other) : sub_iter{other.sub_iter}, sub_end{other.sub_end}, accumulate_func{other.accumulate_func}, acc_val{other.acc_val ? new AccumVal(*other.acc_val) : nullptr} {} Iterator& operator=(const Iterator& other) { if (this == &other) return *this; this->sub_iter = other.sub_iter; this->sub_end = other.sub_end; this->accumulate_func = other.accumulate_func; this->acc_val.reset( other.acc_val ? new AccumVal(*other.acc_val) : nullptr); return *this; } Iterator(Iterator&&) = default; Iterator& operator=(Iterator&&) = default; const AccumVal& operator*() const { return *this->acc_val; } const AccumVal* operator->() const { return this->acc_val.get(); } Iterator& operator++() { ++this->sub_iter; if (this->sub_iter != this->sub_end) { *this->acc_val = (*accumulate_func)(*this->acc_val, *this->sub_iter); } return *this; } Iterator operator++(int) { auto ret = *this; ++*this; return ret; } bool operator!=(const Iterator& other) const { return this->sub_iter != other.sub_iter; } bool operator==(const Iterator& other) const { return !(*this != other); } }; Iterator begin() { return {std::begin(this->container), std::end(this->container), this->accumulate_func}; } Iterator end() { return {std::end(this->container), std::end(this->container), this->accumulate_func}; } }; template <typename Container, typename AccumulateFunc> iter::impl::Accumulator<Container, AccumulateFunc> iter::accumulate( Container&& container, AccumulateFunc accumulate_func) { return {std::forward<Container>(container), accumulate_func}; } template <typename T, typename AccumulateFunc> iter::impl::Accumulator<std::initializer_list<T>, AccumulateFunc> iter::accumulate(std::initializer_list<T> il, AccumulateFunc accumulate_func) { return {std::move(il), accumulate_func}; } namespace iter { template <typename Container> auto accumulate(Container&& container) -> decltype(accumulate( std::forward<Container>(container), std::plus<typename std:: remove_reference<impl::iterator_deref<Container>>::type>{})) { return accumulate( std::forward<Container>(container), std::plus<typename std:: remove_reference<impl::iterator_deref<Container>>::type>{}); } template <typename T> auto accumulate(std::initializer_list<T> il) -> decltype(accumulate(std::move(il), std::plus<T>{})) { return accumulate(std::move(il), std::plus<T>{}); } } #endif <commit_msg>fixes clang tidy warnings<commit_after>#ifndef ITER_ACCUMULATE_H_ #define ITER_ACCUMULATE_H_ #include "internal/iterbase.hpp" #include <utility> #include <iterator> #include <initializer_list> #include <functional> #include <type_traits> #include <memory> namespace iter { namespace impl { template <typename Container, typename AccumulateFunc> class Accumulator; } template <typename Container, typename AccumulateFunc> impl::Accumulator<Container, AccumulateFunc> accumulate( Container&&, AccumulateFunc); template <typename T, typename AccumulateFunc> impl::Accumulator<std::initializer_list<T>, AccumulateFunc> accumulate( std::initializer_list<T>, AccumulateFunc); } template <typename Container, typename AccumulateFunc> class iter::impl::Accumulator { private: Container container; AccumulateFunc accumulate_func; friend Accumulator iter::accumulate<Container, AccumulateFunc>( Container&&, AccumulateFunc); template <typename T, typename AF> friend Accumulator<std::initializer_list<T>, AF> iter::accumulate( std::initializer_list<T>, AF); // AccumVal must be default constructible using AccumVal = typename std::remove_reference<typename std::result_of<AccumulateFunc( iterator_deref<Container>, iterator_deref<Container>)>::type>::type; Accumulator(Container&& in_container, AccumulateFunc in_accumulate_func) : container(std::forward<Container>(in_container)), accumulate_func(in_accumulate_func) {} public: Accumulator(Accumulator&&) noexcept = default; class Iterator : public std::iterator<std::input_iterator_tag, AccumVal> { private: iterator_type<Container> sub_iter; iterator_type<Container> sub_end; AccumulateFunc* accumulate_func; std::unique_ptr<AccumVal> acc_val; public: Iterator(iterator_type<Container>&& iter, iterator_type<Container>&& end, AccumulateFunc& in_accumulate_fun) : sub_iter{std::move(iter)}, sub_end{std::move(end)}, accumulate_func(&in_accumulate_fun), // only get first value if not an end iterator acc_val{!(iter != end) ? nullptr : new AccumVal(*iter)} {} Iterator(const Iterator& other) : sub_iter{other.sub_iter}, sub_end{other.sub_end}, accumulate_func{other.accumulate_func}, acc_val{other.acc_val ? new AccumVal(*other.acc_val) : nullptr} {} Iterator& operator=(const Iterator& other) { if (this == &other) { return *this; } this->sub_iter = other.sub_iter; this->sub_end = other.sub_end; this->accumulate_func = other.accumulate_func; this->acc_val.reset( other.acc_val ? new AccumVal(*other.acc_val) : nullptr); return *this; } Iterator(Iterator&&) noexcept = default; Iterator& operator=(Iterator&&) noexcept = default; const AccumVal& operator*() const { return *this->acc_val; } const AccumVal* operator->() const { return this->acc_val.get(); } Iterator& operator++() { ++this->sub_iter; if (this->sub_iter != this->sub_end) { *this->acc_val = (*accumulate_func)(*this->acc_val, *this->sub_iter); } return *this; } Iterator operator++(int) { auto ret = *this; ++*this; return ret; } bool operator!=(const Iterator& other) const { return this->sub_iter != other.sub_iter; } bool operator==(const Iterator& other) const { return !(*this != other); } }; Iterator begin() { return {std::begin(this->container), std::end(this->container), this->accumulate_func}; } Iterator end() { return {std::end(this->container), std::end(this->container), this->accumulate_func}; } }; template <typename Container, typename AccumulateFunc> iter::impl::Accumulator<Container, AccumulateFunc> iter::accumulate( Container&& container, AccumulateFunc accumulate_func) { return {std::forward<Container>(container), accumulate_func}; } template <typename T, typename AccumulateFunc> iter::impl::Accumulator<std::initializer_list<T>, AccumulateFunc> iter::accumulate(std::initializer_list<T> il, AccumulateFunc accumulate_func) { return {std::move(il), accumulate_func}; } namespace iter { template <typename Container> auto accumulate(Container&& container) -> decltype(accumulate( std::forward<Container>(container), std::plus<typename std:: remove_reference<impl::iterator_deref<Container>>::type>{})) { return accumulate( std::forward<Container>(container), std::plus<typename std:: remove_reference<impl::iterator_deref<Container>>::type>{}); } template <typename T> auto accumulate(std::initializer_list<T> il) -> decltype(accumulate(std::move(il), std::plus<T>{})) { return accumulate(std::move(il), std::plus<T>{}); } } #endif <|endoftext|>
<commit_before>//============================================================================================================= /** * @file main.cpp * @author Lorenz Esch <lorenz.esch@tu-ilmenau.de>; * Matti Hamalainen <msh@nmr.mgh.harvard.edu> * @version 1.0 * @date April, 2019 * * @section LICENSE * * Copyright (C) 2019, Lorenz Esch and Matti Hamalainen. 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 MNE-CPP authors 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. * * * @brief Example of using the MNE-CPP Connectivity library * */ //************************************************************************************************************* //============================================================================================================= // INCLUDES //============================================================================================================= #include <connectivity/connectivity.h> #include <connectivity/connectivitysettings.h> #include <connectivity/network/network.h> #include <connectivity/metrics/abstractmetric.h> #include <fiff/fiff_raw_data.h> #include <utils/ioutils.h> #include <mne/mne_epoch_data_list.h> #include <mne/mne.h> #include <stdio.h> //************************************************************************************************************* //============================================================================================================= // QT INCLUDES //============================================================================================================= #include <QDebug> #include <QFile> #include <QDateTime> #include <QDir> #include <QCoreApplication> #include <QHostInfo> //************************************************************************************************************* //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace Eigen; using namespace FIFFLIB; using namespace CONNECTIVITYLIB; using namespace Eigen; using namespace UTILSLIB; using namespace MNELIB; //************************************************************************************************************* //============================================================================================================= // Global Defines //============================================================================================================= QString m_sCurrentDir; int m_iCurrentIteration = 0; int m_iNumberTrials; int m_iNumberChannels; int m_iNumberSamples; void customMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg) { Q_UNUSED(context); QString dt = QDateTime::currentDateTime().toString("dd/MM/yyyy hh:mm:ss"); QString txt;// = QString("[%1] ").arg(dt); bool writeToLog = false; switch (type) { case QtWarningMsg: //txt += QString("{Warning} \t %1").arg(msg); txt += QString("%1").arg(msg); writeToLog=true; break; } if(!writeToLog) { return; } QString sFileName = m_sCurrentDir + "/itr" + QString::number(m_iCurrentIteration) + "_" + QString::number(m_iNumberChannels) + "_" + QString::number(m_iNumberSamples) + "_" + QString::number(m_iNumberTrials) + ".log"; QFile outFile(sFileName); outFile.open(QIODevice::WriteOnly | QIODevice::Append); QTextStream textStream(&outFile); textStream << txt << endl; } //************************************************************************************************************* //============================================================================================================= // MAIN //============================================================================================================= //============================================================================================================= /** * The function main marks the entry point of the program. * By default, main has the storage class extern. * * @param [in] argc (argument count) is an integer that indicates how many arguments were entered on the command line when the program was started. * @param [in] argv (argument vector) is an array of pointers to arrays of character objects. The array objects are null-terminated strings, representing the arguments that were entered on the command line when the program was started. * @return the value that was set to exit() (which is 0 if exit() is called via quit()). */ int main(int argc, char *argv[]) { qInstallMessageHandler(customMessageHandler); //Parameters for performance test QStringList sConnectivityMethodList = QStringList() << "COR" << "XCOR" << "COH" << "IMAGCOH" << "PLI" << "WPLI" << "USPLI" << "DSWPLI" << "PLV"; QList<int> lNumberTrials = QList<int>() << 1 << 5 << 10 << 20 << 50 << 100 << 200; QList<int> lNumberChannels = QList<int>() << 32 << 64 << 128 << 256; QList<int> lNumberSamples = QList<int>() << 100 << 200 << 300 << 400 << 500 << 600 << 700 << 800 << 900 << 1000 << 2000 << 3000 << 4000 << 5000 << 6000 << 7000 << 8000 << 9000 << 10000 << 20000 << 30000 << 40000 << 50000 << 60000 << 70000 << 80000 << 90000 << 100000; int iNumberRepeats = 20; int iStorageModeActive = 0; AbstractMetric::m_bStorageModeIsActive = iStorageModeActive; AbstractMetric::m_iNumberBins = 4; // Create sensor level data QString sRaw = "/cluster/fusion/lesch/Git/mne-cpp-lorenze/bin/MNE-sample-data/MEG/sample/sample_audvis_raw.fif"; MatrixXd matDataOrig, matData; MatrixXd times; QFile t_fileRaw(sRaw); FiffRawData raw(t_fileRaw); raw.read_raw_segment(matDataOrig, times, raw.first_samp, raw.first_samp+100001); //Perform connectivity performance tests Connectivity connectivityObj; ConnectivitySettings connectivitySettings; connectivitySettings.setSamplingFrequency(raw.info.sfreq); connectivitySettings.setWindowType("hanning"); for(int u = 0; u < iNumberRepeats; ++u) { for(int i = 0; i < sConnectivityMethodList.size(); ++i) { for(int j = 0; j < lNumberSamples.size(); ++j) { for(int k = 0; k < lNumberChannels.size(); ++k) { matData = matDataOrig.block(0,0,lNumberChannels.at(k), lNumberSamples.at(j)); RowVectorXi picks = RowVectorXi::LinSpaced(lNumberChannels.at(k),1,lNumberChannels.at(k)+1); connectivitySettings.setNodePositions(raw.info, picks); for(int l = 0; l < lNumberTrials.size(); ++l) { m_iNumberTrials = lNumberTrials.at(l); m_iNumberChannels = lNumberChannels.at(k); m_iNumberSamples = lNumberSamples.at(j); //Create new folder m_sCurrentDir = QString("/cluster/fusion/lesch/connectivity_performance_%1_%2_%3/%4/%5_%6_%7").arg(QHostInfo::localHostName()).arg(AbstractMetric::m_iNumberBins).arg(iStorageModeActive).arg(sConnectivityMethodList.at(i)).arg(QString::number(lNumberChannels.at(k))).arg(QString::number(lNumberSamples.at(j))).arg(QString::number(lNumberTrials.at(l))); QDir().mkpath(m_sCurrentDir); //Write basic information to file qWarning() << "sConnectivityMethod" << sConnectivityMethodList.at(i); qWarning() << "sRaw" << sRaw; qWarning() << "storageModeActive" << iStorageModeActive; qWarning() << "iteration" << m_iCurrentIteration; qWarning() << "iNumberSamples" << lNumberSamples.at(j); qWarning() << "iNumberChannels" << lNumberChannels.at(k); qWarning() << "iNumberTrials" << lNumberTrials.at(l); qWarning() << "iNumberCSDFreqBins" << AbstractMetric::m_iNumberBins; qWarning() << "rows" << matData.rows(); qWarning() << "cols" << matData.cols(); qWarning() << "picks" << picks.cols(); qWarning() << "numberNodes" << connectivitySettings.getNodePositions().rows(); // Check that iNfft >= signal length int iSignalLength = lNumberSamples.at(j); int iNfft = int(raw.info.sfreq/1.0); if(iNfft > iSignalLength) { iNfft = iSignalLength; } qWarning() << "iNfft" << iNfft; int iNFreqs = int(floor(iNfft / 2.0)) + 1; qWarning() << "iNFreqs" << iNFreqs; //Create data to work on connectivitySettings.clearAllData(); for(int p = 0; p < lNumberTrials.at(l); ++p) { connectivitySettings.append(matData); } connectivitySettings.setConnectivityMethods(QStringList() << sConnectivityMethodList.at(i)); //Do connectivity estimation connectivityObj.calculate(connectivitySettings); printf("Iteration %d: Calculating %s for %d trials, %d channels, %d samples\n", m_iCurrentIteration, sConnectivityMethodList.at(i).toLatin1().data(), lNumberTrials.at(l), lNumberChannels.at(k), lNumberSamples.at(j)); } } } } m_iCurrentIteration++; } return 0; } <commit_msg>work on performance example<commit_after>//============================================================================================================= /** * @file main.cpp * @author Lorenz Esch <lorenz.esch@tu-ilmenau.de>; * Matti Hamalainen <msh@nmr.mgh.harvard.edu> * @version 1.0 * @date April, 2019 * * @section LICENSE * * Copyright (C) 2019, Lorenz Esch and Matti Hamalainen. 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 MNE-CPP authors 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. * * * @brief Example of using the MNE-CPP Connectivity library * */ //************************************************************************************************************* //============================================================================================================= // INCLUDES //============================================================================================================= #include <connectivity/connectivity.h> #include <connectivity/connectivitysettings.h> #include <connectivity/network/network.h> #include <connectivity/metrics/abstractmetric.h> #include <fiff/fiff_raw_data.h> #include <utils/ioutils.h> #include <mne/mne_epoch_data_list.h> #include <mne/mne.h> #include <stdio.h> //************************************************************************************************************* //============================================================================================================= // QT INCLUDES //============================================================================================================= #include <QDebug> #include <QFile> #include <QDateTime> #include <QDir> #include <QCoreApplication> #include <QHostInfo> //************************************************************************************************************* //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace Eigen; using namespace FIFFLIB; using namespace CONNECTIVITYLIB; using namespace Eigen; using namespace UTILSLIB; using namespace MNELIB; //************************************************************************************************************* //============================================================================================================= // Global Defines //============================================================================================================= QString m_sCurrentDir; int m_iCurrentIteration = 0; int m_iNumberTrials; int m_iNumberChannels; int m_iNumberSamples; void customMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg) { Q_UNUSED(context); QString dt = QDateTime::currentDateTime().toString("dd/MM/yyyy hh:mm:ss"); QString txt;// = QString("[%1] ").arg(dt); bool writeToLog = false; switch (type) { case QtWarningMsg: //txt += QString("{Warning} \t %1").arg(msg); txt += QString("%1").arg(msg); writeToLog=true; break; } if(!writeToLog) { return; } QString sFileName = m_sCurrentDir + "/itr" + QString::number(m_iCurrentIteration) + "_" + QString::number(m_iNumberChannels) + "_" + QString::number(m_iNumberSamples) + "_" + QString::number(m_iNumberTrials) + ".log"; QFile outFile(sFileName); outFile.open(QIODevice::WriteOnly | QIODevice::Append); QTextStream textStream(&outFile); textStream << txt << endl; } //************************************************************************************************************* //============================================================================================================= // MAIN //============================================================================================================= //============================================================================================================= /** * The function main marks the entry point of the program. * By default, main has the storage class extern. * * @param [in] argc (argument count) is an integer that indicates how many arguments were entered on the command line when the program was started. * @param [in] argv (argument vector) is an array of pointers to arrays of character objects. The array objects are null-terminated strings, representing the arguments that were entered on the command line when the program was started. * @return the value that was set to exit() (which is 0 if exit() is called via quit()). */ int main(int argc, char *argv[]) { qInstallMessageHandler(customMessageHandler); //Parameters for performance test QStringList sConnectivityMethodList = QStringList() << "COR" << "XCOR" << "COH" << "IMAGCOH" << "PLI" << "WPLI" << "USPLI" << "DSWPLI" << "PLV"; QList<int> lNumberTrials = QList<int>() << 1 << 5 << 10 << 20 << 50 << 100 << 200; QList<int> lNumberChannels = QList<int>() << 32 << 64 << 128 << 256; QList<int> lNumberSamples = QList<int>() << 100 << 200 << 300 << 400 << 500 << 600 << 700 << 800 << 900 << 1000 << 2000 << 3000 << 4000 << 5000 << 6000 << 7000 << 8000 << 9000 << 10000 << 20000 << 30000 << 40000 << 50000 << 60000 << 70000 << 80000 << 90000 << 100000; int iNumberRepeats = 10; int iStorageModeActive = 0; AbstractMetric::m_bStorageModeIsActive = iStorageModeActive; AbstractMetric::m_iNumberBins = 4; // Create sensor level data QString sRaw = "/cluster/fusion/lesch/Git/mne-cpp-lorenze/bin/MNE-sample-data/MEG/sample/sample_audvis_raw.fif"; MatrixXd matDataOrig, matData; MatrixXd times; QFile t_fileRaw(sRaw); FiffRawData raw(t_fileRaw); raw.read_raw_segment(matDataOrig, times, raw.first_samp, raw.first_samp+100001); //Perform connectivity performance tests Connectivity connectivityObj; ConnectivitySettings connectivitySettings; connectivitySettings.setSamplingFrequency(raw.info.sfreq); connectivitySettings.setWindowType("hanning"); for(int u = 0; u < iNumberRepeats; ++u) { for(int i = 0; i < sConnectivityMethodList.size(); ++i) { for(int j = 0; j < lNumberSamples.size(); ++j) { for(int k = 0; k < lNumberChannels.size(); ++k) { matData = matDataOrig.block(0,0,lNumberChannels.at(k), lNumberSamples.at(j)); RowVectorXi picks = RowVectorXi::LinSpaced(lNumberChannels.at(k),1,lNumberChannels.at(k)+1); connectivitySettings.setNodePositions(raw.info, picks); for(int l = 0; l < lNumberTrials.size(); ++l) { m_iNumberTrials = lNumberTrials.at(l); m_iNumberChannels = lNumberChannels.at(k); m_iNumberSamples = lNumberSamples.at(j); //Create new folder m_sCurrentDir = QString("/homes/8/lesch/connectivity_performance_%1_%2_%3/%4/%5_%6_%7").arg(QHostInfo::localHostName()).arg(AbstractMetric::m_iNumberBins).arg(iStorageModeActive).arg(sConnectivityMethodList.at(i)).arg(QString::number(lNumberChannels.at(k))).arg(QString::number(lNumberSamples.at(j))).arg(QString::number(lNumberTrials.at(l))); QDir().mkpath(m_sCurrentDir); //Write basic information to file qWarning() << "sConnectivityMethod" << sConnectivityMethodList.at(i); qWarning() << "sRaw" << sRaw; qWarning() << "storageModeActive" << iStorageModeActive; qWarning() << "iteration" << m_iCurrentIteration; qWarning() << "iNumberSamples" << lNumberSamples.at(j); qWarning() << "iNumberChannels" << lNumberChannels.at(k); qWarning() << "iNumberTrials" << lNumberTrials.at(l); qWarning() << "iNumberCSDFreqBins" << AbstractMetric::m_iNumberBins; qWarning() << "rows" << matData.rows(); qWarning() << "cols" << matData.cols(); qWarning() << "picks" << picks.cols(); qWarning() << "numberNodes" << connectivitySettings.getNodePositions().rows(); // Check that iNfft >= signal length int iSignalLength = lNumberSamples.at(j); int iNfft = int(raw.info.sfreq/1.0); if(iNfft > iSignalLength) { iNfft = iSignalLength; } qWarning() << "iNfft" << iNfft; int iNFreqs = int(floor(iNfft / 2.0)) + 1; qWarning() << "iNFreqs" << iNFreqs; //Create data to work on connectivitySettings.clearAllData(); for(int p = 0; p < lNumberTrials.at(l); ++p) { connectivitySettings.append(matData); } connectivitySettings.setConnectivityMethods(QStringList() << sConnectivityMethodList.at(i)); //Do connectivity estimation connectivityObj.calculate(connectivitySettings); printf("Iteration %d: Calculating %s for %d trials, %d channels, %d samples\n", m_iCurrentIteration, sConnectivityMethodList.at(i).toLatin1().data(), lNumberTrials.at(l), lNumberChannels.at(k), lNumberSamples.at(j)); } } } } m_iCurrentIteration++; } return 0; } <|endoftext|>
<commit_before>#include "../stkpl/StkPl.h" #include "StkProperties.h" class StkProperties::Impl { public: char PropertyName[256][256]; char PropertyValue[256][256]; int NumOfProperties; }; StkProperties::StkProperties() { pImpl = new Impl; pImpl->NumOfProperties = 0; } StkProperties::~StkProperties() { delete pImpl; } // Get properties from the specified file name // FileName [in] : Target file name which you want to get properties. Do not specify path. The file is searched from Module existing folder. // Return : Result code 0:Success, -1:Failure int StkProperties::GetProperties(const wchar_t* FileName) { wchar_t Buf[FILENAME_MAX]; StkPlGetFullPathFromFileName(FileName, Buf); size_t WorkDatLength = StkPlGetFileSize(Buf); if (WorkDatLength == 0) { return 0; } if (WorkDatLength == (size_t)-1) { #ifndef WIN32 StkPlSwPrintf(Buf, FILENAME_MAX, L"/etc/%s", FileName); WorkDatLength = StkPlGetFileSize(Buf); if (WorkDatLength == (size_t)-1) { return-1; } #else return -1; #endif } char* WorkDat = new char[WorkDatLength + 1]; StkPlReadFile(Buf, WorkDat, WorkDatLength); WorkDat[WorkDatLength] = '\0'; // set line char PropertyLine[64][256]; char* WorkDatAddr = WorkDat; char* WorkDatEnd = WorkDat + WorkDatLength; int Loop; for (Loop = 0; Loop < 64; Loop++) { for (; WorkDatAddr < WorkDatEnd; WorkDatAddr++) { if ((*WorkDatAddr != '\n') && (*WorkDatAddr != '\r') && (*WorkDatAddr != '\t') && (*WorkDatAddr != ' ')) { break; } } char* Start = (char*)WorkDatAddr; for (; WorkDatAddr < WorkDatEnd; WorkDatAddr++) { if (*WorkDatAddr == '\n' || *WorkDatAddr == '\r') { break; } } *WorkDatAddr = '\0'; if (WorkDatAddr >= WorkDatEnd) { break; } if (StkPlStrLen(Start) < 256) { StkPlStrCpy(PropertyLine[Loop], 256, (char*)Start); } else { Loop--; } WorkDatAddr++; } Loop++; delete WorkDat; // Acquire property name and value for (int PrLoop = 0; PrLoop < Loop; PrLoop++) { int ChLoop = 0; if (StkPlStrStr(PropertyLine[PrLoop], "=") == 0) { continue; } int PName = 0; for (; ChLoop < (int)StkPlStrLen(PropertyLine[PrLoop]); ChLoop++) { if (PropertyLine[PrLoop][ChLoop] != ' ' && PropertyLine[PrLoop][ChLoop] != '=' && PropertyLine[PrLoop][ChLoop] != '\t') { pImpl->PropertyName[pImpl->NumOfProperties][PName] = PropertyLine[PrLoop][ChLoop]; PName++; } else { break; } } pImpl->PropertyName[pImpl->NumOfProperties][PName] = '\0'; // If length of property name is zero, proceed to next line. if (StkPlStrLen(pImpl->PropertyName[pImpl->NumOfProperties]) == 0) { continue; } // If same property name has already been registered, proceed to next line. bool Found = false; for (int Lp = 0; Lp < pImpl->NumOfProperties; Lp++) { if (StkPlStrCmp(pImpl->PropertyName[Lp], pImpl->PropertyName[pImpl->NumOfProperties]) == 0) { Found = true; break; } } if (Found == true) { continue; } for (; ChLoop < (int)StkPlStrLen(PropertyLine[PrLoop]); ChLoop++) { if (PropertyLine[PrLoop][ChLoop] != ' ' && PropertyLine[PrLoop][ChLoop] != '=' && PropertyLine[PrLoop][ChLoop] != '\t') { break; } } int PValue = 0; for (; ChLoop < (int)StkPlStrLen(PropertyLine[PrLoop]); ChLoop++) { pImpl->PropertyValue[pImpl->NumOfProperties][PValue] = PropertyLine[PrLoop][ChLoop]; PValue++; } pImpl->PropertyValue[pImpl->NumOfProperties][PValue] = '\0'; pImpl->NumOfProperties++; } return 0; } // This method acquires the value of the specified property name // Value [out] : Acquired value (int) // Return : Reault code, 0:Success, -1:Failure int StkProperties::GetPropertyInt(const char* PropName, int* Value) { for (int Loop = 0; Loop < pImpl->NumOfProperties; Loop++) { if (StkPlStrCmp(PropName, pImpl->PropertyName[Loop]) == 0) { *Value = StkPlAtoi(pImpl->PropertyValue[Loop]); return 0; } } return -1; } // This method acquires the value of the specified property name // Value [out] : Acquired value (char[256]) // Return : Reault code, 0:Success, -1:Failure int StkProperties::GetPropertyStr(const char* PropName, char Value[256]) { for (int Loop = 0; Loop < pImpl->NumOfProperties; Loop++) { if (StkPlStrCmp(PropName, pImpl->PropertyName[Loop]) == 0) { StkPlStrCpy(Value, 256, pImpl->PropertyValue[Loop]); return 0; } } return -1; } <commit_msg>#83 : %s --> %S<commit_after>#include "../stkpl/StkPl.h" #include "StkProperties.h" class StkProperties::Impl { public: char PropertyName[256][256]; char PropertyValue[256][256]; int NumOfProperties; }; StkProperties::StkProperties() { pImpl = new Impl; pImpl->NumOfProperties = 0; } StkProperties::~StkProperties() { delete pImpl; } // Get properties from the specified file name // FileName [in] : Target file name which you want to get properties. Do not specify path. The file is searched from Module existing folder. // Return : Result code 0:Success, -1:Failure int StkProperties::GetProperties(const wchar_t* FileName) { wchar_t Buf[FILENAME_MAX]; StkPlGetFullPathFromFileName(FileName, Buf); size_t WorkDatLength = StkPlGetFileSize(Buf); if (WorkDatLength == 0) { return 0; } if (WorkDatLength == (size_t)-1) { #ifndef WIN32 StkPlSwPrintf(Buf, FILENAME_MAX, L"/etc/%S", FileName); WorkDatLength = StkPlGetFileSize(Buf); if (WorkDatLength == (size_t)-1) { return-1; } #else return -1; #endif } char* WorkDat = new char[WorkDatLength + 1]; StkPlReadFile(Buf, WorkDat, WorkDatLength); WorkDat[WorkDatLength] = '\0'; // set line char PropertyLine[64][256]; char* WorkDatAddr = WorkDat; char* WorkDatEnd = WorkDat + WorkDatLength; int Loop; for (Loop = 0; Loop < 64; Loop++) { for (; WorkDatAddr < WorkDatEnd; WorkDatAddr++) { if ((*WorkDatAddr != '\n') && (*WorkDatAddr != '\r') && (*WorkDatAddr != '\t') && (*WorkDatAddr != ' ')) { break; } } char* Start = (char*)WorkDatAddr; for (; WorkDatAddr < WorkDatEnd; WorkDatAddr++) { if (*WorkDatAddr == '\n' || *WorkDatAddr == '\r') { break; } } *WorkDatAddr = '\0'; if (WorkDatAddr >= WorkDatEnd) { break; } if (StkPlStrLen(Start) < 256) { StkPlStrCpy(PropertyLine[Loop], 256, (char*)Start); } else { Loop--; } WorkDatAddr++; } Loop++; delete WorkDat; // Acquire property name and value for (int PrLoop = 0; PrLoop < Loop; PrLoop++) { int ChLoop = 0; if (StkPlStrStr(PropertyLine[PrLoop], "=") == 0) { continue; } int PName = 0; for (; ChLoop < (int)StkPlStrLen(PropertyLine[PrLoop]); ChLoop++) { if (PropertyLine[PrLoop][ChLoop] != ' ' && PropertyLine[PrLoop][ChLoop] != '=' && PropertyLine[PrLoop][ChLoop] != '\t') { pImpl->PropertyName[pImpl->NumOfProperties][PName] = PropertyLine[PrLoop][ChLoop]; PName++; } else { break; } } pImpl->PropertyName[pImpl->NumOfProperties][PName] = '\0'; // If length of property name is zero, proceed to next line. if (StkPlStrLen(pImpl->PropertyName[pImpl->NumOfProperties]) == 0) { continue; } // If same property name has already been registered, proceed to next line. bool Found = false; for (int Lp = 0; Lp < pImpl->NumOfProperties; Lp++) { if (StkPlStrCmp(pImpl->PropertyName[Lp], pImpl->PropertyName[pImpl->NumOfProperties]) == 0) { Found = true; break; } } if (Found == true) { continue; } for (; ChLoop < (int)StkPlStrLen(PropertyLine[PrLoop]); ChLoop++) { if (PropertyLine[PrLoop][ChLoop] != ' ' && PropertyLine[PrLoop][ChLoop] != '=' && PropertyLine[PrLoop][ChLoop] != '\t') { break; } } int PValue = 0; for (; ChLoop < (int)StkPlStrLen(PropertyLine[PrLoop]); ChLoop++) { pImpl->PropertyValue[pImpl->NumOfProperties][PValue] = PropertyLine[PrLoop][ChLoop]; PValue++; } pImpl->PropertyValue[pImpl->NumOfProperties][PValue] = '\0'; pImpl->NumOfProperties++; } return 0; } // This method acquires the value of the specified property name // Value [out] : Acquired value (int) // Return : Reault code, 0:Success, -1:Failure int StkProperties::GetPropertyInt(const char* PropName, int* Value) { for (int Loop = 0; Loop < pImpl->NumOfProperties; Loop++) { if (StkPlStrCmp(PropName, pImpl->PropertyName[Loop]) == 0) { *Value = StkPlAtoi(pImpl->PropertyValue[Loop]); return 0; } } return -1; } // This method acquires the value of the specified property name // Value [out] : Acquired value (char[256]) // Return : Reault code, 0:Success, -1:Failure int StkProperties::GetPropertyStr(const char* PropName, char Value[256]) { for (int Loop = 0; Loop < pImpl->NumOfProperties; Loop++) { if (StkPlStrCmp(PropName, pImpl->PropertyName[Loop]) == 0) { StkPlStrCpy(Value, 256, pImpl->PropertyValue[Loop]); return 0; } } return -1; } <|endoftext|>
<commit_before>// minimal set of files to be linked with a compiled database #include "../journal/File.cpp" #include "../journal/Generic_File.cpp" #include "../journal/Journal_File.cpp" #include "../journal/Readonly_Journal.cpp" #include "../journal/Stream_File.cpp" <commit_msg>Writeable.cpp in minimal_runtime.cpp<commit_after>// minimal set of files to be linked with a compiled database #include "../interpreter/abstract/Writeable.cpp" #include "../journal/File.cpp" #include "../journal/Generic_File.cpp" #include "../journal/Journal_File.cpp" #include "../journal/Readonly_Journal.cpp" #include "../journal/Stream_File.cpp" <|endoftext|>
<commit_before>#include "aio_private.h" #define AIO_DEPTH (40 * num_open_files() / nthreads) #define EVEN_DISTRIBUTE const int MAX_BUF_REQS = 1024 * 3; /* * each file gets the same number of outstanding requests. */ #ifdef EVEN_DISTRIBUTE #define MAX_OUTSTANDING_NREQS (AIO_DEPTH / num_open_files()) #define ALLOW_DROP #endif void aio_callback(io_context_t ctx, struct iocb* iocb, struct io_callback_s *cb, long res, long res2) { thread_callback_s *tcb = (thread_callback_s *) cb; tcb->thread->return_cb(tcb); } aio_private::aio_private(const char *names[], int num, long size, int idx, int entry_size): read_private(names, num, size, idx, entry_size, O_DIRECT | O_RDONLY) { printf("aio is used\n"); buf_idx = 0; ctx = create_aio_ctx(AIO_DEPTH); for (int i = 0; i < AIO_DEPTH * 5; i++) { cbs.push_back(new thread_callback_s()); } } void aio_private::cleanup() { int slot = max_io_slot(ctx); while (slot < AIO_DEPTH) { io_wait(ctx, NULL); slot = max_io_slot(ctx); } read_private::cleanup(); } aio_private::~aio_private() { cleanup(); } struct iocb *aio_private::construct_req(char *buf, off_t offset, ssize_t size, int access_method, callback_t cb_func, thread_private *initiator, void *priv) { struct iocb *req = NULL; if (cbs.empty()) { fprintf(stderr, "no callback object left\n"); return NULL; } thread_callback_s *tcb = cbs.front(); io_callback_s *cb = (io_callback_s *) tcb; cbs.pop_front(); cb->buf = buf; cb->offset = offset; cb->size = size; cb->func = cb_func; tcb->thread = this; tcb->priv = priv; assert(size >= MIN_BLOCK_SIZE); assert(size % MIN_BLOCK_SIZE == 0); assert(offset % MIN_BLOCK_SIZE == 0); assert((long) buf % MIN_BLOCK_SIZE == 0); req = make_io_request(ctx, get_fd(offset), size, offset, buf, A_READ, cb); return req; } ssize_t aio_private::access(char *buf, off_t offset, ssize_t size, int access_method) { struct iocb *req; int slot = max_io_slot(ctx); assert(access_method == READ); if (slot == 0) { io_wait(ctx, NULL); } /* the initiator of the request must be itself. */ req = construct_req(buf, offset, size, access_method, aio_callback, this, NULL); submit_io_request(ctx, &req, 1); return 0; } ssize_t aio_private::access(io_request *requests, int num, int access_method) { ssize_t ret = 0; while (num > 0) { int slot = max_io_slot(ctx); if (slot == 0) { io_wait(ctx, NULL, 10); slot = max_io_slot(ctx); } struct iocb *reqs[slot]; int min = slot > num ? num : slot; for (int i = 0; i < min; i++) { reqs[i] = construct_req(requests->get_buf(), requests->get_offset(), requests->get_size(), requests->get_access_method(), aio_callback, /* * The initiator thread is normally itself. * However, if the request is received from * another thread with message passing, * it will be another thread. */ requests->get_thread(), requests->get_priv()); ret += requests->get_size(); requests++; } submit_io_request(ctx, reqs, min); num -= min; } return ret; } <commit_msg>fix a minor bug in aio_private.<commit_after>#include "aio_private.h" #define AIO_DEPTH (40 * num_open_files() / nthreads) #define EVEN_DISTRIBUTE const int MAX_BUF_REQS = 1024 * 3; /* * each file gets the same number of outstanding requests. */ #ifdef EVEN_DISTRIBUTE #define MAX_OUTSTANDING_NREQS (AIO_DEPTH / num_open_files()) #define ALLOW_DROP #endif void aio_callback(io_context_t ctx, struct iocb* iocb, struct io_callback_s *cb, long res, long res2) { thread_callback_s *tcb = (thread_callback_s *) cb; tcb->thread->return_cb(tcb); } aio_private::aio_private(const char *names[], int num, long size, int idx, int entry_size): read_private(names, num, size, idx, entry_size, O_DIRECT | O_RDONLY) { printf("aio is used\n"); buf_idx = 0; ctx = create_aio_ctx(AIO_DEPTH); for (int i = 0; i < AIO_DEPTH * 5; i++) { cbs.push_back(new thread_callback_s()); } } void aio_private::cleanup() { int slot = max_io_slot(ctx); while (slot < AIO_DEPTH) { io_wait(ctx, NULL); slot = max_io_slot(ctx); } read_private::cleanup(); } aio_private::~aio_private() { cleanup(); } struct iocb *aio_private::construct_req(char *buf, off_t offset, ssize_t size, int access_method, callback_t cb_func, thread_private *initiator, void *priv) { struct iocb *req = NULL; if (cbs.empty()) { fprintf(stderr, "no callback object left\n"); return NULL; } thread_callback_s *tcb = cbs.front(); io_callback_s *cb = (io_callback_s *) tcb; cbs.pop_front(); cb->buf = buf; cb->offset = offset; cb->size = size; cb->func = cb_func; tcb->thread = this; tcb->initiator = initiator; tcb->priv = priv; assert(size >= MIN_BLOCK_SIZE); assert(size % MIN_BLOCK_SIZE == 0); assert(offset % MIN_BLOCK_SIZE == 0); assert((long) buf % MIN_BLOCK_SIZE == 0); req = make_io_request(ctx, get_fd(offset), size, offset, buf, A_READ, cb); return req; } ssize_t aio_private::access(char *buf, off_t offset, ssize_t size, int access_method) { struct iocb *req; int slot = max_io_slot(ctx); assert(access_method == READ); if (slot == 0) { io_wait(ctx, NULL); } /* the initiator of the request must be itself. */ req = construct_req(buf, offset, size, access_method, aio_callback, this, NULL); submit_io_request(ctx, &req, 1); return 0; } ssize_t aio_private::access(io_request *requests, int num, int access_method) { ssize_t ret = 0; while (num > 0) { int slot = max_io_slot(ctx); if (slot == 0) { io_wait(ctx, NULL, 10); slot = max_io_slot(ctx); } struct iocb *reqs[slot]; int min = slot > num ? num : slot; for (int i = 0; i < min; i++) { reqs[i] = construct_req(requests->get_buf(), requests->get_offset(), requests->get_size(), requests->get_access_method(), aio_callback, /* * The initiator thread is normally itself. * However, if the request is received from * another thread with message passing, * it will be another thread. */ requests->get_thread(), requests->get_priv()); ret += requests->get_size(); requests++; } submit_io_request(ctx, reqs, min); num -= min; } return ret; } <|endoftext|>
<commit_before>// // Created by wahba on 18/08/17. // #include <iostream> #include <utility> #include <unordered_map> #include "alarmWatch.h" class duration; using namespace std::chrono_literals; alarmWatch::alarmWatch() : _runningFlag(false) { stopWatch(); } void alarmWatch::alarmEvery(int repeats, std::chrono::duration<float, std::ratio<1, 100000000>> __timeD, std::function<void()> callableFunc) { //catch if we call for zero duration if (__timeD <= __timeD.zero()) { return; } _callableFunc = std::move(callableFunc); _runningFlag = true; _alarmThread = new std::thread( [this, __timeD, repeats]() { while (_runningFlag) { startWatch(); for (int x = 0; x <= repeats; x++) { std::this_thread::sleep_for(__timeD); _callableFunc(); if (!_runningFlag) { watchStop(); return; } } watchStop(); _runningFlag = !_runningFlag; } }); } /*! * If on it will change the running flag * forcing the working thread to return */ void alarmWatch::alarmKill() { //check if the thread is running and if so //join it if (alarmRunning()) { _runningFlag = !_runningFlag; if (_alarmThread->joinable()) { _alarmThread->join(); } } } /*! * indicates whether the alarm is on or off * @return thread's joinable status, thus telling us if its working or not */ bool alarmWatch::alarmRunning() { return _runningFlag; } <commit_msg>removed duration class<commit_after>// // Created by wahba on 18/08/17. // #include <iostream> #include <utility> #include <unordered_map> #include "alarmWatch.h" using namespace std::chrono_literals; alarmWatch::alarmWatch() : _runningFlag(false) { stopWatch(); } void alarmWatch::alarmEvery(int repeats, std::chrono::duration<float, std::ratio<1, 100000000>> __timeD, std::function<void()> callableFunc) { //catch if we call for zero duration if (__timeD <= __timeD.zero()) { return; } _callableFunc = std::move(callableFunc); _runningFlag = true; _alarmThread = new std::thread( [this, __timeD, repeats]() { while (_runningFlag) { startWatch(); for (int x = 0; x <= repeats; x++) { std::this_thread::sleep_for(__timeD); _callableFunc(); if (!_runningFlag) { watchStop(); return; } } watchStop(); _runningFlag = !_runningFlag; } }); } /*! * If on it will change the running flag * forcing the working thread to return */ void alarmWatch::alarmKill() { //check if the thread is running and if so //join it if (alarmRunning()) { _runningFlag = !_runningFlag; if (_alarmThread->joinable()) { _alarmThread->join(); } } } /*! * indicates whether the alarm is on or off * @return thread's joinable status, thus telling us if its working or not */ bool alarmWatch::alarmRunning() { return _runningFlag; } <|endoftext|>
<commit_before>// Copyright 2010-2012 RethinkDB, all rights reserved. #ifndef CONTAINERS_INTRUSIVE_PTR_HPP_ #define CONTAINERS_INTRUSIVE_PTR_HPP_ #include <stddef.h> #include <stdint.h> #include "errors.hpp" // Yes, this is a clone of boost::intrusive_ptr. This will probably // not be the case in the future. // Now it supports .unique(), and in order to use it, your type needs // to provide an intrusive_ptr_use_count implementation. template <class T> class intrusive_ptr_t { public: intrusive_ptr_t() : p_(NULL) { } explicit intrusive_ptr_t(T *p) : p_(p) { if (p_) { intrusive_ptr_add_ref(p_); } } intrusive_ptr_t(const intrusive_ptr_t &copyee) : p_(copyee.p_) { if (p_) { intrusive_ptr_add_ref(p_); } } ~intrusive_ptr_t() { if (p_) { intrusive_ptr_release(p_); } } void swap(intrusive_ptr_t &other) { T *tmp = p_; p_ = other.p_; other.p_ = tmp; } intrusive_ptr_t &operator=(const intrusive_ptr_t &other) { intrusive_ptr_t tmp(other); swap(tmp); return *this; } void reset() { intrusive_ptr_t tmp; swap(tmp); } void reset(T *other) { intrusive_ptr_t tmp(other); swap(tmp); // NOLINT } T *operator->() const { return p_; } T &operator*() const { return *p_; } T *get() const { return p_; } bool has() const { return p_ != NULL; } bool unique() const { return intrusive_ptr_use_count(p_) == 1; } class hidden_t { hidden_t(); }; typedef void booleanesque_t(hidden_t); operator booleanesque_t*() const { return p_ ? &intrusive_ptr_t<T>::dummy_method : 0; } private: static void dummy_method(hidden_t) { } T *p_; }; template <class> class slow_shared_mixin_t; template <class T> inline void intrusive_ptr_add_ref(slow_shared_mixin_t<T> *p); template <class T> inline void intrusive_ptr_release(slow_shared_mixin_t<T> *p); template <class T> inline intptr_t intrusive_ptr_use_count(const slow_shared_mixin_t<T> *p); template <class T> class slow_shared_mixin_t { public: slow_shared_mixin_t() : refcount_(0) { } protected: ~slow_shared_mixin_t() { } private: friend void intrusive_ptr_add_ref<T>(slow_shared_mixin_t<T> *p); friend void intrusive_ptr_release<T>(slow_shared_mixin_t<T> *p); friend intptr_t intrusive_ptr_use_count<T>(const slow_shared_mixin_t<T> *p); intptr_t refcount_; DISABLE_COPYING(slow_shared_mixin_t); }; template <class T> inline void intrusive_ptr_add_ref(slow_shared_mixin_t<T> *p) { DEBUG_VAR intptr_t res = __sync_add_and_fetch(&p->refcount_, 1); rassert(res > 0); } template <class T> inline void intrusive_ptr_release(slow_shared_mixin_t<T> *p) { intptr_t res = __sync_sub_and_fetch(&p->refcount_, 1); rassert(res >= 0); if (res == 0) { delete static_cast<T *>(p); } } template <class T> inline intptr_t intrusive_ptr_use_count(const slow_shared_mixin_t<T> *p) { // Finally a practical use for volatile. intptr_t tmp = static_cast<const volatile intptr_t&>(p->refcount_); rassert(tmp > 0); return tmp; } #endif // CONTAINERS_INTRUSIVE_PTR_HPP_ <commit_msg>Added single_threaded_shared_mixin_t (for use with intrusive_ptr_t).<commit_after>// Copyright 2010-2012 RethinkDB, all rights reserved. #ifndef CONTAINERS_INTRUSIVE_PTR_HPP_ #define CONTAINERS_INTRUSIVE_PTR_HPP_ #include <stddef.h> #include <stdint.h> #include "errors.hpp" // Yes, this is a clone of boost::intrusive_ptr. This will probably // not be the case in the future. // Now it supports .unique(), and in order to use it, your type needs // to provide an intrusive_ptr_use_count implementation. template <class T> class intrusive_ptr_t { public: intrusive_ptr_t() : p_(NULL) { } explicit intrusive_ptr_t(T *p) : p_(p) { if (p_) { intrusive_ptr_add_ref(p_); } } intrusive_ptr_t(const intrusive_ptr_t &copyee) : p_(copyee.p_) { if (p_) { intrusive_ptr_add_ref(p_); } } ~intrusive_ptr_t() { if (p_) { intrusive_ptr_release(p_); } } void swap(intrusive_ptr_t &other) { T *tmp = p_; p_ = other.p_; other.p_ = tmp; } intrusive_ptr_t &operator=(const intrusive_ptr_t &other) { intrusive_ptr_t tmp(other); swap(tmp); return *this; } void reset() { intrusive_ptr_t tmp; swap(tmp); } void reset(T *other) { intrusive_ptr_t tmp(other); swap(tmp); // NOLINT } T *operator->() const { return p_; } T &operator*() const { return *p_; } T *get() const { return p_; } bool has() const { return p_ != NULL; } bool unique() const { return intrusive_ptr_use_count(p_) == 1; } class hidden_t { hidden_t(); }; typedef void booleanesque_t(hidden_t); operator booleanesque_t*() const { return p_ ? &intrusive_ptr_t<T>::dummy_method : 0; } private: static void dummy_method(hidden_t) { } T *p_; }; template <class> class single_threaded_shared_mixin_t; template <class T> inline void intrusive_ptr_add_ref(single_threaded_shared_mixin_t<T> *p); template <class T> inline void intrusive_ptr_release(single_threaded_shared_mixin_t<T> *p); template <class T> inline intptr_t intrusive_ptr_use_count(const single_threaded_shared_mixin_t<T> *p); template <class T> class single_threaded_shared_mixin_t { public: single_threaded_shared_mixin_t() : refcount_(0) { } protected: ~single_threaded_shared_mixin_t() { } private: friend void intrusive_ptr_add_ref<T>(single_threaded_shared_mixin_t<T> *p); friend void intrusive_ptr_release<T>(single_threaded_shared_mixin_t<T> *p); friend intptr_t intrusive_ptr_use_count<T>(const single_threaded_shared_mixin_t<T> *p); intptr_t refcount_; DISABLE_COPYING(single_threaded_shared_mixin_t); }; template <class T> inline void intrusive_ptr_add_ref(single_threaded_shared_mixin_t<T> *p) { p->refcount_ += 1; rassert(p->refcount_ > 0); } template <class T> inline void intrusive_ptr_release(single_threaded_shared_mixin_t<T> *p) { rassert(p->refcount_ > 0); --p->refcount_; if (p->refcount_ == 0) { delete static_cast<T *>(p); } } template <class T> inline intptr_t intrusive_ptr_use_count(const single_threaded_shared_mixin_t<T> *p) { return p->refcount_; } template <class> class slow_shared_mixin_t; template <class T> inline void intrusive_ptr_add_ref(slow_shared_mixin_t<T> *p); template <class T> inline void intrusive_ptr_release(slow_shared_mixin_t<T> *p); template <class T> inline intptr_t intrusive_ptr_use_count(const slow_shared_mixin_t<T> *p); template <class T> class slow_shared_mixin_t { public: slow_shared_mixin_t() : refcount_(0) { } protected: ~slow_shared_mixin_t() { } private: friend void intrusive_ptr_add_ref<T>(slow_shared_mixin_t<T> *p); friend void intrusive_ptr_release<T>(slow_shared_mixin_t<T> *p); friend intptr_t intrusive_ptr_use_count<T>(const slow_shared_mixin_t<T> *p); intptr_t refcount_; DISABLE_COPYING(slow_shared_mixin_t); }; template <class T> inline void intrusive_ptr_add_ref(slow_shared_mixin_t<T> *p) { DEBUG_VAR intptr_t res = __sync_add_and_fetch(&p->refcount_, 1); rassert(res > 0); } template <class T> inline void intrusive_ptr_release(slow_shared_mixin_t<T> *p) { intptr_t res = __sync_sub_and_fetch(&p->refcount_, 1); rassert(res >= 0); if (res == 0) { delete static_cast<T *>(p); } } template <class T> inline intptr_t intrusive_ptr_use_count(const slow_shared_mixin_t<T> *p) { // Finally a practical use for volatile. intptr_t tmp = static_cast<const volatile intptr_t&>(p->refcount_); rassert(tmp > 0); return tmp; } #endif // CONTAINERS_INTRUSIVE_PTR_HPP_ <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2013 Jolla Ltd. ** Contact: Vesa-Matti Hartikainen <vesa-matti.hartikainen@jollamobile.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 "declarativebookmarkmodel.h" #include <QJsonDocument> #include <QJsonArray> #include <QJsonObject> #include <QDebug> #include <QDesktopServices> #include <QDir> #include <QFile> #include <QTextStream> DeclarativeBookmarkModel::DeclarativeBookmarkModel(QObject *parent) : QAbstractListModel(parent) { } QHash<int, QByteArray> DeclarativeBookmarkModel::roleNames() const { QHash<int, QByteArray> roles; roles[UrlRole] = "url"; roles[TitleRole] = "title"; roles[FaviconRole] = "favicon"; return roles; } // TODO cleanup void DeclarativeBookmarkModel::addBookmark(const QString& url, const QString& title, const QString& favicon) { beginInsertRows(QModelIndex(), rowCount(), rowCount()); bookmarks.insert(url, new Bookmark(title, url, favicon)); bookmarkUrls.append(url); endInsertRows(); emit countChanged(); save(); } void DeclarativeBookmarkModel::removeBookmark(const QString& url) { if (!contains(url)) { return; } if (bookmarks.contains(url)) { int index = bookmarkUrls.indexOf(url); beginRemoveRows(QModelIndex(), index, index); Bookmark* bookmark = bookmarks.take(url); delete bookmark; bookmarkUrls.removeAt(index); endRemoveRows(); emit countChanged(); save(); } } void DeclarativeBookmarkModel::componentComplete() { QString settingsLocation = QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/bookmarks.json"; QScopedPointer<QFile> file(new QFile(settingsLocation)); if (!file->open(QIODevice::ReadOnly | QIODevice::Text)) { qWarning() << "Unable to open bookmarks "+settingsLocation; file.reset(new QFile(QLatin1Literal("/usr/share/sailfish-browser/content/bookmarks.json"))); if (!file->open(QIODevice::ReadOnly | QIODevice::Text)) { qWarning() << "Unable to open bookmarks defaults"; return; } } QJsonDocument doc = QJsonDocument::fromJson(file->readAll()); if (doc.isArray()) { QJsonArray array = doc.array(); QJsonArray::iterator i; for(i=array.begin(); i != array.end(); ++i) { if((*i).isObject()) { QJsonObject obj = (*i).toObject(); QString url = obj.value("url").toString(); Bookmark* m = new Bookmark(obj.value("title").toString(), url, obj.value("favicon").toString()); bookmarks.insert(url, m); bookmarkUrls.append(url); } } } else { qWarning() << "Bookmarks.json should be an array of items"; } emit countChanged(); file->close(); } void DeclarativeBookmarkModel::classBegin() {} void DeclarativeBookmarkModel::save() { QString settingsLocation = QStandardPaths::writableLocation(QStandardPaths::DataLocation); QDir dir(settingsLocation); if(!dir.exists()) { if(!dir.mkpath(settingsLocation)) { qWarning() << "Can't create directory "+ settingsLocation; return; } } QString path = settingsLocation + "/bookmarks.json"; QFile file(path); if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) { qWarning() << "Can't create file "+ path; return; } QTextStream out(&file); QJsonArray items; QMapIterator<QString, Bookmark*> bookmarkIterator(bookmarks); while (bookmarkIterator.hasNext()) { bookmarkIterator.next(); QJsonObject title; Bookmark* bookmark = bookmarkIterator.value(); title.insert("url", QJsonValue(bookmark->url())); title.insert("title", QJsonValue(bookmark->title())); title.insert("favicon", QJsonValue(bookmark->favicon())); items.append(QJsonValue(title)); } QJsonDocument doc(items); out.setCodec("UTF-8"); out << doc.toJson(); file.close(); } int DeclarativeBookmarkModel::rowCount(const QModelIndex & parent) const { Q_UNUSED(parent) return bookmarks.count(); } QVariant DeclarativeBookmarkModel::data(const QModelIndex & index, int role) const { if (index.row() < 0 || index.row() > bookmarkUrls.count()) return QVariant(); const Bookmark * bookmark = bookmarks.value(bookmarkUrls[index.row()]); if (role == UrlRole) { return bookmark->url(); } else if (role == TitleRole) { return bookmark->title(); } else if (role == FaviconRole) { return bookmark->favicon(); } return QVariant(); } bool DeclarativeBookmarkModel::contains(const QString& url) const { return bookmarks.contains(url); } <commit_msg>[sailfish-browser] Add support for web service icons provided by platform<commit_after>/**************************************************************************** ** ** Copyright (C) 2013 Jolla Ltd. ** Contact: Vesa-Matti Hartikainen <vesa-matti.hartikainen@jollamobile.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 "declarativebookmarkmodel.h" #include <QJsonDocument> #include <QJsonArray> #include <QJsonObject> #include <QDebug> #include <QDesktopServices> #include <QDir> #include <QFile> #include <QRegularExpression> #include <QTextStream> DeclarativeBookmarkModel::DeclarativeBookmarkModel(QObject *parent) : QAbstractListModel(parent) { } QHash<int, QByteArray> DeclarativeBookmarkModel::roleNames() const { QHash<int, QByteArray> roles; roles[UrlRole] = "url"; roles[TitleRole] = "title"; roles[FaviconRole] = "favicon"; return roles; } // TODO cleanup void DeclarativeBookmarkModel::addBookmark(const QString& url, const QString& title, const QString& favicon) { beginInsertRows(QModelIndex(), rowCount(), rowCount()); bookmarks.insert(url, new Bookmark(title, url, favicon)); bookmarkUrls.append(url); endInsertRows(); emit countChanged(); save(); } void DeclarativeBookmarkModel::removeBookmark(const QString& url) { if (!contains(url)) { return; } if (bookmarks.contains(url)) { int index = bookmarkUrls.indexOf(url); beginRemoveRows(QModelIndex(), index, index); Bookmark* bookmark = bookmarks.take(url); delete bookmark; bookmarkUrls.removeAt(index); endRemoveRows(); emit countChanged(); save(); } } void DeclarativeBookmarkModel::componentComplete() { QString settingsLocation = QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/bookmarks.json"; QScopedPointer<QFile> file(new QFile(settingsLocation)); if (!file->open(QIODevice::ReadOnly | QIODevice::Text)) { qWarning() << "Unable to open bookmarks "+settingsLocation; file.reset(new QFile(QLatin1Literal("/usr/share/sailfish-browser/content/bookmarks.json"))); if (!file->open(QIODevice::ReadOnly | QIODevice::Text)) { qWarning() << "Unable to open bookmarks defaults"; return; } } QJsonDocument doc = QJsonDocument::fromJson(file->readAll()); if (doc.isArray()) { QJsonArray array = doc.array(); QJsonArray::iterator i; QRegularExpression re("^http[s]?://(together.)?jolla.com"); for(i=array.begin(); i != array.end(); ++i) { if((*i).isObject()) { QJsonObject obj = (*i).toObject(); QString url = obj.value("url").toString(); QString favicon = obj.value("favicon").toString(); if (url.contains(re)) { favicon = "image://theme/icon-m-service-jolla"; } Bookmark* m = new Bookmark(obj.value("title").toString(), url, favicon); bookmarks.insert(url, m); bookmarkUrls.append(url); } } } else { qWarning() << "Bookmarks.json should be an array of items"; } emit countChanged(); file->close(); } void DeclarativeBookmarkModel::classBegin() {} void DeclarativeBookmarkModel::save() { QString settingsLocation = QStandardPaths::writableLocation(QStandardPaths::DataLocation); QDir dir(settingsLocation); if(!dir.exists()) { if(!dir.mkpath(settingsLocation)) { qWarning() << "Can't create directory "+ settingsLocation; return; } } QString path = settingsLocation + "/bookmarks.json"; QFile file(path); if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) { qWarning() << "Can't create file "+ path; return; } QTextStream out(&file); QJsonArray items; QMapIterator<QString, Bookmark*> bookmarkIterator(bookmarks); while (bookmarkIterator.hasNext()) { bookmarkIterator.next(); QJsonObject title; Bookmark* bookmark = bookmarkIterator.value(); title.insert("url", QJsonValue(bookmark->url())); title.insert("title", QJsonValue(bookmark->title())); title.insert("favicon", QJsonValue(bookmark->favicon())); items.append(QJsonValue(title)); } QJsonDocument doc(items); out.setCodec("UTF-8"); out << doc.toJson(); file.close(); } int DeclarativeBookmarkModel::rowCount(const QModelIndex & parent) const { Q_UNUSED(parent) return bookmarks.count(); } QVariant DeclarativeBookmarkModel::data(const QModelIndex & index, int role) const { if (index.row() < 0 || index.row() > bookmarkUrls.count()) return QVariant(); const Bookmark * bookmark = bookmarks.value(bookmarkUrls[index.row()]); if (role == UrlRole) { return bookmark->url(); } else if (role == TitleRole) { return bookmark->title(); } else if (role == FaviconRole) { return bookmark->favicon(); } return QVariant(); } bool DeclarativeBookmarkModel::contains(const QString& url) const { return bookmarks.contains(url); } <|endoftext|>
<commit_before>/* * Copyright (C) 2017 The Android Open Source Project * * 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 "perfetto/ext/base/paged_memory.h" #include <stdint.h> #include "perfetto/base/build_config.h" #include "perfetto/ext/base/utils.h" #include "src/base/test/vm_test_utils.h" #include "test/gtest_and_gmock.h" #if !PERFETTO_BUILDFLAG(PERFETTO_OS_APPLE) && \ !PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) && \ !PERFETTO_BUILDFLAG(PERFETTO_OS_FUCHSIA) #include <sys/resource.h> #endif namespace perfetto { namespace base { namespace { TEST(PagedMemoryTest, Basic) { const size_t kNumPages = 10; const size_t kSize = 4096 * kNumPages; void* ptr_raw = nullptr; { PagedMemory mem = PagedMemory::Allocate(kSize); ASSERT_TRUE(mem.IsValid()); ASSERT_EQ(0u, reinterpret_cast<uintptr_t>(mem.Get()) % 4096); ptr_raw = mem.Get(); for (size_t i = 0; i < kSize / sizeof(uint64_t); i++) ASSERT_EQ(0u, *(reinterpret_cast<uint64_t*>(mem.Get()) + i)); #if !PERFETTO_BUILDFLAG(PERFETTO_OS_FUCHSIA) ASSERT_TRUE(vm_test_utils::IsMapped(ptr_raw, kSize)); #endif #if PERFETTO_BUILDFLAG(PERFETTO_OS_LINUX) || \ PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) ASSERT_TRUE(mem.AdviseDontNeed(ptr_raw, kSize)); // Make sure the pages were removed from the working set. ASSERT_FALSE(vm_test_utils::IsMapped(ptr_raw, kSize)); #endif } #if !PERFETTO_BUILDFLAG(PERFETTO_OS_FUCHSIA) // Freed memory is necessarily not mapped in to the process. ASSERT_FALSE(vm_test_utils::IsMapped(ptr_raw, kSize)); #endif } TEST(PagedMemoryTest, SubPageGranularity) { const size_t kSize = GetSysPageSize() + 1024; PagedMemory mem = PagedMemory::Allocate(kSize); ASSERT_TRUE(mem.IsValid()); ASSERT_EQ(0u, reinterpret_cast<uintptr_t>(mem.Get()) % GetSysPageSize()); void* ptr_raw = mem.Get(); for (size_t i = 0; i < kSize / sizeof(uint64_t); i++) { auto* ptr64 = reinterpret_cast<volatile uint64_t*>(ptr_raw) + i; ASSERT_EQ(0u, *ptr64); *ptr64 = i; } #if PERFETTO_BUILDFLAG(PERFETTO_OS_LINUX) || \ PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) // Do an AdviseDontNeed on the whole range, which is NOT an integer multiple // of the page size. The initial page must be cleared. The remaining 1024 // might or might not be cleared depending on the OS implementation. ASSERT_TRUE(mem.AdviseDontNeed(ptr_raw, kSize)); ASSERT_FALSE(vm_test_utils::IsMapped(ptr_raw, GetSysPageSize())); for (size_t i = 0; i < GetSysPageSize() / sizeof(uint64_t); i++) { auto* ptr64 = reinterpret_cast<volatile uint64_t*>(ptr_raw) + i; ASSERT_EQ(0u, *ptr64); } #endif } TEST(PagedMemoryTest, Uncommitted) { constexpr size_t kNumPages = 4096; constexpr size_t kSize = 4096 * kNumPages; char* ptr_raw = nullptr; { PagedMemory mem = PagedMemory::Allocate(kSize, PagedMemory::kDontCommit); ASSERT_TRUE(mem.IsValid()); ptr_raw = reinterpret_cast<char*>(mem.Get()); #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) // Windows only commits the first 1024 pages. constexpr size_t kMappedSize = 4096 * 1024; for (size_t i = 0; i < kMappedSize / sizeof(uint64_t); i++) ASSERT_EQ(0u, *(reinterpret_cast<uint64_t*>(mem.Get()) + i)); ASSERT_TRUE(vm_test_utils::IsMapped(ptr_raw, kMappedSize)); // Next page shouldn't be mapped. ASSERT_FALSE(vm_test_utils::IsMapped(ptr_raw + kMappedSize, 4096)); EXPECT_DEATH_IF_SUPPORTED({ ptr_raw[kMappedSize] = 'x'; }, ".*"); // Commit the remaining pages. mem.EnsureCommitted(kSize); for (size_t i = kMappedSize / sizeof(uint64_t); i < kSize / sizeof(uint64_t); i++) { ASSERT_EQ(0u, *(reinterpret_cast<uint64_t*>(mem.Get()) + i)); } #elif PERFETTO_BUILDFLAG(PERFETTO_OS_FUCHSIA) // Fuchsia doesn't yet support paging. So this should be a no-op. mem.EnsureCommitted(kSize); for (size_t i = 0; i < kSize / sizeof(uint64_t); i++) ASSERT_EQ(0u, *(reinterpret_cast<uint64_t*>(mem.Get()) + i)); #else // Linux only maps on access. ASSERT_FALSE(vm_test_utils::IsMapped(ptr_raw, kSize)); // This should not have any effect. mem.EnsureCommitted(kSize); ASSERT_FALSE(vm_test_utils::IsMapped(ptr_raw, kSize)); for (size_t i = 0; i < kSize / sizeof(uint64_t); i++) ASSERT_EQ(0u, *(reinterpret_cast<uint64_t*>(mem.Get()) + i)); ASSERT_TRUE(vm_test_utils::IsMapped(ptr_raw, kSize)); #endif } #if !PERFETTO_BUILDFLAG(PERFETTO_OS_FUCHSIA) // Freed memory is necessarily not mapped in to the process. ASSERT_FALSE(vm_test_utils::IsMapped(ptr_raw, kSize)); #endif } #if defined(ADDRESS_SANITIZER) TEST(PagedMemoryTest, AccessUncommittedMemoryTriggersASAN) { EXPECT_DEATH_IF_SUPPORTED( { constexpr size_t kNumPages = 4096; constexpr size_t kSize = 4096 * kNumPages; PagedMemory mem = PagedMemory::Allocate(kSize, PagedMemory::kDontCommit); ASSERT_TRUE(mem.IsValid()); char* ptr_raw = reinterpret_cast<char*>(mem.Get()); // Only the first 1024 pages are mapped. constexpr size_t kMappedSize = 4096 * 1024; ptr_raw[kMappedSize] = 'x'; abort(); }, "AddressSanitizer: .*"); } #endif // ADDRESS_SANITIZER TEST(PagedMemoryTest, GuardRegions) { const size_t kSize = GetSysPageSize(); PagedMemory mem = PagedMemory::Allocate(kSize); ASSERT_TRUE(mem.IsValid()); volatile char* raw = reinterpret_cast<char*>(mem.Get()); EXPECT_DEATH_IF_SUPPORTED({ raw[-1] = 'x'; }, ".*"); EXPECT_DEATH_IF_SUPPORTED({ raw[kSize] = 'x'; }, ".*"); } // Disable this on: // MacOS: because it doesn't seem to have an equivalent rlimit to bound mmap(). // Fuchsia: doesn't support rlimit. // Sanitizers: they seem to try to shadow mmaped memory and fail due to OOMs. #if !PERFETTO_BUILDFLAG(PERFETTO_OS_APPLE) && \ !PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) && \ !PERFETTO_BUILDFLAG(PERFETTO_OS_FUCHSIA) && !defined(ADDRESS_SANITIZER) && \ !defined(LEAK_SANITIZER) && !defined(THREAD_SANITIZER) && \ !defined(MEMORY_SANITIZER) // Glibc headers hit this on RLIMIT_ macros. #pragma GCC diagnostic push #if defined(__clang__) #pragma GCC diagnostic ignored "-Wdisabled-macro-expansion" #endif TEST(PagedMemoryTest, Unchecked) { const size_t kMemLimit = 256 * 1024 * 1024l; struct rlimit limit { kMemLimit, kMemLimit }; // ASSERT_EXIT here is to spawn the test in a sub-process and avoid // propagating the setrlimit() to other test units in case of failure. ASSERT_EXIT( { ASSERT_EQ(0, setrlimit(RLIMIT_AS, &limit)); auto mem = PagedMemory::Allocate(kMemLimit * 2, PagedMemory::kMayFail); ASSERT_FALSE(mem.IsValid()); // Use _exit() instead of exit() to avoid calling destructors on child // process death, which may interfere with the parent process's test // launcher expectations. _exit(0); }, ::testing::ExitedWithCode(0), ""); } #pragma GCC diagnostic pop #endif } // namespace } // namespace base } // namespace perfetto <commit_msg>Fix some instances of -Wunused-but-set-variable.<commit_after>/* * Copyright (C) 2017 The Android Open Source Project * * 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 "perfetto/ext/base/paged_memory.h" #include <stdint.h> #include "perfetto/base/build_config.h" #include "perfetto/ext/base/utils.h" #include "src/base/test/vm_test_utils.h" #include "test/gtest_and_gmock.h" #if !PERFETTO_BUILDFLAG(PERFETTO_OS_APPLE) && \ !PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) && \ !PERFETTO_BUILDFLAG(PERFETTO_OS_FUCHSIA) #include <sys/resource.h> #endif namespace perfetto { namespace base { namespace { TEST(PagedMemoryTest, Basic) { const size_t kNumPages = 10; const size_t kSize = 4096 * kNumPages; #if !PERFETTO_BUILDFLAG(PERFETTO_OS_FUCHSIA) void* ptr_raw = nullptr; #endif { PagedMemory mem = PagedMemory::Allocate(kSize); ASSERT_TRUE(mem.IsValid()); ASSERT_EQ(0u, reinterpret_cast<uintptr_t>(mem.Get()) % 4096); #if !PERFETTO_BUILDFLAG(PERFETTO_OS_FUCHSIA) ptr_raw = mem.Get(); #endif for (size_t i = 0; i < kSize / sizeof(uint64_t); i++) ASSERT_EQ(0u, *(reinterpret_cast<uint64_t*>(mem.Get()) + i)); #if !PERFETTO_BUILDFLAG(PERFETTO_OS_FUCHSIA) ASSERT_TRUE(vm_test_utils::IsMapped(ptr_raw, kSize)); #endif #if PERFETTO_BUILDFLAG(PERFETTO_OS_LINUX) || \ PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) ASSERT_TRUE(mem.AdviseDontNeed(ptr_raw, kSize)); // Make sure the pages were removed from the working set. ASSERT_FALSE(vm_test_utils::IsMapped(ptr_raw, kSize)); #endif } #if !PERFETTO_BUILDFLAG(PERFETTO_OS_FUCHSIA) // Freed memory is necessarily not mapped in to the process. ASSERT_FALSE(vm_test_utils::IsMapped(ptr_raw, kSize)); #endif } TEST(PagedMemoryTest, SubPageGranularity) { const size_t kSize = GetSysPageSize() + 1024; PagedMemory mem = PagedMemory::Allocate(kSize); ASSERT_TRUE(mem.IsValid()); ASSERT_EQ(0u, reinterpret_cast<uintptr_t>(mem.Get()) % GetSysPageSize()); void* ptr_raw = mem.Get(); for (size_t i = 0; i < kSize / sizeof(uint64_t); i++) { auto* ptr64 = reinterpret_cast<volatile uint64_t*>(ptr_raw) + i; ASSERT_EQ(0u, *ptr64); *ptr64 = i; } #if PERFETTO_BUILDFLAG(PERFETTO_OS_LINUX) || \ PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID) // Do an AdviseDontNeed on the whole range, which is NOT an integer multiple // of the page size. The initial page must be cleared. The remaining 1024 // might or might not be cleared depending on the OS implementation. ASSERT_TRUE(mem.AdviseDontNeed(ptr_raw, kSize)); ASSERT_FALSE(vm_test_utils::IsMapped(ptr_raw, GetSysPageSize())); for (size_t i = 0; i < GetSysPageSize() / sizeof(uint64_t); i++) { auto* ptr64 = reinterpret_cast<volatile uint64_t*>(ptr_raw) + i; ASSERT_EQ(0u, *ptr64); } #endif } TEST(PagedMemoryTest, Uncommitted) { constexpr size_t kNumPages = 4096; constexpr size_t kSize = 4096 * kNumPages; #if !PERFETTO_BUILDFLAG(PERFETTO_OS_FUCHSIA) char* ptr_raw = nullptr; #endif { PagedMemory mem = PagedMemory::Allocate(kSize, PagedMemory::kDontCommit); ASSERT_TRUE(mem.IsValid()); #if !PERFETTO_BUILDFLAG(PERFETTO_OS_FUCHSIA) ptr_raw = reinterpret_cast<char*>(mem.Get()); #endif #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) // Windows only commits the first 1024 pages. constexpr size_t kMappedSize = 4096 * 1024; for (size_t i = 0; i < kMappedSize / sizeof(uint64_t); i++) ASSERT_EQ(0u, *(reinterpret_cast<uint64_t*>(mem.Get()) + i)); ASSERT_TRUE(vm_test_utils::IsMapped(ptr_raw, kMappedSize)); // Next page shouldn't be mapped. ASSERT_FALSE(vm_test_utils::IsMapped(ptr_raw + kMappedSize, 4096)); EXPECT_DEATH_IF_SUPPORTED({ ptr_raw[kMappedSize] = 'x'; }, ".*"); // Commit the remaining pages. mem.EnsureCommitted(kSize); for (size_t i = kMappedSize / sizeof(uint64_t); i < kSize / sizeof(uint64_t); i++) { ASSERT_EQ(0u, *(reinterpret_cast<uint64_t*>(mem.Get()) + i)); } #elif PERFETTO_BUILDFLAG(PERFETTO_OS_FUCHSIA) // Fuchsia doesn't yet support paging. So this should be a no-op. mem.EnsureCommitted(kSize); for (size_t i = 0; i < kSize / sizeof(uint64_t); i++) ASSERT_EQ(0u, *(reinterpret_cast<uint64_t*>(mem.Get()) + i)); #else // Linux only maps on access. ASSERT_FALSE(vm_test_utils::IsMapped(ptr_raw, kSize)); // This should not have any effect. mem.EnsureCommitted(kSize); ASSERT_FALSE(vm_test_utils::IsMapped(ptr_raw, kSize)); for (size_t i = 0; i < kSize / sizeof(uint64_t); i++) ASSERT_EQ(0u, *(reinterpret_cast<uint64_t*>(mem.Get()) + i)); ASSERT_TRUE(vm_test_utils::IsMapped(ptr_raw, kSize)); #endif } #if !PERFETTO_BUILDFLAG(PERFETTO_OS_FUCHSIA) // Freed memory is necessarily not mapped in to the process. ASSERT_FALSE(vm_test_utils::IsMapped(ptr_raw, kSize)); #endif } #if defined(ADDRESS_SANITIZER) TEST(PagedMemoryTest, AccessUncommittedMemoryTriggersASAN) { EXPECT_DEATH_IF_SUPPORTED( { constexpr size_t kNumPages = 4096; constexpr size_t kSize = 4096 * kNumPages; PagedMemory mem = PagedMemory::Allocate(kSize, PagedMemory::kDontCommit); ASSERT_TRUE(mem.IsValid()); char* ptr_raw = reinterpret_cast<char*>(mem.Get()); // Only the first 1024 pages are mapped. constexpr size_t kMappedSize = 4096 * 1024; ptr_raw[kMappedSize] = 'x'; abort(); }, "AddressSanitizer: .*"); } #endif // ADDRESS_SANITIZER TEST(PagedMemoryTest, GuardRegions) { const size_t kSize = GetSysPageSize(); PagedMemory mem = PagedMemory::Allocate(kSize); ASSERT_TRUE(mem.IsValid()); volatile char* raw = reinterpret_cast<char*>(mem.Get()); EXPECT_DEATH_IF_SUPPORTED({ raw[-1] = 'x'; }, ".*"); EXPECT_DEATH_IF_SUPPORTED({ raw[kSize] = 'x'; }, ".*"); } // Disable this on: // MacOS: because it doesn't seem to have an equivalent rlimit to bound mmap(). // Fuchsia: doesn't support rlimit. // Sanitizers: they seem to try to shadow mmaped memory and fail due to OOMs. #if !PERFETTO_BUILDFLAG(PERFETTO_OS_APPLE) && \ !PERFETTO_BUILDFLAG(PERFETTO_OS_WIN) && \ !PERFETTO_BUILDFLAG(PERFETTO_OS_FUCHSIA) && !defined(ADDRESS_SANITIZER) && \ !defined(LEAK_SANITIZER) && !defined(THREAD_SANITIZER) && \ !defined(MEMORY_SANITIZER) // Glibc headers hit this on RLIMIT_ macros. #pragma GCC diagnostic push #if defined(__clang__) #pragma GCC diagnostic ignored "-Wdisabled-macro-expansion" #endif TEST(PagedMemoryTest, Unchecked) { const size_t kMemLimit = 256 * 1024 * 1024l; struct rlimit limit { kMemLimit, kMemLimit }; // ASSERT_EXIT here is to spawn the test in a sub-process and avoid // propagating the setrlimit() to other test units in case of failure. ASSERT_EXIT( { ASSERT_EQ(0, setrlimit(RLIMIT_AS, &limit)); auto mem = PagedMemory::Allocate(kMemLimit * 2, PagedMemory::kMayFail); ASSERT_FALSE(mem.IsValid()); // Use _exit() instead of exit() to avoid calling destructors on child // process death, which may interfere with the parent process's test // launcher expectations. _exit(0); }, ::testing::ExitedWithCode(0), ""); } #pragma GCC diagnostic pop #endif } // namespace } // namespace base } // namespace perfetto <|endoftext|>
<commit_before>/* dtkPluginManager.cpp --- * * Author: Julien Wintz * Copyright (C) 2008 - Julien Wintz, Inria. * Created: Tue Aug 4 12:20:59 2009 (+0200) * Version: $Id$ * Last-Updated: Sun Jul 18 14:57:08 2010 (+0200) * By: Julien Wintz * Update #: 126 */ /* Commentary: * */ /* Change log: * */ #include "dtkAbstractData.h" #include "dtkPluginManager.h" #include <dtkCore/dtkPlugin.h> #include <dtkCore/dtkLog.h> #define DTK_VERBOSE_LOAD false class dtkPluginManagerPrivate { public: QString path; QHash<QString, QPluginLoader *> loaders; }; dtkPluginManager *dtkPluginManager::instance(void) { if(!s_instance) { s_instance = new dtkPluginManager; qRegisterMetaType<dtkAbstractData>("dtkAbstractData"); } return s_instance; } void dtkPluginManager::initialize(void) { if(d->path.isNull()) this->readSettings(); if(d->path.isEmpty()) return; QString paths = d->path + ":" + #ifdef Q_WS_WIN qApp->applicationDirPath() + "\\..\\plugins"; #else #ifdef Q_WS_MAC qApp->applicationDirPath() + "/../PlugIns"; #else qApp->applicationDirPath() + "/../plugins"; #endif #endif foreach(QString path, paths.split(":", QString::SkipEmptyParts)) { QDir dir(path); dir.setFilter(QDir::AllEntries | QDir::NoDotAndDotDot); foreach (QFileInfo entry, dir.entryInfoList()) loadPlugin(entry.absoluteFilePath()); } } void dtkPluginManager::uninitialize(void) { this->writeSettings(); // foreach(QString path, d->loaders.keys()) // unloadPlugin(path); } void dtkPluginManager::readSettings(void) { QSettings settings("inria", "dtk"); settings.beginGroup("plugins"); #ifdef Q_WS_WIN d->path = settings.value("path", "C:\\Program Files\\inria\\plugins").toString(); #else d->path = settings.value("path", "/usr/local/inria/plugins").toString(); #endif settings.endGroup(); if(d->path.isEmpty()) { dtkWarning() << "Your dtk config does not seem to be set correctly."; dtkWarning() << "Please set plugins.path."; } } void dtkPluginManager::writeSettings(void) { QSettings settings("inria", "dtk"); settings.beginGroup("plugins"); settings.setValue("path", d->path); settings.endGroup(); } void dtkPluginManager::printPlugins(void) { foreach(QString path, d->loaders.keys()) dtkOutput() << path; } dtkPlugin *dtkPluginManager::plugin(QString name) { foreach(QPluginLoader *loader, d->loaders) { dtkPlugin *plugin = qobject_cast<dtkPlugin *>(loader->instance()); if(plugin->name() == name) return plugin; } return NULL; } QList<dtkPlugin *> dtkPluginManager::plugins(void) { QList<dtkPlugin *> list; foreach(QPluginLoader *loader, d->loaders) list << qobject_cast<dtkPlugin *>(loader->instance()); return list; } void dtkPluginManager::setPath(const QString& path) { d->path = path; } dtkPluginManager::dtkPluginManager(void) : d(new dtkPluginManagerPrivate) { } dtkPluginManager::~dtkPluginManager(void) { delete d; d = NULL; } void dtkPluginManager::loadPlugin(const QString& path) { QPluginLoader *loader = new QPluginLoader(path); loader->setLoadHints (QLibrary::ExportExternalSymbolsHint); if(!loader->load()) { if(DTK_VERBOSE_LOAD) dtkDebug() << "Unable to load - " << loader->errorString(); delete loader; return; } dtkPlugin *plugin = qobject_cast<dtkPlugin *>(loader->instance()); if(!plugin) { if(DTK_VERBOSE_LOAD) dtkDebug() << "Unable to retrieve" << path; return; } if(!plugin->initialize()) { if(DTK_VERBOSE_LOAD) dtkOutput() << "Unable to initialize" << plugin->name() << "plugin"; return; } d->loaders.insert(path, loader); emit loaded(plugin->name()); } void dtkPluginManager::unloadPlugin(const QString& path) { dtkPlugin *plugin = qobject_cast<dtkPlugin *>(d->loaders.value(path)->instance()); if(!plugin) { if(DTK_VERBOSE_LOAD) dtkDebug() << "dtkPluginManager - Unable to retrieve" << plugin->name() << "plugin"; return; } if(!plugin->uninitialize()) { if(DTK_VERBOSE_LOAD) dtkOutput() << "Unable to uninitialize" << plugin->name() << "plugin"; return; } QPluginLoader *loader = d->loaders.value(path); if(!loader->unload()) { if(DTK_VERBOSE_LOAD) dtkDebug() << "dtkPluginManager - Unable to unload plugin:" << loader->errorString(); return; } delete loader; d->loaders.remove(path); // emit unloaded(plugin->name()); } dtkPluginManager *dtkPluginManager::s_instance = NULL; <commit_msg>Do not return when plugin path is empty, use ../plugins as default path instead<commit_after>/* dtkPluginManager.cpp --- * * Author: Julien Wintz * Copyright (C) 2008 - Julien Wintz, Inria. * Created: Tue Aug 4 12:20:59 2009 (+0200) * Version: $Id$ * Last-Updated: Sun Jul 18 14:57:08 2010 (+0200) * By: Julien Wintz * Update #: 126 */ /* Commentary: * */ /* Change log: * */ #include "dtkAbstractData.h" #include "dtkPluginManager.h" #include <dtkCore/dtkPlugin.h> #include <dtkCore/dtkLog.h> #define DTK_VERBOSE_LOAD false class dtkPluginManagerPrivate { public: QString path; QHash<QString, QPluginLoader *> loaders; }; dtkPluginManager *dtkPluginManager::instance(void) { if(!s_instance) { s_instance = new dtkPluginManager; qRegisterMetaType<dtkAbstractData>("dtkAbstractData"); } return s_instance; } void dtkPluginManager::initialize(void) { if(d->path.isNull()) this->readSettings(); QString paths = ""; if (!d->path.isEmpty()) paths = d->path + ":"; paths = paths + #ifdef Q_WS_WIN qApp->applicationDirPath() + "\\..\\plugins"; #else #ifdef Q_WS_MAC qApp->applicationDirPath() + "/../PlugIns"; #else qApp->applicationDirPath() + "/../plugins"; #endif #endif foreach(QString path, paths.split(":", QString::SkipEmptyParts)) { QDir dir(path); dir.setFilter(QDir::AllEntries | QDir::NoDotAndDotDot); foreach (QFileInfo entry, dir.entryInfoList()) loadPlugin(entry.absoluteFilePath()); } } void dtkPluginManager::uninitialize(void) { this->writeSettings(); // foreach(QString path, d->loaders.keys()) // unloadPlugin(path); } void dtkPluginManager::readSettings(void) { QSettings settings("inria", "dtk"); settings.beginGroup("plugins"); #ifdef Q_WS_WIN d->path = settings.value("path", "C:\\Program Files\\inria\\plugins").toString(); #else d->path = settings.value("path", "/usr/local/inria/plugins").toString(); #endif settings.endGroup(); if(d->path.isEmpty()) { dtkWarning() << "Your dtk config does not seem to be set correctly."; dtkWarning() << "Please set plugins.path."; } } void dtkPluginManager::writeSettings(void) { QSettings settings("inria", "dtk"); settings.beginGroup("plugins"); settings.setValue("path", d->path); settings.endGroup(); } void dtkPluginManager::printPlugins(void) { foreach(QString path, d->loaders.keys()) dtkOutput() << path; } dtkPlugin *dtkPluginManager::plugin(QString name) { foreach(QPluginLoader *loader, d->loaders) { dtkPlugin *plugin = qobject_cast<dtkPlugin *>(loader->instance()); if(plugin->name() == name) return plugin; } return NULL; } QList<dtkPlugin *> dtkPluginManager::plugins(void) { QList<dtkPlugin *> list; foreach(QPluginLoader *loader, d->loaders) list << qobject_cast<dtkPlugin *>(loader->instance()); return list; } void dtkPluginManager::setPath(const QString& path) { d->path = path; } dtkPluginManager::dtkPluginManager(void) : d(new dtkPluginManagerPrivate) { } dtkPluginManager::~dtkPluginManager(void) { delete d; d = NULL; } void dtkPluginManager::loadPlugin(const QString& path) { QPluginLoader *loader = new QPluginLoader(path); loader->setLoadHints (QLibrary::ExportExternalSymbolsHint); if(!loader->load()) { if(DTK_VERBOSE_LOAD) dtkDebug() << "Unable to load - " << loader->errorString(); delete loader; return; } dtkPlugin *plugin = qobject_cast<dtkPlugin *>(loader->instance()); if(!plugin) { if(DTK_VERBOSE_LOAD) dtkDebug() << "Unable to retrieve" << path; return; } if(!plugin->initialize()) { if(DTK_VERBOSE_LOAD) dtkOutput() << "Unable to initialize" << plugin->name() << "plugin"; return; } d->loaders.insert(path, loader); emit loaded(plugin->name()); } void dtkPluginManager::unloadPlugin(const QString& path) { dtkPlugin *plugin = qobject_cast<dtkPlugin *>(d->loaders.value(path)->instance()); if(!plugin) { if(DTK_VERBOSE_LOAD) dtkDebug() << "dtkPluginManager - Unable to retrieve" << plugin->name() << "plugin"; return; } if(!plugin->uninitialize()) { if(DTK_VERBOSE_LOAD) dtkOutput() << "Unable to uninitialize" << plugin->name() << "plugin"; return; } QPluginLoader *loader = d->loaders.value(path); if(!loader->unload()) { if(DTK_VERBOSE_LOAD) dtkDebug() << "dtkPluginManager - Unable to unload plugin:" << loader->errorString(); return; } delete loader; d->loaders.remove(path); // emit unloaded(plugin->name()); } dtkPluginManager *dtkPluginManager::s_instance = NULL; <|endoftext|>
<commit_before>// Copyright 2010-2014 RethinkDB, all rights reserved. #include "btree/secondary_operations.hpp" #include "btree/operations.hpp" #include "buffer_cache/alt/alt.hpp" #include "buffer_cache/alt/blob.hpp" #include "buffer_cache/alt/serialize_onto_blob.hpp" #include "containers/archive/vector_stream.hpp" RDB_IMPL_SERIALIZABLE_5(secondary_index_t, superblock, opaque_definition, post_construction_complete, being_deleted, id); RDB_IMPL_SERIALIZABLE_2(sindex_name_t, name, being_deleted); struct btree_sindex_block_t { static const int SINDEX_BLOB_MAXREFLEN = 4076; block_magic_t magic; char sindex_blob[SINDEX_BLOB_MAXREFLEN]; } __attribute__((__packed__)); // RSI: Can this be in the .cc file? template <cluster_version_t W> struct btree_sindex_block_magic_t { static const block_magic_t value; }; template <> const block_magic_t btree_sindex_block_magic_t<cluster_version_t::v1_13_is_latest>::value = { { 's', 'i', 'n', 'd' } }; cluster_version_t sindex_block_version(const btree_sindex_block_t *data) { if (data->magic == btree_sindex_block_magic_t<cluster_version_t::v1_13_is_latest>::value) { return cluster_version_t::v1_13_is_latest; } else { crash("Unexpected magic in btree_sindex_block_t."); } } void get_secondary_indexes_internal( buf_lock_t *sindex_block, std::map<sindex_name_t, secondary_index_t> *sindexes_out) { buf_read_t read(sindex_block); const btree_sindex_block_t *data = static_cast<const btree_sindex_block_t *>(read.get_data_read()); blob_t sindex_blob(sindex_block->cache()->max_block_size(), const_cast<char *>(data->sindex_blob), btree_sindex_block_t::SINDEX_BLOB_MAXREFLEN); deserialize_for_version_from_blob(sindex_block_version(data), buf_parent_t(sindex_block), &sindex_blob, sindexes_out); } void set_secondary_indexes_internal( buf_lock_t *sindex_block, const std::map<sindex_name_t, secondary_index_t> &sindexes) { buf_write_t write(sindex_block); btree_sindex_block_t *data = static_cast<btree_sindex_block_t *>(write.get_data_write()); blob_t sindex_blob(sindex_block->cache()->max_block_size(), data->sindex_blob, btree_sindex_block_t::SINDEX_BLOB_MAXREFLEN); // There's just one field in btree_sindex_block_t, sindex_blob. So we set // the magic to the latest value and serialize with the latest version. data->magic = btree_sindex_block_magic_t<cluster_version_t::LATEST>::value; serialize_for_version_onto_blob(cluster_version_t::LATEST, buf_parent_t(sindex_block), &sindex_blob, sindexes); } void initialize_secondary_indexes(buf_lock_t *sindex_block) { buf_write_t write(sindex_block); btree_sindex_block_t *data = static_cast<btree_sindex_block_t *>(write.get_data_write()); data->magic = btree_sindex_block_magic_t<cluster_version_t::LATEST>::value; memset(data->sindex_blob, 0, btree_sindex_block_t::SINDEX_BLOB_MAXREFLEN); set_secondary_indexes_internal(sindex_block, std::map<sindex_name_t, secondary_index_t>()); } bool get_secondary_index(buf_lock_t *sindex_block, const sindex_name_t &name, secondary_index_t *sindex_out) { std::map<sindex_name_t, secondary_index_t> sindex_map; get_secondary_indexes_internal(sindex_block, &sindex_map); auto it = sindex_map.find(name); if (it != sindex_map.end()) { *sindex_out = it->second; return true; } else { return false; } } bool get_secondary_index(buf_lock_t *sindex_block, uuid_u id, secondary_index_t *sindex_out) { std::map<sindex_name_t, secondary_index_t> sindex_map; get_secondary_indexes_internal(sindex_block, &sindex_map); for (auto it = sindex_map.begin(); it != sindex_map.end(); ++it) { if (it->second.id == id) { *sindex_out = it->second; return true; } } return false; } void get_secondary_indexes(buf_lock_t *sindex_block, std::map<sindex_name_t, secondary_index_t> *sindexes_out) { get_secondary_indexes_internal(sindex_block, sindexes_out); } void set_secondary_index(buf_lock_t *sindex_block, const sindex_name_t &name, const secondary_index_t &sindex) { std::map<sindex_name_t, secondary_index_t> sindex_map; get_secondary_indexes_internal(sindex_block, &sindex_map); /* We insert even if it already exists overwriting the old value. */ sindex_map[name] = sindex; set_secondary_indexes_internal(sindex_block, sindex_map); } void set_secondary_index(buf_lock_t *sindex_block, uuid_u id, const secondary_index_t &sindex) { std::map<sindex_name_t, secondary_index_t> sindex_map; get_secondary_indexes_internal(sindex_block, &sindex_map); for (auto it = sindex_map.begin(); it != sindex_map.end(); ++it) { if (it->second.id == id) { guarantee(sindex.id == id, "This shouldn't change the id."); it->second = sindex; } } set_secondary_indexes_internal(sindex_block, sindex_map); } bool delete_secondary_index(buf_lock_t *sindex_block, const sindex_name_t &name) { std::map<sindex_name_t, secondary_index_t> sindex_map; get_secondary_indexes_internal(sindex_block, &sindex_map); if (sindex_map.erase(name) == 1) { set_secondary_indexes_internal(sindex_block, sindex_map); return true; } else { return false; } } <commit_msg>Removed RSI made obsolete.<commit_after>// Copyright 2010-2014 RethinkDB, all rights reserved. #include "btree/secondary_operations.hpp" #include "btree/operations.hpp" #include "buffer_cache/alt/alt.hpp" #include "buffer_cache/alt/blob.hpp" #include "buffer_cache/alt/serialize_onto_blob.hpp" #include "containers/archive/vector_stream.hpp" RDB_IMPL_SERIALIZABLE_5(secondary_index_t, superblock, opaque_definition, post_construction_complete, being_deleted, id); RDB_IMPL_SERIALIZABLE_2(sindex_name_t, name, being_deleted); struct btree_sindex_block_t { static const int SINDEX_BLOB_MAXREFLEN = 4076; block_magic_t magic; char sindex_blob[SINDEX_BLOB_MAXREFLEN]; } __attribute__((__packed__)); template <cluster_version_t W> struct btree_sindex_block_magic_t { static const block_magic_t value; }; template <> const block_magic_t btree_sindex_block_magic_t<cluster_version_t::v1_13_is_latest>::value = { { 's', 'i', 'n', 'd' } }; cluster_version_t sindex_block_version(const btree_sindex_block_t *data) { if (data->magic == btree_sindex_block_magic_t<cluster_version_t::v1_13_is_latest>::value) { return cluster_version_t::v1_13_is_latest; } else { crash("Unexpected magic in btree_sindex_block_t."); } } void get_secondary_indexes_internal( buf_lock_t *sindex_block, std::map<sindex_name_t, secondary_index_t> *sindexes_out) { buf_read_t read(sindex_block); const btree_sindex_block_t *data = static_cast<const btree_sindex_block_t *>(read.get_data_read()); blob_t sindex_blob(sindex_block->cache()->max_block_size(), const_cast<char *>(data->sindex_blob), btree_sindex_block_t::SINDEX_BLOB_MAXREFLEN); deserialize_for_version_from_blob(sindex_block_version(data), buf_parent_t(sindex_block), &sindex_blob, sindexes_out); } void set_secondary_indexes_internal( buf_lock_t *sindex_block, const std::map<sindex_name_t, secondary_index_t> &sindexes) { buf_write_t write(sindex_block); btree_sindex_block_t *data = static_cast<btree_sindex_block_t *>(write.get_data_write()); blob_t sindex_blob(sindex_block->cache()->max_block_size(), data->sindex_blob, btree_sindex_block_t::SINDEX_BLOB_MAXREFLEN); // There's just one field in btree_sindex_block_t, sindex_blob. So we set // the magic to the latest value and serialize with the latest version. data->magic = btree_sindex_block_magic_t<cluster_version_t::LATEST>::value; serialize_for_version_onto_blob(cluster_version_t::LATEST, buf_parent_t(sindex_block), &sindex_blob, sindexes); } void initialize_secondary_indexes(buf_lock_t *sindex_block) { buf_write_t write(sindex_block); btree_sindex_block_t *data = static_cast<btree_sindex_block_t *>(write.get_data_write()); data->magic = btree_sindex_block_magic_t<cluster_version_t::LATEST>::value; memset(data->sindex_blob, 0, btree_sindex_block_t::SINDEX_BLOB_MAXREFLEN); set_secondary_indexes_internal(sindex_block, std::map<sindex_name_t, secondary_index_t>()); } bool get_secondary_index(buf_lock_t *sindex_block, const sindex_name_t &name, secondary_index_t *sindex_out) { std::map<sindex_name_t, secondary_index_t> sindex_map; get_secondary_indexes_internal(sindex_block, &sindex_map); auto it = sindex_map.find(name); if (it != sindex_map.end()) { *sindex_out = it->second; return true; } else { return false; } } bool get_secondary_index(buf_lock_t *sindex_block, uuid_u id, secondary_index_t *sindex_out) { std::map<sindex_name_t, secondary_index_t> sindex_map; get_secondary_indexes_internal(sindex_block, &sindex_map); for (auto it = sindex_map.begin(); it != sindex_map.end(); ++it) { if (it->second.id == id) { *sindex_out = it->second; return true; } } return false; } void get_secondary_indexes(buf_lock_t *sindex_block, std::map<sindex_name_t, secondary_index_t> *sindexes_out) { get_secondary_indexes_internal(sindex_block, sindexes_out); } void set_secondary_index(buf_lock_t *sindex_block, const sindex_name_t &name, const secondary_index_t &sindex) { std::map<sindex_name_t, secondary_index_t> sindex_map; get_secondary_indexes_internal(sindex_block, &sindex_map); /* We insert even if it already exists overwriting the old value. */ sindex_map[name] = sindex; set_secondary_indexes_internal(sindex_block, sindex_map); } void set_secondary_index(buf_lock_t *sindex_block, uuid_u id, const secondary_index_t &sindex) { std::map<sindex_name_t, secondary_index_t> sindex_map; get_secondary_indexes_internal(sindex_block, &sindex_map); for (auto it = sindex_map.begin(); it != sindex_map.end(); ++it) { if (it->second.id == id) { guarantee(sindex.id == id, "This shouldn't change the id."); it->second = sindex; } } set_secondary_indexes_internal(sindex_block, sindex_map); } bool delete_secondary_index(buf_lock_t *sindex_block, const sindex_name_t &name) { std::map<sindex_name_t, secondary_index_t> sindex_map; get_secondary_indexes_internal(sindex_block, &sindex_map); if (sindex_map.erase(name) == 1) { set_secondary_indexes_internal(sindex_block, sindex_map); return true; } else { return false; } } <|endoftext|>
<commit_before>/* bzflag * Copyright (c) 1993 - 2005 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named LICENSE that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ // Provide BZFS with a list server connection /* class header */ #include "ListServerConnection.h" /* system implementation headers */ #include <string.h> #include <string> #include <math.h> #include <errno.h> #include <set> /* common implementation headers */ #include "bzfio.h" #include "version.h" #include "TextUtils.h" #include "Protocol.h" #include "GameKeeper.h" #include "bzfsAPI.h" #include "WorldEventManager.h" /* local implementation headers */ #include "CmdLineOptions.h" // FIXME remove externs! extern PingPacket getTeamCounts(); extern uint16_t curMaxPlayers; extern void sendMessage(int playerIndex, PlayerId targetPlayer, const char *message); extern void sendPlayerInfo(void); extern void sendIPUpdate(int targetPlayer, int playerIndex); extern CmdLineOptions *clOptions; const int ListServerLink::NotConnected = -1; ListServerLink::ListServerLink(std::string listServerURL, std::string publicizedAddress, std::string publicizedTitle, std::string _advertiseGroups) { std::string bzfsUserAgent = "bzfs "; bzfsUserAgent += getAppVersion(); setURL(listServerURL); setUserAgent(bzfsUserAgent); setDNSCachingTime(-1); if (clOptions->pingInterface != "") setInterface(clOptions->pingInterface); publicizeAddress = publicizedAddress; publicizeDescription = publicizedTitle; advertiseGroups = _advertiseGroups; //if this c'tor is called, it's safe to publicize publicizeServer = true; queuedRequest = false; // schedule initial ADD message queueMessage(ListServerLink::ADD); } ListServerLink::ListServerLink() { // does not create a usable link, so checks should be placed // in all public member functions to ensure that nothing tries // to happen if publicizeServer is false publicizeServer = false; } ListServerLink::~ListServerLink() { // now tell the list server that we're going away. this can // take some time but we don't want to wait too long. we do // our own multiplexing loop and wait for a maximum of 3 seconds // total. // if we aren't supposed to be publicizing, skip the whole thing // and don't waste 3 seconds. if (!publicizeServer) return; queueMessage(ListServerLink::REMOVE); for (int i = 0; i < 12; i++) { cURLManager::perform(); if (!queuedRequest) break; TimeKeeper::sleep(0.25f); } } void ListServerLink::finalization(char *data, unsigned int length, bool good) { queuedRequest = false; if (good && (length < 2048)) { char buf[2048]; memcpy(buf, data, length); int bytes = length; buf[bytes]=0; char* base = buf; static char *tokGoodIdentifier = "TOKGOOD: "; static char *tokBadIdentifier = "TOKBAD: "; // walks entire reply including HTTP headers while (*base) { // find next newline char* scan = base; while (*scan && *scan != '\r' && *scan != '\n') scan++; // if no newline then no more complete replies if (*scan != '\r' && *scan != '\n') break; while (*scan && (*scan == '\r' || *scan == '\n')) *scan++ = '\0'; DEBUG4("Got line: \"%s\"\n", base); // TODO don't do this if we don't want central logins if (strncmp(base, tokGoodIdentifier, strlen(tokGoodIdentifier)) == 0) { char *callsign, *group; callsign = base + strlen(tokGoodIdentifier); DEBUG3("Got: %s\n", base); group = callsign; while (*group && (*group != ':')) group++; while (*group && (*group == ':')) *group++ = 0; int playerIndex; GameKeeper::Player *playerData; for (playerIndex = 0; playerIndex < curMaxPlayers; playerIndex++) { playerData = GameKeeper::Player::getPlayerByIndex(playerIndex); if (!playerData) continue; if (playerData->_LSAState != GameKeeper::Player::checking) continue; if (!TextUtils::compare_nocase(playerData->player.getCallSign(), callsign)) break; } if (playerIndex < curMaxPlayers) { // don't accept the global auth if there's a local account // of the same name and the local account is not marked as // being the same as the global account if (!playerData->accessInfo.hasRealPassword() || playerData->accessInfo.getUserInfo(callsign) .hasGroup("LOCAL.GLOBAL")) { playerData->_LSAState = GameKeeper::Player::verified; if (!playerData->accessInfo.isRegistered()) playerData->accessInfo.storeInfo(NULL); playerData->accessInfo.setPermissionRights(); while (*group) { char *nextgroup = group; while (*nextgroup && (*nextgroup != ':')) nextgroup++; while (*nextgroup && (*nextgroup == ':')) *nextgroup++ = 0; playerData->accessInfo.addGroup(group); group = nextgroup; } playerData->authentication.global(true); sendMessage(ServerPlayer, playerIndex, "Global login approved!"); sendIPUpdate(playerIndex, -1); sendPlayerInfo(); } else { playerData->_LSAState = GameKeeper::Player::failed; sendMessage(ServerPlayer, playerIndex, "Global login rejected. " "This callsign is registered locally on this " "server."); sendMessage(ServerPlayer, playerIndex, "If the local account is yours, " "/identify, /deregister and reconnnect, " "or ask an admin for the LOCAL.GLOBAL group."); sendMessage(ServerPlayer, playerIndex, "If it is not yours, please ask an admin " "to deregister it so that you may use your global " "callsign."); } playerData->setNeedThisHostbanChecked(true); playerData->player.clearToken(); } } else if (!strncmp(base, tokBadIdentifier, strlen(tokBadIdentifier))) { char *callsign; callsign = base + strlen(tokBadIdentifier); int playerIndex; GameKeeper::Player *playerData; for (playerIndex = 0; playerIndex < curMaxPlayers; playerIndex++) { playerData = GameKeeper::Player::getPlayerByIndex(playerIndex); if (!playerData) continue; if (playerData->_LSAState != GameKeeper::Player::checking) continue; if (!TextUtils::compare_nocase(playerData->player.getCallSign(), callsign)) break; } DEBUG3("Got: [%d] %s\n", playerIndex, base); if (playerIndex < curMaxPlayers) { playerData->_LSAState = GameKeeper::Player::failed; sendMessage(ServerPlayer, playerIndex, "Global login rejected, bad token."); playerData->setNeedThisHostbanChecked(true); playerData->player.clearToken(); } } // next reply base = scan; } } for (int i = 0; i < curMaxPlayers; i++) { GameKeeper::Player *playerData = GameKeeper::Player::getPlayerByIndex(i); if (!playerData) continue; if (playerData->_LSAState != GameKeeper::Player::checking) continue; playerData->_LSAState = GameKeeper::Player::timed; } if (nextMessageType != ListServerLink::NONE) { // There was a pending request arrived after we write: // we should redo all the stuff sendQueuedMessages(); } } void ListServerLink::queueMessage(MessageType type) { // ignore if the server is not public if (!publicizeServer) return; // record next message to send. nextMessageType = type; if (!queuedRequest) sendQueuedMessages(); else DEBUG3("There is a message already queued to the list server: not sending this one yet.\n"); } void ListServerLink::sendQueuedMessages() { queuedRequest = true; if (nextMessageType == ListServerLink::ADD) { DEBUG3("Queuing ADD message to list server\n"); bz_ListServerUpdateEvent updateEvent; updateEvent.address = publicizeAddress; updateEvent.description = publicizeDescription; updateEvent.groups = advertiseGroups; worldEventManager.callEvents(bz_eListServerUpdateEvent,-1,&updateEvent); addMe(getTeamCounts(), std::string(updateEvent.address.c_str()), std::string(updateEvent.description.c_str()), std::string(updateEvent.groups.c_str())); lastAddTime = TimeKeeper::getCurrent(); } else if (nextMessageType == ListServerLink::REMOVE) { DEBUG3("Queuing REMOVE message to list server\n"); removeMe(publicizeAddress); } nextMessageType = ListServerLink::NONE; } void ListServerLink::addMe(PingPacket pingInfo, std::string publicizedAddress, std::string publicizedTitle, std::string _advertiseGroups) { std::string msg; std::string hdr; // encode ping reply as ascii hex digits plus NULL char gameInfo[PingPacketHexPackedSize + 1]; pingInfo.packHex(gameInfo); // send ADD message (must send blank line) msg = "action=ADD&nameport="; msg += publicizedAddress; msg += "&version="; msg += getServerVersion(); msg += "&gameinfo="; msg += gameInfo; msg += "&build="; msg += getAppVersion(); msg += "&checktokens="; std::set<std::string> callSigns; // callsign1@ip1=token1%0D%0Acallsign2@ip2=token2%0D%0A for (int i = 0; i < curMaxPlayers; i++) { GameKeeper::Player *playerData = GameKeeper::Player::getPlayerByIndex(i); if (!playerData) continue; if ((playerData->_LSAState != GameKeeper::Player::required) && (playerData->_LSAState != GameKeeper::Player::requesting)) continue; if (callSigns.count(playerData->player.getCallSign())) continue; callSigns.insert(playerData->player.getCallSign()); playerData->_LSAState = GameKeeper::Player::checking; NetHandler *handler = playerData->netHandler; msg += TextUtils::url_encode(playerData->player.getCallSign()); Address addr = handler->getIPAddress(); if (!addr.isPrivate()) { msg += "@"; msg += handler->getTargetIP(); } msg += "="; msg += playerData->player.getToken(); msg += "%0D%0A"; } msg += "&groups="; // *groups=GROUP0%0D%0AGROUP1%0D%0A PlayerAccessMap::iterator itr = groupAccess.begin(); for ( ; itr != groupAccess.end(); itr++) { if (itr->first.substr(0, 6) != "LOCAL.") { msg += itr->first.c_str(); msg += "%0D%0A"; } } msg += "&advertgroups="; msg += _advertiseGroups; msg += "&title="; msg += publicizedTitle; setPostMode(msg); addHandle(); } void ListServerLink::removeMe(std::string publicizedAddress) { std::string msg; msg = "action=REMOVE&nameport="; msg += publicizedAddress; setPostMode(msg); addHandle(); } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <commit_msg>Timeout on connect is 15 sec<commit_after>/* bzflag * Copyright (c) 1993 - 2005 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named LICENSE that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ // Provide BZFS with a list server connection /* class header */ #include "ListServerConnection.h" /* system implementation headers */ #include <string.h> #include <string> #include <math.h> #include <errno.h> #include <set> /* common implementation headers */ #include "bzfio.h" #include "version.h" #include "TextUtils.h" #include "Protocol.h" #include "GameKeeper.h" #include "bzfsAPI.h" #include "WorldEventManager.h" /* local implementation headers */ #include "CmdLineOptions.h" // FIXME remove externs! extern PingPacket getTeamCounts(); extern uint16_t curMaxPlayers; extern void sendMessage(int playerIndex, PlayerId targetPlayer, const char *message); extern void sendPlayerInfo(void); extern void sendIPUpdate(int targetPlayer, int playerIndex); extern CmdLineOptions *clOptions; const int ListServerLink::NotConnected = -1; ListServerLink::ListServerLink(std::string listServerURL, std::string publicizedAddress, std::string publicizedTitle, std::string _advertiseGroups) { std::string bzfsUserAgent = "bzfs "; bzfsUserAgent += getAppVersion(); setURL(listServerURL); setUserAgent(bzfsUserAgent); setDNSCachingTime(-1); setTimeout(10); if (clOptions->pingInterface != "") setInterface(clOptions->pingInterface); publicizeAddress = publicizedAddress; publicizeDescription = publicizedTitle; advertiseGroups = _advertiseGroups; //if this c'tor is called, it's safe to publicize publicizeServer = true; queuedRequest = false; // schedule initial ADD message queueMessage(ListServerLink::ADD); } ListServerLink::ListServerLink() { // does not create a usable link, so checks should be placed // in all public member functions to ensure that nothing tries // to happen if publicizeServer is false publicizeServer = false; } ListServerLink::~ListServerLink() { // now tell the list server that we're going away. this can // take some time but we don't want to wait too long. we do // our own multiplexing loop and wait for a maximum of 3 seconds // total. // if we aren't supposed to be publicizing, skip the whole thing // and don't waste 3 seconds. if (!publicizeServer) return; queueMessage(ListServerLink::REMOVE); for (int i = 0; i < 12; i++) { cURLManager::perform(); if (!queuedRequest) break; TimeKeeper::sleep(0.25f); } } void ListServerLink::finalization(char *data, unsigned int length, bool good) { queuedRequest = false; if (good && (length < 2048)) { char buf[2048]; memcpy(buf, data, length); int bytes = length; buf[bytes]=0; char* base = buf; static char *tokGoodIdentifier = "TOKGOOD: "; static char *tokBadIdentifier = "TOKBAD: "; // walks entire reply including HTTP headers while (*base) { // find next newline char* scan = base; while (*scan && *scan != '\r' && *scan != '\n') scan++; // if no newline then no more complete replies if (*scan != '\r' && *scan != '\n') break; while (*scan && (*scan == '\r' || *scan == '\n')) *scan++ = '\0'; DEBUG4("Got line: \"%s\"\n", base); // TODO don't do this if we don't want central logins if (strncmp(base, tokGoodIdentifier, strlen(tokGoodIdentifier)) == 0) { char *callsign, *group; callsign = base + strlen(tokGoodIdentifier); DEBUG3("Got: %s\n", base); group = callsign; while (*group && (*group != ':')) group++; while (*group && (*group == ':')) *group++ = 0; int playerIndex; GameKeeper::Player *playerData; for (playerIndex = 0; playerIndex < curMaxPlayers; playerIndex++) { playerData = GameKeeper::Player::getPlayerByIndex(playerIndex); if (!playerData) continue; if (playerData->_LSAState != GameKeeper::Player::checking) continue; if (!TextUtils::compare_nocase(playerData->player.getCallSign(), callsign)) break; } if (playerIndex < curMaxPlayers) { // don't accept the global auth if there's a local account // of the same name and the local account is not marked as // being the same as the global account if (!playerData->accessInfo.hasRealPassword() || playerData->accessInfo.getUserInfo(callsign) .hasGroup("LOCAL.GLOBAL")) { playerData->_LSAState = GameKeeper::Player::verified; if (!playerData->accessInfo.isRegistered()) playerData->accessInfo.storeInfo(NULL); playerData->accessInfo.setPermissionRights(); while (*group) { char *nextgroup = group; while (*nextgroup && (*nextgroup != ':')) nextgroup++; while (*nextgroup && (*nextgroup == ':')) *nextgroup++ = 0; playerData->accessInfo.addGroup(group); group = nextgroup; } playerData->authentication.global(true); sendMessage(ServerPlayer, playerIndex, "Global login approved!"); sendIPUpdate(playerIndex, -1); sendPlayerInfo(); } else { playerData->_LSAState = GameKeeper::Player::failed; sendMessage(ServerPlayer, playerIndex, "Global login rejected. " "This callsign is registered locally on this " "server."); sendMessage(ServerPlayer, playerIndex, "If the local account is yours, " "/identify, /deregister and reconnnect, " "or ask an admin for the LOCAL.GLOBAL group."); sendMessage(ServerPlayer, playerIndex, "If it is not yours, please ask an admin " "to deregister it so that you may use your global " "callsign."); } playerData->setNeedThisHostbanChecked(true); playerData->player.clearToken(); } } else if (!strncmp(base, tokBadIdentifier, strlen(tokBadIdentifier))) { char *callsign; callsign = base + strlen(tokBadIdentifier); int playerIndex; GameKeeper::Player *playerData; for (playerIndex = 0; playerIndex < curMaxPlayers; playerIndex++) { playerData = GameKeeper::Player::getPlayerByIndex(playerIndex); if (!playerData) continue; if (playerData->_LSAState != GameKeeper::Player::checking) continue; if (!TextUtils::compare_nocase(playerData->player.getCallSign(), callsign)) break; } DEBUG3("Got: [%d] %s\n", playerIndex, base); if (playerIndex < curMaxPlayers) { playerData->_LSAState = GameKeeper::Player::failed; sendMessage(ServerPlayer, playerIndex, "Global login rejected, bad token."); playerData->setNeedThisHostbanChecked(true); playerData->player.clearToken(); } } // next reply base = scan; } } for (int i = 0; i < curMaxPlayers; i++) { GameKeeper::Player *playerData = GameKeeper::Player::getPlayerByIndex(i); if (!playerData) continue; if (playerData->_LSAState != GameKeeper::Player::checking) continue; playerData->_LSAState = GameKeeper::Player::timed; } if (nextMessageType != ListServerLink::NONE) { // There was a pending request arrived after we write: // we should redo all the stuff sendQueuedMessages(); } } void ListServerLink::queueMessage(MessageType type) { // ignore if the server is not public if (!publicizeServer) return; // record next message to send. nextMessageType = type; if (!queuedRequest) sendQueuedMessages(); else DEBUG3("There is a message already queued to the list server: not sending this one yet.\n"); } void ListServerLink::sendQueuedMessages() { queuedRequest = true; if (nextMessageType == ListServerLink::ADD) { DEBUG3("Queuing ADD message to list server\n"); bz_ListServerUpdateEvent updateEvent; updateEvent.address = publicizeAddress; updateEvent.description = publicizeDescription; updateEvent.groups = advertiseGroups; worldEventManager.callEvents(bz_eListServerUpdateEvent,-1,&updateEvent); addMe(getTeamCounts(), std::string(updateEvent.address.c_str()), std::string(updateEvent.description.c_str()), std::string(updateEvent.groups.c_str())); lastAddTime = TimeKeeper::getCurrent(); } else if (nextMessageType == ListServerLink::REMOVE) { DEBUG3("Queuing REMOVE message to list server\n"); removeMe(publicizeAddress); } nextMessageType = ListServerLink::NONE; } void ListServerLink::addMe(PingPacket pingInfo, std::string publicizedAddress, std::string publicizedTitle, std::string _advertiseGroups) { std::string msg; std::string hdr; // encode ping reply as ascii hex digits plus NULL char gameInfo[PingPacketHexPackedSize + 1]; pingInfo.packHex(gameInfo); // send ADD message (must send blank line) msg = "action=ADD&nameport="; msg += publicizedAddress; msg += "&version="; msg += getServerVersion(); msg += "&gameinfo="; msg += gameInfo; msg += "&build="; msg += getAppVersion(); msg += "&checktokens="; std::set<std::string> callSigns; // callsign1@ip1=token1%0D%0Acallsign2@ip2=token2%0D%0A for (int i = 0; i < curMaxPlayers; i++) { GameKeeper::Player *playerData = GameKeeper::Player::getPlayerByIndex(i); if (!playerData) continue; if ((playerData->_LSAState != GameKeeper::Player::required) && (playerData->_LSAState != GameKeeper::Player::requesting)) continue; if (callSigns.count(playerData->player.getCallSign())) continue; callSigns.insert(playerData->player.getCallSign()); playerData->_LSAState = GameKeeper::Player::checking; NetHandler *handler = playerData->netHandler; msg += TextUtils::url_encode(playerData->player.getCallSign()); Address addr = handler->getIPAddress(); if (!addr.isPrivate()) { msg += "@"; msg += handler->getTargetIP(); } msg += "="; msg += playerData->player.getToken(); msg += "%0D%0A"; } msg += "&groups="; // *groups=GROUP0%0D%0AGROUP1%0D%0A PlayerAccessMap::iterator itr = groupAccess.begin(); for ( ; itr != groupAccess.end(); itr++) { if (itr->first.substr(0, 6) != "LOCAL.") { msg += itr->first.c_str(); msg += "%0D%0A"; } } msg += "&advertgroups="; msg += _advertiseGroups; msg += "&title="; msg += publicizedTitle; setPostMode(msg); addHandle(); } void ListServerLink::removeMe(std::string publicizedAddress) { std::string msg; msg = "action=REMOVE&nameport="; msg += publicizedAddress; setPostMode(msg); addHandle(); } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <|endoftext|>
<commit_before>#include <algorithm> #include <functional> #include <utility> #include <vector> #include "caffe/layer.hpp" #include "caffe/vision_layers.hpp" namespace caffe { template <typename Dtype> void ArgMaxLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { const ArgMaxParameter& argmax_param = this->layer_param_.argmax_param(); out_max_val_ = argmax_param.out_max_val(); top_k_ = argmax_param.top_k(); has_axis_ = argmax_param.has_axis(); CHECK_GE(top_k_, 1) << "top k must not be less than 1."; if (has_axis_) { axis_ = bottom[0]->CanonicalAxisIndex(argmax_param.axis()); CHECK_GE(axis_, 0) << "axis must not be less than 0."; CHECK_LE(axis_, bottom[0]->num_axes()) << "axis must be less than or equal to the number of axis."; CHECK_LE(top_k_, bottom[0]->shape(axis_)) << "top_k must be less than or equal to the dimension of the axis."; } else { CHECK_LE(top_k_, bottom[0]->count(1)) << "top_k must be less than or equal to" " the dimension of the flattened bottom blob per instance."; } } template <typename Dtype> void ArgMaxLayer<Dtype>::Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { if (out_max_val_) { // Produces max_ind and max_val top[0]->Reshape(bottom[0]->num(), 2, top_k_, 1); } else { // Produces only max_ind top[0]->Reshape(bottom[0]->num(), 1, top_k_, 1); } } template <typename Dtype> void ArgMaxLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { const Dtype* bottom_data = bottom[0]->cpu_data(); Dtype* top_data = top[0]->mutable_cpu_data(); int num = bottom[0]->num(); int dim = bottom[0]->count() / bottom[0]->num(); for (int i = 0; i < num; ++i) { std::vector<std::pair<Dtype, int> > bottom_data_vector; for (int j = 0; j < dim; ++j) { bottom_data_vector.push_back( std::make_pair(bottom_data[i * dim + j], j)); } std::partial_sort( bottom_data_vector.begin(), bottom_data_vector.begin() + top_k_, bottom_data_vector.end(), std::greater<std::pair<Dtype, int> >()); for (int j = 0; j < top_k_; ++j) { top_data[top[0]->offset(i, 0, j)] = bottom_data_vector[j].second; } if (out_max_val_) { for (int j = 0; j < top_k_; ++j) { top_data[top[0]->offset(i, 1, j)] = bottom_data_vector[j].first; } } } } INSTANTIATE_CLASS(ArgMaxLayer); REGISTER_LAYER_CLASS(ArgMax); } // namespace caffe <commit_msg>Argmax axis implimentation<commit_after>#include <algorithm> #include <functional> #include <utility> #include <vector> #include "caffe/common_layers.hpp" namespace caffe { template <typename Dtype> void ArgMaxLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { const ArgMaxParameter& argmax_param = this->layer_param_.argmax_param(); out_max_val_ = argmax_param.out_max_val(); top_k_ = argmax_param.top_k(); has_axis_ = argmax_param.has_axis(); CHECK_GE(top_k_, 1) << "top k must not be less than 1."; if (has_axis_) { axis_ = bottom[0]->CanonicalAxisIndex(argmax_param.axis()); CHECK_GE(axis_, 0) << "axis must not be less than 0."; CHECK_LE(axis_, bottom[0]->num_axes()) << "axis must be less than or equal to the number of axis."; CHECK_LE(top_k_, bottom[0]->shape(axis_)) << "top_k must be less than or equal to the dimension of the axis."; } else { CHECK_LE(top_k_, bottom[0]->count(1)) << "top_k must be less than or equal to" " the dimension of the flattened bottom blob per instance."; } } template <typename Dtype> void ArgMaxLayer<Dtype>::Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { int num_top_axes = bottom[0]->num_axes(); if ( num_top_axes < 3 ) num_top_axes = 3; std::vector<int> shape(num_top_axes, 1); if (has_axis_) { // Produces max_ind or max_val per axis shape = bottom[0]->shape(); shape[axis_] = top_k_; } else { shape[0] = bottom[0]->shape(0); // Produces max_ind shape[2] = top_k_; if (out_max_val_) { // Produces max_ind and max_val shape[1] = 2; } } top[0]->Reshape(shape); } template <typename Dtype> void ArgMaxLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { const Dtype* bottom_data = bottom[0]->cpu_data(); Dtype* top_data = top[0]->mutable_cpu_data(); int dim, axis_dist; if (has_axis_) { dim = bottom[0]->shape(axis_); // Distance between values of axis in blob axis_dist = bottom[0]->count(axis_) / dim; } else { dim = bottom[0]->count(1); axis_dist = 1; } int num = bottom[0]->count() / dim; std::vector<std::pair<Dtype, int> > bottom_data_vector(dim); for (int i = 0; i < num; ++i) { for (int j = 0; j < dim; ++j) { bottom_data_vector[j] = std::make_pair( bottom_data[(i / axis_dist * dim + j) * axis_dist + i % axis_dist], j); } std::partial_sort( bottom_data_vector.begin(), bottom_data_vector.begin() + top_k_, bottom_data_vector.end(), std::greater<std::pair<Dtype, int> >()); for (int j = 0; j < top_k_; ++j) { if (out_max_val_) { if (has_axis_) { // Produces max_val per axis top_data[(i / axis_dist * top_k_ + j) * axis_dist + i % axis_dist] = bottom_data_vector[j].first; } else { // Produces max_ind and max_val top_data[2 * i * top_k_ + j] = bottom_data_vector[j].second; top_data[2 * i * top_k_ + top_k_ + j] = bottom_data_vector[j].first; } } else { // Produces max_ind per axis top_data[(i / axis_dist * top_k_ + j) * axis_dist + i % axis_dist] = bottom_data_vector[j].second; } } } } INSTANTIATE_CLASS(ArgMaxLayer); REGISTER_LAYER_CLASS(ArgMax); } // namespace caffe <|endoftext|>
<commit_before>// Copyright 2014 BVLC and contributors. #include <vector> #include "caffe/layer.hpp" #include "caffe/vision_layers.hpp" #include "caffe/util/math_functions.hpp" namespace caffe { template <typename Dtype> void ConcatLayer<Dtype>::SetUp(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) { Layer<Dtype>::SetUp(bottom, top); concat_dim_ = this->layer_param_.concat_param().concat_dim(); CHECK_GE(concat_dim_, 0) << "concat_dim should be >= 0"; CHECK_LE(concat_dim_, 1) << "For now concat_dim <=1, it can only concat num and channels"; // Initialize with the first blob. count_ = bottom[0]->count(); num_ = bottom[0]->num(); channels_ = bottom[0]->channels(); height_ = bottom[0]->height(); width_ = bottom[0]->width(); depth_ = bottom[0]->depth(); for (int i = 1; i < bottom.size(); ++i) { count_ += bottom[i]->count(); if (concat_dim_== 0) { num_ += bottom[i]->num(); } else if (concat_dim_ == 1) { channels_ += bottom[i]->channels(); } else if (concat_dim_ == 2) { height_ += bottom[i]->height(); } else if (concat_dim_ == 3) { width_ += bottom[i]->width(); } else if (concat_dim_ == 4) { depth_ += bottom[i]->depth(); } } (*top)[0]->Reshape(num_, channels_, height_, width_, depth_); CHECK_EQ(count_, (*top)[0]->count()); } template <typename Dtype> Dtype ConcatLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) { Dtype* top_data = (*top)[0]->mutable_cpu_data(); if (concat_dim_== 0) { int offset_num = 0; for (int i = 0; i < bottom.size(); ++i) { const Dtype* bottom_data = bottom[i]->cpu_data(); Dtype sum_bottom=0; int num_elem = bottom[i]->count(); for(int k=0;k<num_elem;k++){ sum_bottom=sum_bottom+bottom_data[k]; } if (sum_bottom==0){ LOG(INFO)<<"bottom "<<i<< "= 0"; } caffe_copy(num_elem, bottom_data, top_data+(*top)[0]->offset(offset_num)); offset_num += bottom[i]->num(); } } else if (concat_dim_ == 1) { int offset_channel = 0; for (int i = 0; i < bottom.size(); ++i) { const Dtype* bottom_data = bottom[i]->cpu_data(); int num_elem = bottom[i]->channels()*bottom[i]->height()*bottom[i]->width()*bottom[i]->depth(); for (int n = 0; n < num_; ++n) { caffe_copy(num_elem, bottom_data+bottom[i]->offset(n), top_data+(*top)[0]->offset(n, offset_channel)); } offset_channel += bottom[i]->channels(); } // concat_dim_ is guaranteed to be 0 or 1 by SetUp. } return Dtype(0.); } template <typename Dtype> void ConcatLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom) { const Dtype* top_diff = top[0]->cpu_diff(); if (concat_dim_ == 0) { int offset_num = 0; for (int i = 0; i < bottom->size(); ++i) { Blob<Dtype>* blob = (*bottom)[i]; if (propagate_down[i]) { Dtype* bottom_diff = blob->mutable_cpu_diff(); caffe_copy(blob->count(), top_diff + top[0]->offset(offset_num), bottom_diff); } offset_num += blob->num(); } } else if (concat_dim_ == 1) { int offset_channel = 0; for (int i = 0; i < bottom->size(); ++i) { Blob<Dtype>* blob = (*bottom)[i]; if (propagate_down[i]) { Dtype* bottom_diff = blob->mutable_cpu_diff(); int num_elem = blob->channels()*blob->height()*blob->width(); for (int n = 0; n < num_; ++n) { caffe_copy(num_elem, top_diff + top[0]->offset(n, offset_channel), bottom_diff + blob->offset(n)); } } offset_channel += blob->channels(); } } // concat_dim_ is guaranteed to be 0 or 1 by SetUp. } INSTANTIATE_CLASS(ConcatLayer); } // namespace caffe <commit_msg>correction for 3d reshape<commit_after>// Copyright 2014 BVLC and contributors. #include <vector> #include "caffe/layer.hpp" #include "caffe/vision_layers.hpp" #include "caffe/util/math_functions.hpp" namespace caffe { template <typename Dtype> void ConcatLayer<Dtype>::SetUp(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) { Layer<Dtype>::SetUp(bottom, top); concat_dim_ = this->layer_param_.concat_param().concat_dim(); CHECK_GE(concat_dim_, 0) << "concat_dim should be >= 0"; CHECK_LE(concat_dim_, 1) << "For now concat_dim <=1, it can only concat num and channels"; // Initialize with the first blob. count_ = bottom[0]->count(); num_ = bottom[0]->num(); channels_ = bottom[0]->channels(); height_ = bottom[0]->height(); width_ = bottom[0]->width(); depth_ = bottom[0]->depth(); for (int i = 1; i < bottom.size(); ++i) { count_ += bottom[i]->count(); if (concat_dim_== 0) { num_ += bottom[i]->num(); } else if (concat_dim_ == 1) { channels_ += bottom[i]->channels(); } else if (concat_dim_ == 2) { height_ += bottom[i]->height(); } else if (concat_dim_ == 3) { width_ += bottom[i]->width(); } else if (concat_dim_ == 4) { depth_ += bottom[i]->depth(); } } (*top)[0]->Reshape(num_, channels_, height_, width_, depth_); CHECK_EQ(count_, (*top)[0]->count()); } template <typename Dtype> Dtype ConcatLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) { Dtype* top_data = (*top)[0]->mutable_cpu_data(); if (concat_dim_== 0) { int offset_num = 0; for (int i = 0; i < bottom.size(); ++i) { const Dtype* bottom_data = bottom[i]->cpu_data(); Dtype sum_bottom=0; int num_elem = bottom[i]->count(); for(int k=0;k<num_elem;k++){ sum_bottom=sum_bottom+bottom_data[k]; } if (sum_bottom==0){ LOG(INFO)<<"bottom "<<i<< "= 0"; } caffe_copy(num_elem, bottom_data, top_data+(*top)[0]->offset(offset_num)); offset_num += bottom[i]->num(); } } else if (concat_dim_ == 1) { int offset_channel = 0; for (int i = 0; i < bottom.size(); ++i) { const Dtype* bottom_data = bottom[i]->cpu_data(); int num_elem = bottom[i]->channels()*bottom[i]->height()*bottom[i]->width()*bottom[i]->depth(); for (int n = 0; n < num_; ++n) { caffe_copy(num_elem, bottom_data+bottom[i]->offset(n), top_data+(*top)[0]->offset(n, offset_channel)); } offset_channel += bottom[i]->channels(); } // concat_dim_ is guaranteed to be 0 or 1 by SetUp. } return Dtype(0.); } template <typename Dtype> void ConcatLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom) { const Dtype* top_diff = top[0]->cpu_diff(); if (concat_dim_ == 0) { int offset_num = 0; for (int i = 0; i < bottom->size(); ++i) { Blob<Dtype>* blob = (*bottom)[i]; if (propagate_down[i]) { Dtype* bottom_diff = blob->mutable_cpu_diff(); caffe_copy(blob->count(), top_diff + top[0]->offset(offset_num), bottom_diff); } offset_num += blob->num(); } } else if (concat_dim_ == 1) { int offset_channel = 0; for (int i = 0; i < bottom->size(); ++i) { Blob<Dtype>* blob = (*bottom)[i]; if (propagate_down[i]) { Dtype* bottom_diff = blob->mutable_cpu_diff(); int num_elem = blob->channels()*blob->height()*blob->width()*blob->depth(); for (int n = 0; n < num_; ++n) { caffe_copy(num_elem, top_diff + top[0]->offset(n, offset_channel), bottom_diff + blob->offset(n)); } } offset_channel += blob->channels(); } } // concat_dim_ is guaranteed to be 0 or 1 by SetUp. } INSTANTIATE_CLASS(ConcatLayer); } // namespace caffe <|endoftext|>
<commit_before>/*!\page test_twobody Twobody * This program will simulate two protein molecules * in a dielectric solvent with explicit mobile ions. * The container is SPHERICAL w. hard walls. * * \author Mikael Lund * \date Prague 2007 * \todo Maybe use a cylindrical cell? * \include twobody.cpp */ #include "faunus/faunus.h" #include "faunus/potentials/pot_coulomb.h" using namespace Faunus; using namespace std; int main(int argc, char* argv[]) { slump slp; cout << faunus_splash(); // Faunus info string config = "twobody.conf"; // Default input (parameter) file if (argc==2) config = argv[1]; // ..also try to get it from the command line inputfile in(config); // Read input file checkValue test(in); // Test output mcloop loop(in); // Set Markov chain loop lengths cell cell(in); // We want a spherical, hard cell canonical nvt; // Use the canonical ensemble interaction<pot_coulomb> pot(in); // Functions for interactions distributions dst; // Distance dep. averages FAUrdf saltrdf(atom["NA"].id,atom["CL"].id, .5, cell.r); atomicRdf gofr_pp(0.5,200); // Amino acid rdf between the two proteins twostatebinding bind(20.); // Two state binding model float gofr_pp_rf=in.getflt("gofr_pp_rf",0);// How often should gofr_pp be sampled? vector<macromolecule> g; // Group for proteins dualmove dm(nvt, cell, pot); // Class for 1D macromolecular translation dm.setup(in); dm.load( in, g, 80.); // Load proteins and separate them salt salt; // Group for mobile ions salt.add(cell, in); // Add salt particles saltmove sm(nvt, cell, pot, in); // Class for salt movements macrorot mr(nvt, cell, pot); // Class for macromolecule rotation iopqr pqr; // PQR output (pos, charge, radius) ioxtc xtc(1000.); // Gromacs xtc output ioaam aam; // Protein input file format is AAM //if (aam.load(cell,"confout.aam")) { aam.load(cell,"confout.aam"); g[0].masscenter(cell); // Load old config (if present) g[1].masscenter(cell); // ...and recalc mass centers //} float pH=in.getflt("pH", 7.); // Specify pH chargereg tit(nvt,cell,pot,salt,pH); // Prepare titration. systemenergy sys( pot.energy(cell.p, g[0], g[1]) + pot.energy(cell.p, salt) + pot.internalElectrostatic(cell.p, g[0]) + pot.internalElectrostatic(cell.p, g[1]) + pot.internal(cell.p, salt)); // System energy analysis cout << "# ---- Initial information ----" << endl << in.info() << cell.info() << tit.info() << pot.info(); // Print information to screen cout << "# ---- Runtime output ----" << endl; while ( loop.macroCnt() ) { // Markov chain while (loop.microCnt() ) { short i,n; switch (rand() % 4) { // Pick a random MC move case 0: // Displace salt sys+=sm.move(salt); // Do the move. break; case 1: // Rotate proteins for (n=0; n<2; n++) { // Loop over all proteins i = rand() % g.size(); // and pick at random. sys+=mr.move(g[i]); // Do the move. } break; case 2: // Translate proteins sys+=dm.move(g[0], g[1]); // Do the move. break; case 3: // Fluctuate charges sys+=tit.titrateall(); // Titrate sites on the protein if (tit.du!=0) { // Average charges and dipoles dst.add("Q1",dm.r, g[0].charge(cell.p)); dst.add("Q2",dm.r, g[1].charge(cell.p)); dst.add("MU1",dm.r,g[0].dipole(cell.p)); dst.add("MU2",dm.r,g[1].dipole(cell.p)); } break; } if (slp.random_one()>0.8) dst.add("Utot", dm.r, pot.energy(cell.p)); if (slp.random_one()<gofr_pp_rf) gofr_pp.update( cell.p, g[0], g[1] ); if (slp.random_one()>.5) { //saltrdf.update(cell); // Analyse salt g(r) //bind.update(cell, cell.p[g[0].beg], g[1]); } if (slp.random_one()>.995 && loop.macro>1) xtc.save("coord.xtc", cell.p); // Save trajectory } // End of inner loop sys.update( pot.energy(cell.p, g[0], g[1]) + pot.energy(cell.p, salt) + pot.internalElectrostatic(cell.p, g[0]) + pot.internalElectrostatic(cell.p, g[1]) + pot.internal(cell.p, salt)); // System energy analysis cell.check_vector(); // Check sanity of particle vector gofr_pp.write("rdfatomic.dat"); // Write interprotein g(r) - Atomic dm.gofr.write("rdfprot.dat"); // Write interprotein g(r) - CM saltrdf.write("rdfsalt.dat"); // Write salt g(r) dst.write("distributions.dat"); // Write other distributions aam.save("confout.aam", cell.p); // Save config. for next run pqr.save("confout.pqr", cell.p); // ...also save a PQR file (no salt) cout << loop.timing(); // Show progress } // End of outer loop xtc.close(); // Close xtc file for writing cout << "# ---- Final information ----" << endl << salt.info(cell) << sm.info() << mr.info() << dm.info() << sys.info() << g[0].info() << g[1].info() << cell.info() << tit.info() << bind.info( 1/cell.getvolume() ); // Output tests sys.check(test); test.check("Protein1_charge", g[0].Q.avg()); test.check("Protein2_charge", g[1].Q.avg()); cout << test.report(); return test.returnCode(); } <commit_msg>added extra dipole analysis to twobody<commit_after>/*!\page test_twobody Twobody * This program will simulate two protein molecules * in a dielectric solvent with explicit mobile ions. * The container is SPHERICAL w. hard walls. * * \author Mikael Lund * \date Prague 2007 * \todo Maybe use a cylindrical cell? * \include twobody.cpp */ #include "faunus/faunus.h" #include "faunus/potentials/pot_coulomb.h" using namespace Faunus; using namespace std; int main(int argc, char* argv[]) { slump slp; cout << faunus_splash(); // Faunus info string config = "twobody.conf"; // Default input (parameter) file if (argc==2) config = argv[1]; // ..also try to get it from the command line inputfile in(config); // Read input file checkValue test(in); // Test output mcloop loop(in); // Set Markov chain loop lengths cell cell(in); // We want a spherical, hard cell canonical nvt; // Use the canonical ensemble interaction<pot_coulomb> pot(in); // Functions for interactions distributions dst; // Distance dep. averages FAUrdf saltrdf(atom["NA"].id,atom["CL"].id, .5, cell.r); atomicRdf gofr_pp(0.5,200); // Amino acid rdf between the two proteins twostatebinding bind(20.); // Two state binding model float gofr_pp_rf=in.getflt("gofr_pp_rf",0);// How often should gofr_pp be sampled? vector<macromolecule> g; // Group for proteins dualmove dm(nvt, cell, pot); // Class for 1D macromolecular translation dm.setup(in); dm.load( in, g, 80.); // Load proteins and separate them salt salt; // Group for mobile ions salt.add(cell, in); // Add salt particles saltmove sm(nvt, cell, pot, in); // Class for salt movements macrorot mr(nvt, cell, pot); // Class for macromolecule rotation iopqr pqr; // PQR output (pos, charge, radius) ioxtc xtc(1000.); // Gromacs xtc output ioaam aam; // Protein input file format is AAM //if (aam.load(cell,"confout.aam")) { aam.load(cell,"confout.aam"); g[0].masscenter(cell); // Load old config (if present) g[1].masscenter(cell); // ...and recalc mass centers //} float pH=in.getflt("pH", 7.); // Specify pH chargereg tit(nvt,cell,pot,salt,pH); // Prepare titration. systemenergy sys( pot.energy(cell.p, g[0], g[1]) + pot.energy(cell.p, salt) + pot.internalElectrostatic(cell.p, g[0]) + pot.internalElectrostatic(cell.p, g[1]) + pot.internal(cell.p, salt)); // System energy analysis cout << "# ---- Initial information ----" << endl << in.info() << cell.info() << tit.info() << pot.info(); // Print information to screen cout << "# ---- Runtime output ----" << endl; while ( loop.macroCnt() ) { // Markov chain while (loop.microCnt() ) { short i,n; switch (rand() % 4) { // Pick a random MC move case 0: // Displace salt sys+=sm.move(salt); // Do the move. break; case 1: // Rotate proteins for (n=0; n<2; n++) { // Loop over all proteins i = rand() % g.size(); // and pick at random. sys+=mr.move(g[i]); // Do the move. } break; case 2: // Translate proteins sys+=dm.move(g[0], g[1]); // Do the move. break; case 3: // Fluctuate charges sys+=tit.titrateall(); // Titrate sites on the protein break; } if (slp.random_one()>0.9) { dst.add("Utot", dm.r, pot.energy(cell.p)); } if (slp.random_one()<gofr_pp_rf) gofr_pp.update( cell.p, g[0], g[1] ); if (slp.random_one()>0) { dst.add("Q1",dm.r, g[0].charge(cell.p)); dst.add("Q2",dm.r, g[1].charge(cell.p)); dst.add("MU1",dm.r,g[0].dipole(cell.p)); dst.add("MU2",dm.r,g[1].dipole(cell.p)); double len0 = g[0].mu.len(); double len1 = g[1].mu.len(); if (len0>0) dst.add("MU1z",dm.r, g[0].mu.z / len0 ); if (len1>0) dst.add("MU2z",dm.r, g[1].mu.z / len1 ); if (len0*len1>0) dst.add("MUz1z2",dm.r, g[0].mu.z/len0 * g[1].mu.z/len1 ); //saltrdf.update(cell); // Analyse salt g(r) //bind.update(cell, cell.p[g[0].beg], g[1]); } if (slp.random_one()>.995 && loop.macro>1) xtc.save("coord.xtc", cell.p); // Save trajectory } // End of inner loop sys.update( pot.energy(cell.p, g[0], g[1]) + pot.energy(cell.p, salt) + pot.internalElectrostatic(cell.p, g[0]) + pot.internalElectrostatic(cell.p, g[1]) + pot.internal(cell.p, salt)); // System energy analysis cell.check_vector(); // Check sanity of particle vector gofr_pp.write("rdfatomic.dat"); // Write interprotein g(r) - Atomic dm.gofr.write("rdfprot.dat"); // Write interprotein g(r) - CM saltrdf.write("rdfsalt.dat"); // Write salt g(r) dst.write("distributions.dat"); // Write other distributions aam.save("confout.aam", cell.p); // Save config. for next run pqr.save("confout.pqr", cell.p); // ...also save a PQR file (no salt) cout << loop.timing(); // Show progress } // End of outer loop xtc.close(); // Close xtc file for writing cout << "# ---- Final information ----" << endl << salt.info(cell) << sm.info() << mr.info() << dm.info() << sys.info() << g[0].info() << g[1].info() << cell.info() << tit.info() << bind.info( 1/cell.getvolume() ); // Output tests sys.check(test); test.check("Protein1_charge", g[0].Q.avg()); test.check("Protein2_charge", g[1].Q.avg()); cout << test.report(); return test.returnCode(); } <|endoftext|>
<commit_before>#include <stdio.h> #include <math.h> #include <GL/glut.h> #include "Camera.h" void Camera::Init() { m_yaw = 70.0; m_pitch = -0.3; SetPos(-25, 17, -40); } void Camera::Refresh() { // Camera parameter according to Riegl's co-ordinate system // x/y for flat, z for height m_lx = cos(m_yaw) * cos(m_pitch); m_ly = sin(m_pitch); m_lz = sin(m_yaw) * cos(m_pitch); m_strafe_lx = cos(m_yaw - M_PI_2); m_strafe_lz = sin(m_yaw - M_PI_2); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(m_x, m_y, m_z, m_x + m_lx, m_y + m_ly, m_z + m_lz, 0.0,1.0,0.0); //printf("Camera: %f %f %f Direction vector: %f %f %f\n", m_x, m_y, m_z, m_lx, m_ly, m_lz); } void Camera::SetPos(float x, float y, float z) { m_x = x; m_y = y; m_z =z; Refresh(); } void Camera::GetPos(float &x, float &y, float &z) { x = m_x; y = m_y; z = m_z; } void Camera::GetDirectionVector(float &x, float &y, float &z) { x = m_lx; y = m_ly; z = m_lz; } void Camera::Move(float incr) { float lx = cos(m_yaw)*cos(m_pitch); float ly = sin(m_pitch); float lz = sin(m_yaw)*cos(m_pitch); m_x = m_x + incr*lx; m_y = m_y + incr*ly; m_z = m_z + incr*lz; Refresh(); } void Camera::Strafe(float incr) { m_x = m_x + incr*m_strafe_lx; m_z = m_z + incr*m_strafe_lz; Refresh(); } void Camera::Fly(float incr) { m_y = m_y + incr; Refresh(); } void Camera::RotateYaw(float angle) { m_yaw += angle; Refresh(); } void Camera::RotatePitch(float angle) { const float limit = 89.0 * M_PI / 180.0; m_pitch += angle; if(m_pitch < -limit) m_pitch = -limit; if(m_pitch > limit) m_pitch = limit; Refresh(); } void Camera::SetYaw(float angle) { m_yaw = angle; Refresh(); } void Camera::SetPitch(float angle) { m_pitch = angle; Refresh(); } <commit_msg>Set initial position<commit_after>#include <stdio.h> #include <math.h> #include <GL/glut.h> #include "Camera.h" void Camera::Init() { m_yaw = 67.5466; m_pitch = 1.07706; SetPos(8.8, -63, 40); } void Camera::Refresh() { // Camera parameter according to Riegl's co-ordinate system // x/y for flat, z for height m_lx = cos(m_yaw) * cos(m_pitch); m_ly = sin(m_pitch); m_lz = sin(m_yaw) * cos(m_pitch); m_strafe_lx = cos(m_yaw - M_PI_2); m_strafe_lz = sin(m_yaw - M_PI_2); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(m_x, m_y, m_z, m_x + m_lx, m_y + m_ly, m_z + m_lz, 0.0,1.0,0.0); //printf("Camera: %f %f %f Direction vector: %f %f %f\n", m_x, m_y, m_z, m_lx, m_ly, m_lz); } void Camera::SetPos(float x, float y, float z) { m_x = x; m_y = y; m_z =z; Refresh(); } void Camera::GetPos(float &x, float &y, float &z) { x = m_x; y = m_y; z = m_z; } void Camera::GetDirectionVector(float &x, float &y, float &z) { x = m_lx; y = m_ly; z = m_lz; } void Camera::Move(float incr) { float lx = cos(m_yaw)*cos(m_pitch); float ly = sin(m_pitch); float lz = sin(m_yaw)*cos(m_pitch); m_x = m_x + incr*lx; m_y = m_y + incr*ly; m_z = m_z + incr*lz; Refresh(); } void Camera::Strafe(float incr) { m_x = m_x + incr*m_strafe_lx; m_z = m_z + incr*m_strafe_lz; Refresh(); } void Camera::Fly(float incr) { m_y = m_y + incr; Refresh(); } void Camera::RotateYaw(float angle) { m_yaw += angle; Refresh(); } void Camera::RotatePitch(float angle) { const float limit = 89.0 * M_PI / 180.0; m_pitch += angle; if(m_pitch < -limit) m_pitch = -limit; if(m_pitch > limit) m_pitch = limit; Refresh(); } void Camera::SetYaw(float angle) { m_yaw = angle; Refresh(); } void Camera::SetPitch(float angle) { m_pitch = angle; Refresh(); } <|endoftext|>
<commit_before>// Actions specific to an NPC. #include "../clients/CClient.h" #include "../triggers.h" #include "CChar.h" // Add some enemy to my Attacker list bool CChar::Attacker_Add(CChar * pChar, int threat) { ADDTOCALLSTACK("CChar::Attacker_Add"); CUID uid = pChar->GetUID(); if (!m_lastAttackers.empty()) // Must only check for existing attackers if there are any attacker already. { for (auto it = m_lastAttackers.begin(), end = m_lastAttackers.end(); it != end; ++it) { LastAttackers & refAttacker = *it; if (refAttacker.charUID == uid) return true; // found one, no actions needed so we skip } } else if (IsTrigUsed(TRIGGER_COMBATSTART)) { TRIGRET_TYPE tRet = OnTrigger(CTRIG_CombatStart, pChar, 0); if (tRet == TRIGRET_RET_TRUE) return false; } CScriptTriggerArgs Args; bool fIgnore = false; Args.m_iN1 = threat; Args.m_iN2 = fIgnore; if (IsTrigUsed(TRIGGER_COMBATADD)) { TRIGRET_TYPE tRet = OnTrigger(CTRIG_CombatAdd, pChar, &Args); if (tRet == TRIGRET_RET_TRUE) return false; threat = (int)Args.m_iN1; fIgnore = (Args.m_iN2 != 0); } LastAttackers attacker; attacker.amountDone = 0; attacker.charUID = uid; attacker.elapsed = 0; attacker.threat = (m_pPlayer) ? 0 : threat; attacker.ignore = fIgnore; m_lastAttackers.emplace_back(std::move(attacker)); // Record the start of the fight. Memory_Fight_Start(pChar); tchar *z = Str_GetTemp(); if (!attacker.ignore) { //if ( GetTopSector()->GetCharComplexity() < 7 ) //{ if (!( g_Cfg.m_iEmoteFlags & EMOTEF_ATTACKER )) { HUE_TYPE emoteHue = (HUE_TYPE)(g_Exp.m_VarDefs.GetKeyNum("EMOTE_DEF_COLOR")); if (this && this->m_EmoteHueOverride) //Set EMOTECOLOROVERRIDE to ATTACKERS emoteHue = this->m_EmoteHueOverride; sprintf(z, g_Cfg.GetDefaultMsg(DEFMSG_COMBAT_ATTACKO), GetName(), pChar->GetName()); UpdateObjMessage(z, nullptr, pChar->GetClient(), emoteHue, TALKMODE_EMOTE); } //} if (pChar->IsClient() && pChar->CanSee(this)) { sprintf(z, g_Cfg.GetDefaultMsg(DEFMSG_COMBAT_ATTACKS), GetName()); pChar->GetClient()->addBarkParse(z, this, HUE_TEXT_DEF, TALKMODE_EMOTE); } } return true; } // Retrieves damage done to nID enemy int CChar::Attacker_GetDam(int attackerIndex) const { ADDTOCALLSTACK("CChar::Attacker_GetDam"); if (m_lastAttackers.empty()) return -1; if ((attackerIndex < 0) || (m_lastAttackers.size() <= (size_t)attackerIndex)) return -1; const LastAttackers & refAttacker = m_lastAttackers[attackerIndex]; return refAttacker.amountDone; } // Retrieves the amount of time elapsed since the last hit to nID enemy int64 CChar::Attacker_GetElapsed(int attackerIndex) const { ADDTOCALLSTACK("CChar::Attacker_GetElapsed"); if (m_lastAttackers.empty()) return -1; if ((attackerIndex < 0) || (m_lastAttackers.size() <= (size_t)attackerIndex)) return -1; const LastAttackers & refAttacker = m_lastAttackers[attackerIndex]; return refAttacker.elapsed; } // Retrieves Threat value that nID enemy represents against me int CChar::Attacker_GetThreat(int attackerIndex) const { ADDTOCALLSTACK("CChar::Attacker_GetThreat"); if (m_lastAttackers.empty()) return -1; if ((attackerIndex < 0) || (m_lastAttackers.size() <= (size_t)attackerIndex)) return -1; const LastAttackers & refAttacker = m_lastAttackers[attackerIndex]; return (refAttacker.threat > 0) ? refAttacker.threat : 0; } // Retrieves the character with most Threat int CChar::Attacker_GetHighestThreat() const { ADDTOCALLSTACK("CChar::Attacker_GetHighestThreat"); if (m_lastAttackers.empty()) return -1; int highThreat = 0; for (const LastAttackers & refAttacker : m_lastAttackers) { if (refAttacker.threat > highThreat) highThreat = refAttacker.threat; } return highThreat; } // Retrieves the last character that I hit CChar * CChar::Attacker_GetLast() const { ADDTOCALLSTACK("CChar::Attacker_GetLast"); int64 iLastTime = INT64_MAX, iCurTime = 0; CChar * retChar = nullptr; for (const LastAttackers & refAttacker : m_lastAttackers) { iCurTime = refAttacker.elapsed; if (iCurTime <= iLastTime) { iLastTime = iCurTime; retChar = CUID::CharFind(refAttacker.charUID); } } return retChar; } // Set elapsed time (refreshing it?) void CChar::Attacker_SetElapsed(const CChar * pChar, int64 value) { ADDTOCALLSTACK("CChar::Attacker_SetElapsed(CChar)"); return Attacker_SetElapsed(Attacker_GetID(pChar), value); } // Set elapsed time (refreshing it?) void CChar::Attacker_SetElapsed(int attackerIndex, int64 value) { ADDTOCALLSTACK("CChar::Attacker_SetElapsed(idx)"); if (m_lastAttackers.empty()) return; if ((attackerIndex < 0) || (m_lastAttackers.size() <= (size_t)attackerIndex)) return; LastAttackers & refAttacker = m_lastAttackers[attackerIndex]; refAttacker.elapsed = value; } // Damaged pChar void CChar::Attacker_SetDam(const CChar * pChar, int value) { ADDTOCALLSTACK("CChar::Attacker_SetDam(CChar)"); return Attacker_SetDam(Attacker_GetID(pChar), value); } // Damaged pChar void CChar::Attacker_SetDam(int attackerIndex, int value) { ADDTOCALLSTACK("CChar::Attacker_SetDam(idx)"); if (m_lastAttackers.empty()) return; if ((attackerIndex < 0) || (m_lastAttackers.size() <= (size_t)attackerIndex)) return; LastAttackers & refAttacker = m_lastAttackers[attackerIndex]; refAttacker.amountDone = value; } // New Treat level void CChar::Attacker_SetThreat(const CChar * pChar, int value) { ADDTOCALLSTACK("CChar::Attacker_SetThreat(CChar)"); return Attacker_SetThreat(Attacker_GetID(pChar), value); } // New Treat level void CChar::Attacker_SetThreat(int attackerIndex, int value) { ADDTOCALLSTACK("CChar::Attacker_SetThreat(idx)"); if (m_pPlayer) return; if (m_lastAttackers.empty()) return; if ((attackerIndex < 0) || (m_lastAttackers.size() <= (size_t)attackerIndex)) return; LastAttackers & refAttacker = m_lastAttackers[attackerIndex]; refAttacker.threat = value; } // Ignoring this pChar on Hit checks void CChar::Attacker_SetIgnore(const CChar * pChar, bool fIgnore) { ADDTOCALLSTACK("CChar::Attacker_SetIgnore(CChar)"); return Attacker_SetIgnore(Attacker_GetID(pChar), fIgnore); } // Ignoring this pChar on Hit checks void CChar::Attacker_SetIgnore(size_t attackerIndex, bool fIgnore) { ADDTOCALLSTACK("CChar::Attacker_SetIgnore(idx)"); if (m_lastAttackers.empty()) return; if (m_lastAttackers.size() <= attackerIndex) return; LastAttackers & refAttacker = m_lastAttackers[attackerIndex]; refAttacker.ignore = fIgnore; } // I'm ignoring pChar? bool CChar::Attacker_GetIgnore(const CChar * pChar) const { ADDTOCALLSTACK("CChar::Attacker_GetIgnore(CChar)"); return Attacker_GetIgnore(Attacker_GetID(pChar)); } // I'm ignoring pChar? bool CChar::Attacker_GetIgnore(int attackerIndex) const { ADDTOCALLSTACK("CChar::Attacker_GetIgnore(idx)"); if (m_lastAttackers.empty()) return false; if ((attackerIndex < 0) || (m_lastAttackers.size() <= (size_t)attackerIndex)) return false; const LastAttackers & refAttacker = m_lastAttackers[attackerIndex]; return (refAttacker.ignore != 0); } // Clear the whole attackers list: forget who attacked me, but if i'm fighting against someone don't stop me. void CChar::Attacker_Clear() { ADDTOCALLSTACK("CChar::Attacker_Clear"); if (IsTrigUsed(TRIGGER_COMBATEND)) { if (!Fight_IsActive() || !m_Fight_Targ_UID.IsValidUID() || !m_Fight_Targ_UID.CharFind()) { OnTrigger(CTRIG_CombatEnd, this, 0); } } StatFlag_Clear(STATF_WAR); // Combat ended, no need to remain in war mode. m_lastAttackers.clear(); UpdateModeFlag(); } // Get nID value of attacker list from the given pChar int CChar::Attacker_GetID(const CChar * pChar) const { ADDTOCALLSTACK("CChar::Attacker_GetID(CChar)"); if (!pChar) return -1; if (m_lastAttackers.empty()) return -1; int count = 0; for (std::vector<LastAttackers>::const_iterator it = m_lastAttackers.begin(), end = m_lastAttackers.end(); it != end; ++it) { const CUID& uid = it->charUID; if (!uid.IsValidUID()) continue; const CChar* pUIDChar = uid.CharFind(); if (!pUIDChar) continue; if (pUIDChar == pChar) return count; ++count; } return -1; } // Get nID value of attacker list from the given uidChar int CChar::Attacker_GetID(const CUID& uidChar) const { ADDTOCALLSTACK("CChar::Attacker_GetID(CUID)"); return Attacker_GetID(uidChar.CharFind()); } // Get CChar* from attacker list at the given attackerIndex CChar * CChar::Attacker_GetUID(int attackerIndex) const { ADDTOCALLSTACK("CChar::Attacker_GetUID"); if (m_lastAttackers.empty()) return nullptr; if ((attackerIndex < 0) || (m_lastAttackers.size() <= (size_t)attackerIndex)) return nullptr; const LastAttackers & refAttacker = m_lastAttackers[attackerIndex]; CChar * pChar = CUID::CharFind(refAttacker.charUID); return pChar; } // Removing attacker pointed by iterator bool CChar::Attacker_Delete(std::vector<LastAttackers>::iterator &itAttacker, bool fForced, ATTACKER_CLEAR_TYPE type) { ADDTOCALLSTACK("CChar::Attacker_Delete(iterator)"); if (m_lastAttackers.empty()) return false; CChar *pChar = CUID::CharFind(itAttacker->charUID); if (pChar) { if (IsTrigUsed(TRIGGER_COMBATDELETE)) { CScriptTriggerArgs Args; Args.m_iN1 = fForced; Args.m_iN2 = (int)type; TRIGRET_TYPE tRet = OnTrigger(CTRIG_CombatDelete, pChar, &Args); if ((tRet == TRIGRET_RET_TRUE) && !fForced) return false; } } itAttacker = m_lastAttackers.erase(itAttacker); // update the iterator to prevent invalidation and crashes! if (pChar && (m_Fight_Targ_UID == pChar->GetUID())) { if (m_pNPC) { m_Fight_Targ_UID.InitUID(); Fight_Attack(NPC_FightFindBestTarget()); } } if (m_lastAttackers.empty()) Attacker_Clear(); return true; } // Removing nID from list bool CChar::Attacker_Delete(int attackerIndex, bool fForced, ATTACKER_CLEAR_TYPE type) { ADDTOCALLSTACK("CChar::Attacker_Delete(size_t)"); if (m_lastAttackers.empty()) return false; if ((attackerIndex < 0) || (m_lastAttackers.size() <= (size_t)attackerIndex)) return false; std::vector<LastAttackers>::iterator it = m_lastAttackers.begin() + attackerIndex; return Attacker_Delete(it, fForced, type); } // Removing pChar from list bool CChar::Attacker_Delete(const CChar * pChar, bool fForced, ATTACKER_CLEAR_TYPE type) { ADDTOCALLSTACK("CChar::Attacker_Delete(CChar)"); if (!pChar || m_lastAttackers.empty()) return false; return Attacker_Delete(Attacker_GetID(pChar), fForced, type); } // Removing everyone void CChar::Attacker_RemoveChar() { ADDTOCALLSTACK("CChar::Attacker_RemoveChar"); if (!m_lastAttackers.empty()) { for (auto it = m_lastAttackers.begin(), end = m_lastAttackers.end(); it != end; ++it) { LastAttackers & refAttacker = *it; CChar * pSrc = CUID::CharFind(refAttacker.charUID); if (!pSrc) continue; pSrc->Attacker_Delete(this, false, ATTACKER_CLEAR_REMOVEDCHAR); } } } // Checking if Elapsed > serv.AttackerTimeout void CChar::Attacker_CheckTimeout() { ADDTOCALLSTACK("CChar::Attacker_CheckTimeout"); if (!m_lastAttackers.empty()) { // do not iterate with an iterator here, since Attacker_Delete can invalidate both current and end iterators! for (int count = 0; count < (int)m_lastAttackers.size(); ) { LastAttackers & refAttacker = m_lastAttackers[count]; const CChar *pEnemy = CUID::CharFind(refAttacker.charUID); if (pEnemy) { // always advance refAttacker.elapsed, i might use it in scripts for a different purpose ++refAttacker.elapsed; if ( (refAttacker.elapsed > g_Cfg.m_iAttackerTimeout) && (g_Cfg.m_iAttackerTimeout > 0)) { if (!Attacker_Delete(count, false, ATTACKER_CLEAR_ELAPSED)) ++count; continue; } ++count; } else { const bool fCleanupSuccess = Attacker_Delete(count, true, ATTACKER_CLEAR_FORCED); ASSERT(fCleanupSuccess); UNREFERENCED_PARAMETER(fCleanupSuccess); //if (!fCleanupSuccess) // ++count; } } } } <commit_msg>Possible fix for #409<commit_after>// Actions specific to an NPC. #include "../clients/CClient.h" #include "../triggers.h" #include "CChar.h" // Add some enemy to my Attacker list bool CChar::Attacker_Add(CChar * pChar, int threat) { ADDTOCALLSTACK("CChar::Attacker_Add"); CUID uid = pChar->GetUID(); if (!m_lastAttackers.empty()) // Must only check for existing attackers if there are any attacker already. { for (auto it = m_lastAttackers.begin(), end = m_lastAttackers.end(); it != end; ++it) { LastAttackers & refAttacker = *it; if (refAttacker.charUID == uid) return true; // found one, no actions needed so we skip } } else if (IsTrigUsed(TRIGGER_COMBATSTART)) { TRIGRET_TYPE tRet = OnTrigger(CTRIG_CombatStart, pChar, 0); if (tRet == TRIGRET_RET_TRUE) return false; } CScriptTriggerArgs Args; bool fIgnore = false; Args.m_iN1 = threat; Args.m_iN2 = fIgnore; if (IsTrigUsed(TRIGGER_COMBATADD)) { TRIGRET_TYPE tRet = OnTrigger(CTRIG_CombatAdd, pChar, &Args); if (tRet == TRIGRET_RET_TRUE) return false; threat = (int)Args.m_iN1; fIgnore = (Args.m_iN2 != 0); } LastAttackers attacker; attacker.amountDone = 0; attacker.charUID = uid; attacker.elapsed = 0; attacker.threat = (m_pPlayer) ? 0 : threat; attacker.ignore = fIgnore; m_lastAttackers.emplace_back(std::move(attacker)); // Record the start of the fight. Memory_Fight_Start(pChar); tchar *z = Str_GetTemp(); if (!attacker.ignore) { //if ( GetTopSector()->GetCharComplexity() < 7 ) //{ if (!( g_Cfg.m_iEmoteFlags & EMOTEF_ATTACKER )) { HUE_TYPE emoteHue = (HUE_TYPE)(g_Exp.m_VarDefs.GetKeyNum("EMOTE_DEF_COLOR")); if (this && this->m_EmoteHueOverride) //Set EMOTECOLOROVERRIDE to ATTACKERS emoteHue = this->m_EmoteHueOverride; sprintf(z, g_Cfg.GetDefaultMsg(DEFMSG_COMBAT_ATTACKO), GetName(), pChar->GetName()); UpdateObjMessage(z, nullptr, pChar->GetClient(), emoteHue, TALKMODE_EMOTE); } //} if (pChar->IsClient() && pChar->CanSee(this)) { sprintf(z, g_Cfg.GetDefaultMsg(DEFMSG_COMBAT_ATTACKS), GetName()); pChar->GetClient()->addBarkParse(z, this, HUE_TEXT_DEF, TALKMODE_EMOTE); } } return true; } // Retrieves damage done to nID enemy int CChar::Attacker_GetDam(int attackerIndex) const { ADDTOCALLSTACK("CChar::Attacker_GetDam"); if (m_lastAttackers.empty()) return -1; if ((attackerIndex < 0) || (m_lastAttackers.size() <= (size_t)attackerIndex)) return -1; const LastAttackers & refAttacker = m_lastAttackers[attackerIndex]; return refAttacker.amountDone; } // Retrieves the amount of time elapsed since the last hit to nID enemy int64 CChar::Attacker_GetElapsed(int attackerIndex) const { ADDTOCALLSTACK("CChar::Attacker_GetElapsed"); if (m_lastAttackers.empty()) return -1; if ((attackerIndex < 0) || (m_lastAttackers.size() <= (size_t)attackerIndex)) return -1; const LastAttackers & refAttacker = m_lastAttackers[attackerIndex]; return refAttacker.elapsed; } // Retrieves Threat value that nID enemy represents against me int CChar::Attacker_GetThreat(int attackerIndex) const { ADDTOCALLSTACK("CChar::Attacker_GetThreat"); if (m_lastAttackers.empty()) return -1; if ((attackerIndex < 0) || (m_lastAttackers.size() <= (size_t)attackerIndex)) return -1; const LastAttackers & refAttacker = m_lastAttackers[attackerIndex]; return (refAttacker.threat > 0) ? refAttacker.threat : 0; } // Retrieves the character with most Threat int CChar::Attacker_GetHighestThreat() const { ADDTOCALLSTACK("CChar::Attacker_GetHighestThreat"); if (m_lastAttackers.empty()) return -1; int highThreat = 0; for (const LastAttackers & refAttacker : m_lastAttackers) { if (refAttacker.threat > highThreat) highThreat = refAttacker.threat; } return highThreat; } // Retrieves the last character that I hit CChar * CChar::Attacker_GetLast() const { ADDTOCALLSTACK("CChar::Attacker_GetLast"); int64 iLastTime = INT64_MAX, iCurTime = 0; CChar * retChar = nullptr; for (const LastAttackers & refAttacker : m_lastAttackers) { iCurTime = refAttacker.elapsed; if (iCurTime <= iLastTime) { iLastTime = iCurTime; retChar = CUID::CharFind(refAttacker.charUID); } } return retChar; } // Set elapsed time (refreshing it?) void CChar::Attacker_SetElapsed(const CChar * pChar, int64 value) { ADDTOCALLSTACK("CChar::Attacker_SetElapsed(CChar)"); return Attacker_SetElapsed(Attacker_GetID(pChar), value); } // Set elapsed time (refreshing it?) void CChar::Attacker_SetElapsed(int attackerIndex, int64 value) { ADDTOCALLSTACK("CChar::Attacker_SetElapsed(idx)"); if (m_lastAttackers.empty()) return; if ((attackerIndex < 0) || (m_lastAttackers.size() <= (size_t)attackerIndex)) return; LastAttackers & refAttacker = m_lastAttackers[attackerIndex]; refAttacker.elapsed = value; } // Damaged pChar void CChar::Attacker_SetDam(const CChar * pChar, int value) { ADDTOCALLSTACK("CChar::Attacker_SetDam(CChar)"); return Attacker_SetDam(Attacker_GetID(pChar), value); } // Damaged pChar void CChar::Attacker_SetDam(int attackerIndex, int value) { ADDTOCALLSTACK("CChar::Attacker_SetDam(idx)"); if (m_lastAttackers.empty()) return; if ((attackerIndex < 0) || (m_lastAttackers.size() <= (size_t)attackerIndex)) return; LastAttackers & refAttacker = m_lastAttackers[attackerIndex]; refAttacker.amountDone = value; } // New Treat level void CChar::Attacker_SetThreat(const CChar * pChar, int value) { ADDTOCALLSTACK("CChar::Attacker_SetThreat(CChar)"); return Attacker_SetThreat(Attacker_GetID(pChar), value); } // New Treat level void CChar::Attacker_SetThreat(int attackerIndex, int value) { ADDTOCALLSTACK("CChar::Attacker_SetThreat(idx)"); if (m_pPlayer) return; if (m_lastAttackers.empty()) return; if ((attackerIndex < 0) || (m_lastAttackers.size() <= (size_t)attackerIndex)) return; LastAttackers & refAttacker = m_lastAttackers[attackerIndex]; refAttacker.threat = value; } // Ignoring this pChar on Hit checks void CChar::Attacker_SetIgnore(const CChar * pChar, bool fIgnore) { ADDTOCALLSTACK("CChar::Attacker_SetIgnore(CChar)"); return Attacker_SetIgnore(Attacker_GetID(pChar), fIgnore); } // Ignoring this pChar on Hit checks void CChar::Attacker_SetIgnore(size_t attackerIndex, bool fIgnore) { ADDTOCALLSTACK("CChar::Attacker_SetIgnore(idx)"); if (m_lastAttackers.empty()) return; if (m_lastAttackers.size() <= attackerIndex) return; LastAttackers & refAttacker = m_lastAttackers[attackerIndex]; refAttacker.ignore = fIgnore; } // I'm ignoring pChar? bool CChar::Attacker_GetIgnore(const CChar * pChar) const { ADDTOCALLSTACK("CChar::Attacker_GetIgnore(CChar)"); return Attacker_GetIgnore(Attacker_GetID(pChar)); } // I'm ignoring pChar? bool CChar::Attacker_GetIgnore(int attackerIndex) const { ADDTOCALLSTACK("CChar::Attacker_GetIgnore(idx)"); if (m_lastAttackers.empty()) return false; if ((attackerIndex < 0) || (m_lastAttackers.size() <= (size_t)attackerIndex)) return false; const LastAttackers & refAttacker = m_lastAttackers[attackerIndex]; return (refAttacker.ignore != 0); } // Clear the whole attackers list: forget who attacked me, but if i'm fighting against someone don't stop me. void CChar::Attacker_Clear() { ADDTOCALLSTACK("CChar::Attacker_Clear"); if (IsTrigUsed(TRIGGER_COMBATEND)) { if (!Fight_IsActive() || !m_Fight_Targ_UID.IsValidUID() || !m_Fight_Targ_UID.CharFind()) { OnTrigger(CTRIG_CombatEnd, this, 0); } } StatFlag_Clear(STATF_WAR); // Combat ended, no need to remain in war mode. m_lastAttackers.clear(); UpdateModeFlag(); } // Get nID value of attacker list from the given pChar int CChar::Attacker_GetID(const CChar * pChar) const { ADDTOCALLSTACK("CChar::Attacker_GetID(CChar)"); if (!pChar) return -1; if (m_lastAttackers.empty()) return -1; int count = 0; for (std::vector<LastAttackers>::const_iterator it = m_lastAttackers.begin(), end = m_lastAttackers.end(); it != end; ++it) { const CUID& uid = it->charUID; if (!uid.IsValidUID()) continue; const CChar* pUIDChar = uid.CharFind(); if (!pUIDChar) continue; if (pUIDChar == pChar) return count; ++count; } return -1; } // Get nID value of attacker list from the given uidChar int CChar::Attacker_GetID(const CUID& uidChar) const { ADDTOCALLSTACK("CChar::Attacker_GetID(CUID)"); return Attacker_GetID(uidChar.CharFind()); } // Get CChar* from attacker list at the given attackerIndex CChar * CChar::Attacker_GetUID(int attackerIndex) const { ADDTOCALLSTACK("CChar::Attacker_GetUID"); if (m_lastAttackers.empty()) return nullptr; if ((attackerIndex < 0) || (m_lastAttackers.size() <= (size_t)attackerIndex)) return nullptr; const LastAttackers & refAttacker = m_lastAttackers[attackerIndex]; CChar * pChar = CUID::CharFind(refAttacker.charUID); return pChar; } // Removing attacker pointed by iterator bool CChar::Attacker_Delete(std::vector<LastAttackers>::iterator &itAttacker, bool fForced, ATTACKER_CLEAR_TYPE type) { ADDTOCALLSTACK("CChar::Attacker_Delete(iterator)"); if (m_lastAttackers.empty()) return false; CChar *pChar = CUID::CharFind(itAttacker->charUID); if (pChar) { if (IsTrigUsed(TRIGGER_COMBATDELETE)) { CScriptTriggerArgs Args; Args.m_iN1 = fForced; Args.m_iN2 = (int)type; TRIGRET_TYPE tRet = OnTrigger(CTRIG_CombatDelete, pChar, &Args); if ((tRet == TRIGRET_RET_TRUE) && !fForced) return false; } } itAttacker = m_lastAttackers.erase(itAttacker); // update the iterator to prevent invalidation and crashes! if (pChar && (m_Fight_Targ_UID == pChar->GetUID())) { if (m_pNPC) { m_Fight_Targ_UID.InitUID(); Fight_Attack(NPC_FightFindBestTarget()); } } if (m_lastAttackers.empty()) Attacker_Clear(); return true; } // Removing nID from list bool CChar::Attacker_Delete(int attackerIndex, bool fForced, ATTACKER_CLEAR_TYPE type) { ADDTOCALLSTACK("CChar::Attacker_Delete(size_t)"); if (m_lastAttackers.empty()) return false; if ((attackerIndex < 0) || (m_lastAttackers.size() <= (size_t)attackerIndex)) return false; std::vector<LastAttackers>::iterator it = m_lastAttackers.begin() + attackerIndex; return Attacker_Delete(it, fForced, type); } // Removing pChar from list bool CChar::Attacker_Delete(const CChar * pChar, bool fForced, ATTACKER_CLEAR_TYPE type) { ADDTOCALLSTACK("CChar::Attacker_Delete(CChar)"); if (!pChar || m_lastAttackers.empty()) { return false; } if (m_Fight_Targ_UID == pChar->GetUID); { m_Fight_Targ_UID.InitUID(); } return Attacker_Delete(Attacker_GetID(pChar), fForced, type); } // Removing everyone void CChar::Attacker_RemoveChar() { ADDTOCALLSTACK("CChar::Attacker_RemoveChar"); if (!m_lastAttackers.empty()) { for (auto it = m_lastAttackers.begin(), end = m_lastAttackers.end(); it != end; ++it) { LastAttackers & refAttacker = *it; CChar * pSrc = CUID::CharFind(refAttacker.charUID); if (!pSrc) continue; pSrc->Attacker_Delete(this, false, ATTACKER_CLEAR_REMOVEDCHAR); } } } // Checking if Elapsed > serv.AttackerTimeout void CChar::Attacker_CheckTimeout() { ADDTOCALLSTACK("CChar::Attacker_CheckTimeout"); if (!m_lastAttackers.empty()) { // do not iterate with an iterator here, since Attacker_Delete can invalidate both current and end iterators! for (int count = 0; count < (int)m_lastAttackers.size(); ) { LastAttackers & refAttacker = m_lastAttackers[count]; const CChar *pEnemy = CUID::CharFind(refAttacker.charUID); if (pEnemy) { // always advance refAttacker.elapsed, i might use it in scripts for a different purpose ++refAttacker.elapsed; if ( (refAttacker.elapsed > g_Cfg.m_iAttackerTimeout) && (g_Cfg.m_iAttackerTimeout > 0)) { if (!Attacker_Delete(count, false, ATTACKER_CLEAR_ELAPSED)) ++count; continue; } ++count; } else { const bool fCleanupSuccess = Attacker_Delete(count, true, ATTACKER_CLEAR_FORCED); ASSERT(fCleanupSuccess); UNREFERENCED_PARAMETER(fCleanupSuccess); //if (!fCleanupSuccess) // ++count; } } } } <|endoftext|>
<commit_before>// // http_server_handler_stats.cc // #include "plat_os.h" #include "plat_net.h" #include <cassert> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include <cerrno> #include <csignal> #include <iostream> #include <iomanip> #include <sstream> #include <string> #include <vector> #include <algorithm> #include <functional> #include <deque> #include <map> #include <atomic> #include <memory> #include <thread> #include <mutex> #include <condition_variable> #include "io.h" #include "url.h" #include "log.h" #include "trie.h" #include "socket.h" #include "resolver.h" #include "config_parser.h" #include "config.h" #include "pollset.h" #include "protocol.h" #include "connection.h" #include "connection_tcp.h" #include "protocol_thread.h" #include "protocol_engine.h" #include "protocol_connection.h" #include "http_common.h" #include "http_constants.h" #include "http_parser.h" #include "http_request.h" #include "http_response.h" #include "http_date.h" #include "http_server.h" #include "http_server_handler_stats.h" /* http_server_handler_stats */ http_server_handler_stats::http_server_handler_stats() { response_buffer.resize(8192); } http_server_handler_stats::~http_server_handler_stats() { } void http_server_handler_stats::init_handler() { http_server::register_handler<http_server_handler_stats>("http_server_handler_stats"); } void http_server_handler_stats::init() { reader = nullptr; response_buffer.reset(); mime_type.clear(); status_text.clear(); status_code = 0; content_length = 0; total_written = 0; } bool http_server_handler_stats::handle_request() { // get request http version and request method http_version = http_constants::get_version_type(http_conn->request.get_http_version()); request_method = http_constants::get_method_type(http_conn->request.get_request_method()); switch (request_method) { case HTTPMethodGET: case HTTPMethodHEAD: status_code = HTTPStatusCodeOK; break; default: status_code = HTTPStatusCodeMethodNotAllowed; break; } // create response status_text = http_constants::get_status_text(status_code); mime_type = "text/plain"; std::stringstream ss; size_t engine_num = 0; ss << "server statistics" << std::endl << std::endl; for (auto engine : protocol_engine::engine_list) { ss << "engine-" << engine_num++ << std::endl; auto http_engine_state = static_cast<http_server_engine_state*> (engine->get_engine_state(http_server::get_proto())); ss << " listens " << http_engine_state->listens.size() << std::endl; for (auto listen : http_engine_state->listens) { ss << " " << socket_addr::addr_to_string(listen->addr) << std::endl; } ss << " threads " << engine->threads_all.size() << std::endl; for (auto &thread : engine->threads_all) { std::string thread_mask = protocol_thread::thread_mask_to_string(thread->thread_mask); ss << " " << thread->get_thread_id() << " " << thread_mask << std::endl; } ss << " handlers " << http_engine_state->handler_list.size() << std::endl; for (auto &handler : http_engine_state->handler_list) { ss << " " << handler->factory->get_name() << " " << handler->path << std::endl; } size_t connections_total = http_engine_state->connections_all.size(); size_t connections_free = http_engine_state->connections_free.size(); ss << " connections" << std::endl; ss << " total " << connections_total << std::endl; ss << " free " << connections_free << std::endl; ss << " inuse " << (connections_total - connections_free) << std::endl; ss << " accepts " << http_engine_state->stats.connections_accepted << std::endl; ss << " closes " << http_engine_state->stats.connections_closed << std::endl; ss << " keepalives " << http_engine_state->stats.connections_keepalive << std::endl; ss << " lingers " << http_engine_state->stats.connections_linger << std::endl; ss << " requests " << http_engine_state->stats.requests_processed << std::endl; } std::string str = ss.str();; response_buffer.set(str.c_str(), str.length()); content_length = str.length(); reader = &response_buffer; if (delegate->get_debug_mask() & protocol_debug_handler) { log_debug("handle_request: status_code=%d status_text=%s mime_type=%s", status_code, status_text.c_str(), mime_type.c_str()); } return true; } io_result http_server_handler_stats::read_request_body() { return io_result(0); } bool http_server_handler_stats::populate_response() { // set request body presence switch (request_method) { case HTTPMethodGET: http_conn->response_has_body = (status_code != HTTPStatusCodeNotModified); break; case HTTPMethodHEAD: http_conn->response_has_body = false; break; default: http_conn->response_has_body = true; break; } // set connection close const char* connection_str = http_conn->request.get_header_string(kHTTPHeaderConnection); bool connection_keepalive_present = (connection_str && strcasecmp(connection_str, kHTTPTokenKeepalive) == 0); bool connection_close_present = (connection_str && strcasecmp(connection_str, kHTTPTokenClose) == 0); switch (http_version) { case HTTPVersion10: http_conn->connection_close = !connection_keepalive_present; break; case HTTPVersion11: http_conn->connection_close = connection_close_present; break; default: http_conn->connection_close = true; break; } // TODO - PUT/POST request has body http_conn->request_has_body = false; // set response headers http_conn->response.set_status_code(status_code); http_conn->response.set_reason_phrase(status_text); if (status_code != HTTPStatusCodeNotModified) { http_conn->response.set_header_field(kHTTPHeaderContentType, mime_type); http_conn->response.set_header_field(kHTTPHeaderContentLength, format_string("%lu", content_length)); } switch (http_version) { case HTTPVersion10: if (connection_keepalive_present) { http_conn->response.set_header_field(kHTTPHeaderConnection, kHTTPTokenKeepalive); } break; case HTTPVersion11: http_conn->response.set_header_field(kHTTPHeaderConnection, http_conn->connection_close ? kHTTPTokenClose : kHTTPTokenKeepalive); break; default: http_conn->connection_close = true; break; } return true; } io_result http_server_handler_stats::write_response_body() { auto &buffer = http_conn->buffer; // refill buffer if (reader && buffer.bytes_readable() == 0) { buffer.reset(); io_result res = buffer.buffer_read(*reader); if (res.has_error()) return res; } // write buffer to socket if (buffer.bytes_readable() > 0) { io_result result = buffer.buffer_write(http_conn->conn); if (result.has_error()) { return result; } total_written += result.size(); } // return bytes available return io_result(content_length - total_written); } bool http_server_handler_stats::end_request() { return true; } <commit_msg>Add aborts to statistics<commit_after>// // http_server_handler_stats.cc // #include "plat_os.h" #include "plat_net.h" #include <cassert> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include <cerrno> #include <csignal> #include <iostream> #include <iomanip> #include <sstream> #include <string> #include <vector> #include <algorithm> #include <functional> #include <deque> #include <map> #include <atomic> #include <memory> #include <thread> #include <mutex> #include <condition_variable> #include "io.h" #include "url.h" #include "log.h" #include "trie.h" #include "socket.h" #include "resolver.h" #include "config_parser.h" #include "config.h" #include "pollset.h" #include "protocol.h" #include "connection.h" #include "connection_tcp.h" #include "protocol_thread.h" #include "protocol_engine.h" #include "protocol_connection.h" #include "http_common.h" #include "http_constants.h" #include "http_parser.h" #include "http_request.h" #include "http_response.h" #include "http_date.h" #include "http_server.h" #include "http_server_handler_stats.h" /* http_server_handler_stats */ http_server_handler_stats::http_server_handler_stats() { response_buffer.resize(8192); } http_server_handler_stats::~http_server_handler_stats() { } void http_server_handler_stats::init_handler() { http_server::register_handler<http_server_handler_stats>("http_server_handler_stats"); } void http_server_handler_stats::init() { reader = nullptr; response_buffer.reset(); mime_type.clear(); status_text.clear(); status_code = 0; content_length = 0; total_written = 0; } bool http_server_handler_stats::handle_request() { // get request http version and request method http_version = http_constants::get_version_type(http_conn->request.get_http_version()); request_method = http_constants::get_method_type(http_conn->request.get_request_method()); switch (request_method) { case HTTPMethodGET: case HTTPMethodHEAD: status_code = HTTPStatusCodeOK; break; default: status_code = HTTPStatusCodeMethodNotAllowed; break; } // create response status_text = http_constants::get_status_text(status_code); mime_type = "text/plain"; std::stringstream ss; size_t engine_num = 0; ss << "server statistics" << std::endl << std::endl; for (auto engine : protocol_engine::engine_list) { ss << "engine-" << engine_num++ << std::endl; auto http_engine_state = static_cast<http_server_engine_state*> (engine->get_engine_state(http_server::get_proto())); ss << " listens " << http_engine_state->listens.size() << std::endl; for (auto listen : http_engine_state->listens) { ss << " " << socket_addr::addr_to_string(listen->addr) << std::endl; } ss << " threads " << engine->threads_all.size() << std::endl; for (auto &thread : engine->threads_all) { std::string thread_mask = protocol_thread::thread_mask_to_string(thread->thread_mask); ss << " " << thread->get_thread_id() << " " << thread_mask << std::endl; } ss << " handlers " << http_engine_state->handler_list.size() << std::endl; for (auto &handler : http_engine_state->handler_list) { ss << " " << handler->factory->get_name() << " " << handler->path << std::endl; } size_t connections_total = http_engine_state->connections_all.size(); size_t connections_free = http_engine_state->connections_free.size(); ss << " connections" << std::endl; ss << " total " << connections_total << std::endl; ss << " free " << connections_free << std::endl; ss << " inuse " << (connections_total - connections_free) << std::endl; ss << " accepts " << http_engine_state->stats.connections_accepted << std::endl; ss << " closes " << http_engine_state->stats.connections_closed << std::endl; ss << " aborts " << http_engine_state->stats.connections_aborted << std::endl; ss << " keepalives " << http_engine_state->stats.connections_keepalive << std::endl; ss << " lingers " << http_engine_state->stats.connections_linger << std::endl; ss << " requests " << http_engine_state->stats.requests_processed << std::endl; } std::string str = ss.str();; response_buffer.set(str.c_str(), str.length()); content_length = str.length(); reader = &response_buffer; if (delegate->get_debug_mask() & protocol_debug_handler) { log_debug("handle_request: status_code=%d status_text=%s mime_type=%s", status_code, status_text.c_str(), mime_type.c_str()); } return true; } io_result http_server_handler_stats::read_request_body() { return io_result(0); } bool http_server_handler_stats::populate_response() { // set request body presence switch (request_method) { case HTTPMethodGET: http_conn->response_has_body = (status_code != HTTPStatusCodeNotModified); break; case HTTPMethodHEAD: http_conn->response_has_body = false; break; default: http_conn->response_has_body = true; break; } // set connection close const char* connection_str = http_conn->request.get_header_string(kHTTPHeaderConnection); bool connection_keepalive_present = (connection_str && strcasecmp(connection_str, kHTTPTokenKeepalive) == 0); bool connection_close_present = (connection_str && strcasecmp(connection_str, kHTTPTokenClose) == 0); switch (http_version) { case HTTPVersion10: http_conn->connection_close = !connection_keepalive_present; break; case HTTPVersion11: http_conn->connection_close = connection_close_present; break; default: http_conn->connection_close = true; break; } // TODO - PUT/POST request has body http_conn->request_has_body = false; // set response headers http_conn->response.set_status_code(status_code); http_conn->response.set_reason_phrase(status_text); if (status_code != HTTPStatusCodeNotModified) { http_conn->response.set_header_field(kHTTPHeaderContentType, mime_type); http_conn->response.set_header_field(kHTTPHeaderContentLength, format_string("%lu", content_length)); } switch (http_version) { case HTTPVersion10: if (connection_keepalive_present) { http_conn->response.set_header_field(kHTTPHeaderConnection, kHTTPTokenKeepalive); } break; case HTTPVersion11: http_conn->response.set_header_field(kHTTPHeaderConnection, http_conn->connection_close ? kHTTPTokenClose : kHTTPTokenKeepalive); break; default: http_conn->connection_close = true; break; } return true; } io_result http_server_handler_stats::write_response_body() { auto &buffer = http_conn->buffer; // refill buffer if (reader && buffer.bytes_readable() == 0) { buffer.reset(); io_result res = buffer.buffer_read(*reader); if (res.has_error()) return res; } // write buffer to socket if (buffer.bytes_readable() > 0) { io_result result = buffer.buffer_write(http_conn->conn); if (result.has_error()) { return result; } total_written += result.size(); } // return bytes available return io_result(content_length - total_written); } bool http_server_handler_stats::end_request() { return true; } <|endoftext|>
<commit_before>/** * A server which is responsible for interacting with devices. * * @date July 7, 2014 * @author Joeri HERMANS * @version 0.1 * * Copyright 2013 Joeri HERMANS * * 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. */ // BEGIN Includes. /////////////////////////////////////////////////// // System dependencies. #include <arpa/inet.h> #include <cassert> #include <cstdio> #include <iostream> // Application dependencies. #include <ias/server/device_server.h> #include <ias/server/session/device_session.h> #include <ias/logger/logger.h> // END Includes. ///////////////////////////////////////////////////// inline void DeviceServer::initialize( void ) { mSocket = nullptr; mListenThread = nullptr; mDispatchThread = nullptr; mFlagRunning = true; } void DeviceServer::setSocket( Socket * socket ) { // Checking the precondition. assert( socket != nullptr && socket->isConnected() ); mSocket = socket; } void DeviceServer::setDeviceIdentifiers( const std::vector<std::string> & i ) { mDeviceIdentifiers = i; } void DeviceServer::startListenThread( void ) { mListenThread = new std::thread([this](){ ServerSocket * serverSocket; Session * session; Socket * socket; serverSocket = getServerSocket(); while( mFlagRunning && mSocket->isConnected() ) { socket = serverSocket->acceptSocket(1); if( socket != nullptr ) { logi("Starting new device session."); session = new DeviceSession(socket, mSocket, &mConnectedDevices, &mDeviceIdentifiers); session->addObserver(this); mSessions[session] = new std::thread([session]{ session->run(); session->notifyObservers(session); delete session; logi("Device session terminated."); }); } cleanupFinishingThreads(); } signalSessions(); mSocket->closeConnection(); while( mSessions.size() > 0 || mInactiveThreads.size() > 0 ) { signalSessions(); cleanupFinishingThreads(); } }); } bool DeviceServer::readBytes( char * buffer , const unsigned int n ) { std::size_t bytesRead; std::size_t nBytes; Reader * reader; // Checking the precondition. assert( buffer != nullptr && n > 0 ); if( !mSocket->isConnected() ) return ( false ); reader = mSocket->getReader(); bytesRead = 0; while( bytesRead != n ) { nBytes = reader->readBytes(buffer + bytesRead,n - bytesRead); if( nBytes == 0 ) return ( false ); bytesRead += nBytes; } return ( true ); } void DeviceServer::dispatchCommand( void ) { std::uint8_t deviceLength; std::uint8_t identifierLength; std::uint8_t parameterLength; std::string message; if( mSocket->isConnected() ) { if( !readBytes(reinterpret_cast<char *>(&deviceLength),1) ) return; if( !readBytes(reinterpret_cast<char *>(&identifierLength),1) ) return; if( !readBytes(reinterpret_cast<char *>(&parameterLength),1) ) return; char deviceIdentifier[deviceLength + 1]; char identifier[identifierLength + 1]; char parameter[parameterLength + 1]; if( !readBytes(deviceIdentifier,deviceLength) ) return; if( !readBytes(identifier,identifierLength) ) return; if( parameterLength > 0 && !readBytes(parameter,parameterLength) ) return; deviceIdentifier[deviceLength] = 0; identifier[identifierLength] = 0; parameter[parameterLength] = 0; // Format the message message += 0x01; message += identifierLength; message += parameterLength; message.append(identifier); message.append(parameter); mConnectedDevices.dispatch(deviceIdentifier,message); } else { stop(); } } void DeviceServer::startDispatchThread( void ) { mDispatchThread = new std::thread([this](){ std::size_t nBytes; std::uint8_t type; Reader * reader; bool heartbeatSend = false; setServerTimeouts(); reader = mSocket->getReader(); while( mFlagRunning && mSocket->isConnected() ) { type = 0xff; reader->lock(); nBytes = reader->readByte(reinterpret_cast<char *>(&type)); reader->unlock(); if( nBytes == 0 ) { if( !serverHeartbeat() || heartbeatSend ) stop(); else heartbeatSend = true; continue; } switch(type) { case 0x00: if( !heartbeatSend ) serverHeartbeat(); break; case 0x01: dispatchCommand(); break; default: mFlagRunning = false; break; } heartbeatSend = false; } stop(); }); } void DeviceServer::signalSessions( void ) { std::map<Session *,std::thread *>::iterator it; mMutexSessions.lock(); for( it = mSessions.begin() ; it != mSessions.end() ; ++it ) it->first->stop(); mMutexSessions.unlock(); } void DeviceServer::cleanupFinishingThreads( void ) { std::thread * t; while( mInactiveThreads.size() > 0 ) { t = mInactiveThreads.front(); if( t != nullptr ) { t->join(); delete t; } mInactiveThreads.erase(mInactiveThreads.begin()); } } bool DeviceServer::serverHeartbeat( void ) { static const std::int8_t beat = 0x00; Writer * writer; bool ok; writer = mSocket->getWriter(); writer->lock(); ok = (writer->writeBytes(reinterpret_cast<const char *>(&beat),1) == 1); writer->unlock(); return ( ok ); } void DeviceServer::setServerTimeouts( void ) { struct timeval tv; tv.tv_sec = 20; tv.tv_usec = 0; mSocket->setReceiveTimeout(tv); } DeviceServer::DeviceServer( ServerSocket * serverSocket, Socket * socket, const std::vector<std::string> & devices ) : Server(serverSocket) { initialize(); setSocket(socket); setDeviceIdentifiers(devices); } DeviceServer::~DeviceServer( void ) { join(); } void DeviceServer::start( void ) { if( mListenThread == nullptr && mDispatchThread == nullptr ) { startListenThread(); startDispatchThread(); } } void DeviceServer::stop( void ) { if( mFlagRunning ) { logi("Stopping device server."); mFlagRunning = false; mSocket->closeConnection(); getServerSocket()->stopListening(); } } void DeviceServer::join( void ) { if( mListenThread != nullptr ) { mListenThread->join(); delete mListenThread; mListenThread = nullptr; } if( mDispatchThread != nullptr ) { mDispatchThread->join(); delete mDispatchThread; mDispatchThread = nullptr; } } void DeviceServer::update( void ) { // Do nothing. } void DeviceServer::update( void * argument ) { std::map<Session *,std::thread *>::iterator it; Session * session; // Checking the precondition. assert( argument != nullptr ); session = static_cast<Session *>(argument); it = mSessions.find(session); if( it != mSessions.end() ) { mInactiveThreads.push_back(it->second); mMutexSessions.lock(); mSessions.erase(it); mMutexSessions.unlock(); } } <commit_msg>Optimize dispatch loop.<commit_after>/** * A server which is responsible for interacting with devices. * * @date July 7, 2014 * @author Joeri HERMANS * @version 0.1 * * Copyright 2013 Joeri HERMANS * * 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. */ // BEGIN Includes. /////////////////////////////////////////////////// // System dependencies. #include <arpa/inet.h> #include <cassert> #include <cstdio> #include <iostream> // Application dependencies. #include <ias/server/device_server.h> #include <ias/server/session/device_session.h> #include <ias/logger/logger.h> // END Includes. ///////////////////////////////////////////////////// inline void DeviceServer::initialize( void ) { mSocket = nullptr; mListenThread = nullptr; mDispatchThread = nullptr; mFlagRunning = true; } void DeviceServer::setSocket( Socket * socket ) { // Checking the precondition. assert( socket != nullptr && socket->isConnected() ); mSocket = socket; } void DeviceServer::setDeviceIdentifiers( const std::vector<std::string> & i ) { mDeviceIdentifiers = i; } void DeviceServer::startListenThread( void ) { mListenThread = new std::thread([this](){ ServerSocket * serverSocket; Session * session; Socket * socket; serverSocket = getServerSocket(); while( mFlagRunning && mSocket->isConnected() ) { socket = serverSocket->acceptSocket(1); if( socket != nullptr ) { logi("Starting new device session."); session = new DeviceSession(socket, mSocket, &mConnectedDevices, &mDeviceIdentifiers); session->addObserver(this); mSessions[session] = new std::thread([session]{ session->run(); session->notifyObservers(session); delete session; logi("Device session terminated."); }); } cleanupFinishingThreads(); } signalSessions(); mSocket->closeConnection(); while( mSessions.size() > 0 || mInactiveThreads.size() > 0 ) { signalSessions(); cleanupFinishingThreads(); } }); } bool DeviceServer::readBytes( char * buffer , const unsigned int n ) { std::size_t bytesRead; std::size_t nBytes; Reader * reader; // Checking the precondition. assert( buffer != nullptr && n > 0 ); if( !mSocket->isConnected() ) return ( false ); reader = mSocket->getReader(); bytesRead = 0; while( bytesRead != n ) { nBytes = reader->readBytes(buffer + bytesRead,n - bytesRead); if( nBytes == 0 ) return ( false ); bytesRead += nBytes; } return ( true ); } void DeviceServer::dispatchCommand( void ) { std::uint8_t deviceLength; std::uint8_t identifierLength; std::uint8_t parameterLength; std::string message; if( mSocket->isConnected() ) { if( !readBytes(reinterpret_cast<char *>(&deviceLength),1) ) return; if( !readBytes(reinterpret_cast<char *>(&identifierLength),1) ) return; if( !readBytes(reinterpret_cast<char *>(&parameterLength),1) ) return; char deviceIdentifier[deviceLength + 1]; char identifier[identifierLength + 1]; char parameter[parameterLength + 1]; if( !readBytes(deviceIdentifier,deviceLength) ) return; if( !readBytes(identifier,identifierLength) ) return; if( parameterLength > 0 && !readBytes(parameter,parameterLength) ) return; deviceIdentifier[deviceLength] = 0; identifier[identifierLength] = 0; parameter[parameterLength] = 0; // Format the message message += 0x01; message += identifierLength; message += parameterLength; message.append(identifier); message.append(parameter); mConnectedDevices.dispatch(deviceIdentifier,message); } else { stop(); } } void DeviceServer::startDispatchThread( void ) { mDispatchThread = new std::thread([this](){ std::size_t nBytes; std::uint8_t type; Reader * reader; bool heartbeatSend = false; setServerTimeouts(); reader = mSocket->getReader(); while( mFlagRunning && mSocket->isConnected() ) { type = 0xff; nBytes = reader->readByte(reinterpret_cast<char *>(&type)); if( nBytes == 0 ) { if( !serverHeartbeat() || heartbeatSend ) mFlagRunning = false; else heartbeatSend = true; continue; } switch(type) { case 0x00: if( !heartbeatSend ) serverHeartbeat(); break; case 0x01: dispatchCommand(); break; default: mFlagRunning = false; break; } heartbeatSend = false; } stop(); }); } void DeviceServer::signalSessions( void ) { std::map<Session *,std::thread *>::iterator it; mMutexSessions.lock(); for( it = mSessions.begin() ; it != mSessions.end() ; ++it ) it->first->stop(); mMutexSessions.unlock(); } void DeviceServer::cleanupFinishingThreads( void ) { std::thread * t; while( mInactiveThreads.size() > 0 ) { t = mInactiveThreads.front(); if( t != nullptr ) { t->join(); delete t; } mInactiveThreads.erase(mInactiveThreads.begin()); } } bool DeviceServer::serverHeartbeat( void ) { static const std::int8_t beat = 0x00; Writer * writer; bool ok; writer = mSocket->getWriter(); writer->lock(); ok = (writer->writeBytes(reinterpret_cast<const char *>(&beat),1) == 1); writer->unlock(); return ( ok ); } void DeviceServer::setServerTimeouts( void ) { struct timeval tv; tv.tv_sec = 20; tv.tv_usec = 0; mSocket->setReceiveTimeout(tv); } DeviceServer::DeviceServer( ServerSocket * serverSocket, Socket * socket, const std::vector<std::string> & devices ) : Server(serverSocket) { initialize(); setSocket(socket); setDeviceIdentifiers(devices); } DeviceServer::~DeviceServer( void ) { join(); } void DeviceServer::start( void ) { if( mListenThread == nullptr && mDispatchThread == nullptr ) { startListenThread(); startDispatchThread(); } } void DeviceServer::stop( void ) { if( mFlagRunning ) { logi("Stopping device server."); mFlagRunning = false; mSocket->closeConnection(); getServerSocket()->stopListening(); } } void DeviceServer::join( void ) { if( mListenThread != nullptr ) { mListenThread->join(); delete mListenThread; mListenThread = nullptr; } if( mDispatchThread != nullptr ) { mDispatchThread->join(); delete mDispatchThread; mDispatchThread = nullptr; } } void DeviceServer::update( void ) { // Do nothing. } void DeviceServer::update( void * argument ) { std::map<Session *,std::thread *>::iterator it; Session * session; // Checking the precondition. assert( argument != nullptr ); session = static_cast<Session *>(argument); it = mSessions.find(session); if( it != mSessions.end() ) { mInactiveThreads.push_back(it->second); mMutexSessions.lock(); mSessions.erase(it); mMutexSessions.unlock(); } } <|endoftext|>
<commit_before>#ifndef GUARD_MLOPEN_OCL_KERNEL_HPP_ #define GUARD_MLOPEN_OCL_KERNEL_HPP_ #include <sstream> #include <array> #include <utility> #include <vector> #include <mlopen.h> #include <cassert> #include <functional> #include <array> #include <memory> #include <algorithm> #include <mlopen/errors.hpp> #include <mlopen/each_args.hpp> #include <mlopen/clhelper.hpp> namespace mlopen { using SharedKernelPtr = std::shared_ptr<typename std::remove_pointer<cl_kernel>::type>; using SharedProgramPtr = std::shared_ptr<typename std::remove_pointer<cl_program>::type>; struct LocalMemArg { LocalMemArg(size_t _size) : size(_size) {} size_t GetSize() const { return size; } private: size_t size; }; struct OCLSetKernelArg { template<class I, class T> void operator()(cl_kernel kernel, I i, const T& x) const { cl_int status = clSetKernelArg(kernel, i, sizeof(T), reinterpret_cast<const void*>(&x)); if (status != CL_SUCCESS) { MLOPEN_THROW("Error setting argument to kernel: " + std::to_string(status)); } } template<class I> void operator()(cl_kernel kernel, I i, const LocalMemArg& lmem) const { cl_int status = clSetKernelArg(kernel, i, lmem.GetSize(), NULL); if (status != CL_SUCCESS) { MLOPEN_THROW("Error setting argument to kernel: " + std::to_string(status)); } } }; struct OCLKernelInvoke { cl_command_queue queue; SharedKernelPtr kernel; size_t work_dim; std::array<size_t, 3> global_work_offset; std::array<size_t, 3> global_work_dim; std::array<size_t, 3> local_work_dim; std::function<void(cl_event&)> callback; template<class... Ts> void operator()(const Ts&... xs) const { each_args_i(std::bind(OCLSetKernelArg{}, kernel.get(), std::placeholders::_1, std::placeholders::_2), xs...); run(); } void run() const; }; class OCLKernel { public: OCLKernel() {} OCLKernel(ClKernelPtr k) : kernel(std::move(k)) {} OCLKernel(ClKernelPtr k, std::vector<size_t> local_dims, std::vector<size_t> global_dims) : kernel(std::move(k)), ldims(std::move(local_dims)), gdims(std::move(global_dims)) { assert(ldims.size() == gdims.size()); assert(!ldims.empty() && ldims.size() <= 3); } OCLKernel(SharedProgramPtr p, const std::string& kernel_name, std::vector<size_t> local_dims, std::vector<size_t> global_dims) : program(p), kernel(CreateKernel(p.get(), kernel_name)), ldims(std::move(local_dims)), gdims(std::move(global_dims)) { assert(!gdims.empty() && gdims.size() <= 3); assert(!ldims.empty() && ldims.size() <= 3); if(std::any_of(ldims.begin(), ldims.end(), [](size_t x) { return x > 256; })) { std::fill(ldims.begin(), ldims.end(), 0); } } OCLKernelInvoke Invoke(cl_command_queue q, std::function<void(cl_event&)> callback=nullptr); cl_kernel GetKernel() { return kernel.get(); } std::string GetName() const; inline const std::vector<size_t>& GetLocalDims() const { return ldims; } inline const std::vector<size_t>& GetGlobalDims() const { return gdims; } private: SharedProgramPtr program; SharedKernelPtr kernel; std::vector<size_t> ldims; std::vector<size_t> gdims; }; } // namespace mlopen #endif // GUARD_MLOPEN_OCL_KERNEL_HPP_ <commit_msg>Use the product of local dims<commit_after>#ifndef GUARD_MLOPEN_OCL_KERNEL_HPP_ #define GUARD_MLOPEN_OCL_KERNEL_HPP_ #include <sstream> #include <array> #include <utility> #include <vector> #include <mlopen.h> #include <cassert> #include <functional> #include <array> #include <memory> #include <algorithm> #include <mlopen/errors.hpp> #include <mlopen/each_args.hpp> #include <mlopen/clhelper.hpp> namespace mlopen { using SharedKernelPtr = std::shared_ptr<typename std::remove_pointer<cl_kernel>::type>; using SharedProgramPtr = std::shared_ptr<typename std::remove_pointer<cl_program>::type>; struct LocalMemArg { LocalMemArg(size_t _size) : size(_size) {} size_t GetSize() const { return size; } private: size_t size; }; struct OCLSetKernelArg { template<class I, class T> void operator()(cl_kernel kernel, I i, const T& x) const { cl_int status = clSetKernelArg(kernel, i, sizeof(T), reinterpret_cast<const void*>(&x)); if (status != CL_SUCCESS) { MLOPEN_THROW("Error setting argument to kernel: " + std::to_string(status)); } } template<class I> void operator()(cl_kernel kernel, I i, const LocalMemArg& lmem) const { cl_int status = clSetKernelArg(kernel, i, lmem.GetSize(), NULL); if (status != CL_SUCCESS) { MLOPEN_THROW("Error setting argument to kernel: " + std::to_string(status)); } } }; struct OCLKernelInvoke { cl_command_queue queue; SharedKernelPtr kernel; size_t work_dim; std::array<size_t, 3> global_work_offset; std::array<size_t, 3> global_work_dim; std::array<size_t, 3> local_work_dim; std::function<void(cl_event&)> callback; template<class... Ts> void operator()(const Ts&... xs) const { each_args_i(std::bind(OCLSetKernelArg{}, kernel.get(), std::placeholders::_1, std::placeholders::_2), xs...); run(); } void run() const; }; class OCLKernel { public: OCLKernel() {} OCLKernel(ClKernelPtr k) : kernel(std::move(k)) {} OCLKernel(ClKernelPtr k, std::vector<size_t> local_dims, std::vector<size_t> global_dims) : kernel(std::move(k)), ldims(std::move(local_dims)), gdims(std::move(global_dims)) { assert(ldims.size() == gdims.size()); assert(!ldims.empty() && ldims.size() <= 3); } OCLKernel(SharedProgramPtr p, const std::string& kernel_name, std::vector<size_t> local_dims, std::vector<size_t> global_dims) : program(p), kernel(CreateKernel(p.get(), kernel_name)), ldims(std::move(local_dims)), gdims(std::move(global_dims)) { assert(!gdims.empty() && gdims.size() <= 3); assert(!ldims.empty() && ldims.size() <= 3); if(std::accumulate(ldims.begin(), ldims.end(), 1, std::multiplies<size_t>{}) > 256) { std::fill(ldims.begin(), ldims.end(), 0); } } OCLKernelInvoke Invoke(cl_command_queue q, std::function<void(cl_event&)> callback=nullptr); cl_kernel GetKernel() { return kernel.get(); } std::string GetName() const; inline const std::vector<size_t>& GetLocalDims() const { return ldims; } inline const std::vector<size_t>& GetGlobalDims() const { return gdims; } private: SharedProgramPtr program; SharedKernelPtr kernel; std::vector<size_t> ldims; std::vector<size_t> gdims; }; } // namespace mlopen #endif // GUARD_MLOPEN_OCL_KERNEL_HPP_ <|endoftext|>
<commit_before>/** * Based on: https://github.com/davetcoleman/ros_control_boilerplate */ #include <kulbu_hardware/kulbu_hardware_interface.h> #include <fcntl.h> #define SYSFS_GPIO_DIR "/sys/class/gpio" #define SYSFS_PWM_DIR "/sys/devices/platform/pwm-ctrl" #define MAX_BUF 256 // FIXME: Encapsulate this IO code. int pwm_enable(unsigned int pwm, bool enable) { int fd; char buf[MAX_BUF]; // First check current value, only update if changed. char curr[11]; int status; snprintf(buf, sizeof(buf), SYSFS_PWM_DIR "/enable%d", pwm); fd = open(buf, sizeof(buf), O_RDONLY); if (fd < 0) { // perror("pwm/enable/read"); ROS_ERROR_STREAM_NAMED("kulbu_hardware_interface", "pwm/enable/read"); return fd; } read(fd, curr, sizeof(curr)); close(fd); // "On" always ends with an "n". status = (curr[strlen(curr)-2] == 'n'); if (status != enable) { ROS_DEBUG_STREAM_NAMED("kulbu_hardware_interface", "Chan: " << pwm << " Enable: " << enable); snprintf(buf, sizeof(buf), SYSFS_PWM_DIR "/enable%d", pwm); fd = open(buf, O_WRONLY); if (fd < 0) { // perror("pwm/enable/write"); ROS_ERROR_STREAM_NAMED("kulbu_hardware_interface", "pwm/enable/write"); return fd; } if (enable) write(fd, "1", 2); else write(fd, "0", 2); close(fd); } return 0; } int pwm_freq(unsigned int pwm, unsigned int freq) { int fd; char buf[MAX_BUF]; // First check current value, only update if changed. char curr[11]; int status; snprintf(buf, sizeof(buf), SYSFS_PWM_DIR "/freq%d", pwm); fd = open(buf, sizeof(buf), O_RDONLY); if (fd < 0) { // perror("pwm/freq/read"); ROS_ERROR_STREAM_NAMED("kulbu_hardware_interface", "pwm/freq/read"); return fd; } read(fd, curr, sizeof(curr)); close(fd); if (atoi(curr) != freq && freq >= 1) { ROS_DEBUG_STREAM_NAMED("kulbu_hardware_interface", "Chan: " << pwm << " Freq: " << freq); snprintf(buf, sizeof(buf), SYSFS_PWM_DIR "/freq%d", pwm); fd = open(buf, O_WRONLY); if (fd < 0) { // perror("pwm/freq/write"); ROS_ERROR_STREAM_NAMED("kulbu_hardware_interface", "pwm/freq/write"); return fd; } int len = snprintf(buf, sizeof(buf), "%d", freq); write(fd, buf, len); close(fd); } return 0; } int pwm_duty(unsigned int pwm, unsigned int duty) { int fd; char buf[MAX_BUF]; ROS_DEBUG_STREAM_NAMED("kulbu_hardware_interface", "Chan: " << pwm << " Duty: " << duty); snprintf(buf, sizeof(buf), SYSFS_PWM_DIR "/duty%d", pwm); fd = open(buf, O_WRONLY); if (fd < 0) { // perror("pwm/duty/write"); ROS_ERROR_STREAM_NAMED("kulbu_hardware_interface", "pwm/duty/write"); return fd; } int len = snprintf(buf, sizeof(buf), "%d", duty); write(fd, buf, len); close(fd); return 0; } int gpio_set(unsigned int gpio, unsigned int value) { int fd; char buf[MAX_BUF]; ROS_DEBUG_STREAM_NAMED("kulbu_hardware_interface", "GPIO: " << gpio << " Value: " << value); snprintf(buf, sizeof(buf), SYSFS_GPIO_DIR "/gpio%d/value", gpio); fd = open(buf, O_WRONLY); if (fd < 0) { // perror("gpio/set-value"); ROS_ERROR_STREAM_NAMED("kulbu_hardware_interface", "gpio/set-value"); return fd; } if (value) write(fd, "1", 2); else write(fd, "0", 2); close(fd); return 0; } namespace kulbu_hardware { KulbuHardwareInterface::KulbuHardwareInterface( ros::NodeHandle& nh, int joint_mode) : nh_(nh), joint_mode_(joint_mode) { // Initialize shared memory and interfaces here init(); // this implementation loads from rosparam ROS_INFO_NAMED("kulbu_hardware_interface", "Loaded kulbu_hardware_interface."); } void KulbuHardwareInterface::init() { ROS_INFO_STREAM_NAMED("kulbu_hardware_interface", "Reading rosparams from namespace: " << nh_.getNamespace()); nh_.getParam("hardware_interface/steps_per_m", steps_per_m_); if (!steps_per_m_ > 0) { ROS_FATAL_STREAM_NAMED("kulbu_hardware_interface", "No step per metre found on parameter server." << " Namespace: " << nh_.getNamespace()); exit(-1); } // Get joint names nh_.getParam("hardware_interface/joints", joint_names_); if (joint_names_.size() == 0) { ROS_FATAL_STREAM_NAMED("kulbu_hardware_interface", "No joints found on parameter server" << " Namespace: " << nh_.getNamespace()); exit(-1); } num_joints_ = joint_names_.size(); nh_.getParam("hardware_interface/dirs", pin_dirs_); if (pin_dirs_.size() == 0) { ROS_FATAL_STREAM_NAMED("kulbu_hardware_interface", "No GPIO direction pins found on parameter server." << " Namespace: " << nh_.getNamespace()); exit(-1); } nh_.getParam("hardware_interface/steps", pin_steps_); if (pin_steps_.size() == 0) { ROS_FATAL_STREAM_NAMED("kulbu_hardware_interface", "No GPIO step pins found on parameter server." << " Namespace: " << nh_.getNamespace()); exit(-1); } // Resize vectors joint_position_.resize(num_joints_); joint_velocity_.resize(num_joints_); joint_effort_.resize(num_joints_); joint_position_command_.resize(num_joints_); joint_velocity_command_.resize(num_joints_); joint_effort_command_.resize(num_joints_); // Initialize controller for (std::size_t i = 0; i < num_joints_; ++i) { ROS_DEBUG_STREAM_NAMED("kulbu_hardware_interface", "Loading joint name: " << joint_names_[i]); // Start with PWM turned off and 50/50 duty cycle. pwm_enable(pin_steps_[i], 0); pwm_duty(pin_steps_[i], 512); // Set direction pins to forward by default. gpio_set(pin_dirs_[i], 0); // Create joint state interface joint_state_interface_.registerHandle(hardware_interface::JointStateHandle( joint_names_[i], &joint_position_[i], &joint_velocity_[i], &joint_effort_[i])); switch (joint_mode_) { case 0: // Create position joint interface position_joint_interface_ .registerHandle(hardware_interface::JointHandle( joint_state_interface_.getHandle( joint_names_[i]), &joint_position_command_[i])); break; case 1: // Create velocity joint interface velocity_joint_interface_ .registerHandle(hardware_interface::JointHandle( joint_state_interface_.getHandle( joint_names_[i]), &joint_velocity_command_[i])); break; case 2: // Create effort joint interface effort_joint_interface_ .registerHandle(hardware_interface::JointHandle( joint_state_interface_.getHandle( joint_names_[i]), &joint_effort_command_[i])); break; } } registerInterface(&joint_state_interface_); // From RobotHW base class. registerInterface(&position_joint_interface_); // From RobotHW base class. registerInterface(&velocity_joint_interface_); // From RobotHW base class. registerInterface(&effort_joint_interface_); // From RobotHW base class. } void KulbuHardwareInterface::read(ros::Duration elapsed_time) { // Read the joint states from your hardware here // e.g. // for (std::size_t i = 0; i < num_joints_; ++i) // { // joint_position_[i] = robot_api_.getJointPosition(i); // joint_velocity_[i] = robot_api_.getJointVelocity(i); // joint_effort_[i] = robot_api_.getJointEffort(i); // } } void KulbuHardwareInterface::write(ros::Duration elapsed_time) { int freq = 0; int dir = 0; // Send commands in different modes for (std::size_t i = 0; i < num_joints_; ++i) { // Skip joints with no pins defined if (pin_dirs_[i] == -1 || pin_steps_[i] == -1) continue; switch (joint_mode_) { case 1: // hardware_interface::MODE_VELOCITY: // Calc PWM frequency. freq = joint_velocity_command_[i] * steps_per_m_; // Reverse flips direction. if (freq < 0) { freq = abs(freq); dir = 1; } else { dir = 0; } // Disable PWM when stopped. if (freq < 1) { freq = 0; pwm_enable(pin_steps_[i], 0); } else { pwm_enable(pin_steps_[i], 1); } // Set direction pin. gpio_set(pin_dirs_[i], dir); // Set PWM frequency. pwm_freq(pin_steps_[i], freq); ROS_DEBUG_STREAM_NAMED("kulbu_hardware_interface", "\ni: " << i << "\ncmd: " << joint_velocity_command_[i] << "\ndist: " << steps_per_m_ << "\nfreq: " << freq << "\ndir: " << dir << "\njoint: " << joint_names_[i] << "\ndir: " << pin_dirs_[i] << "\nstep: " << pin_steps_[i]); break; default: ROS_ERROR_STREAM_NAMED("kulbu_hardware_interface", "Joint mode not implemented"); break; } } } } // namespace kulbu_hardware <commit_msg>Cleanup old error code<commit_after>/** * Based on: https://github.com/davetcoleman/ros_control_boilerplate */ #include <kulbu_hardware/kulbu_hardware_interface.h> #include <fcntl.h> #define SYSFS_GPIO_DIR "/sys/class/gpio" #define SYSFS_PWM_DIR "/sys/devices/platform/pwm-ctrl" #define MAX_BUF 256 // FIXME: Encapsulate this IO code. int pwm_enable(unsigned int pwm, bool enable) { int fd; char buf[MAX_BUF]; // First check current value, only update if changed. char curr[11]; int status; snprintf(buf, sizeof(buf), SYSFS_PWM_DIR "/enable%d", pwm); fd = open(buf, sizeof(buf), O_RDONLY); if (fd < 0) { ROS_ERROR_STREAM_NAMED("kulbu_hardware_interface", "pwm/enable/read"); return fd; } read(fd, curr, sizeof(curr)); close(fd); // "On" always ends with an "n". status = (curr[strlen(curr)-2] == 'n'); if (status != enable) { ROS_DEBUG_STREAM_NAMED("kulbu_hardware_interface", "Chan: " << pwm << " Enable: " << enable); snprintf(buf, sizeof(buf), SYSFS_PWM_DIR "/enable%d", pwm); fd = open(buf, O_WRONLY); if (fd < 0) { ROS_ERROR_STREAM_NAMED("kulbu_hardware_interface", "pwm/enable/write"); return fd; } if (enable) write(fd, "1", 2); else write(fd, "0", 2); close(fd); } return 0; } int pwm_freq(unsigned int pwm, unsigned int freq) { int fd; char buf[MAX_BUF]; // First check current value, only update if changed. char curr[11]; int status; snprintf(buf, sizeof(buf), SYSFS_PWM_DIR "/freq%d", pwm); fd = open(buf, sizeof(buf), O_RDONLY); if (fd < 0) { ROS_ERROR_STREAM_NAMED("kulbu_hardware_interface", "pwm/freq/read"); return fd; } read(fd, curr, sizeof(curr)); close(fd); if (atoi(curr) != freq && freq >= 1) { ROS_DEBUG_STREAM_NAMED("kulbu_hardware_interface", "Chan: " << pwm << " Freq: " << freq); snprintf(buf, sizeof(buf), SYSFS_PWM_DIR "/freq%d", pwm); fd = open(buf, O_WRONLY); if (fd < 0) { ROS_ERROR_STREAM_NAMED("kulbu_hardware_interface", "pwm/freq/write"); return fd; } int len = snprintf(buf, sizeof(buf), "%d", freq); write(fd, buf, len); close(fd); } return 0; } int pwm_duty(unsigned int pwm, unsigned int duty) { int fd; char buf[MAX_BUF]; ROS_DEBUG_STREAM_NAMED("kulbu_hardware_interface", "Chan: " << pwm << " Duty: " << duty); snprintf(buf, sizeof(buf), SYSFS_PWM_DIR "/duty%d", pwm); fd = open(buf, O_WRONLY); if (fd < 0) { ROS_ERROR_STREAM_NAMED("kulbu_hardware_interface", "pwm/duty/write"); return fd; } int len = snprintf(buf, sizeof(buf), "%d", duty); write(fd, buf, len); close(fd); return 0; } int gpio_set(unsigned int gpio, unsigned int value) { int fd; char buf[MAX_BUF]; ROS_DEBUG_STREAM_NAMED("kulbu_hardware_interface", "GPIO: " << gpio << " Value: " << value); snprintf(buf, sizeof(buf), SYSFS_GPIO_DIR "/gpio%d/value", gpio); fd = open(buf, O_WRONLY); if (fd < 0) { ROS_ERROR_STREAM_NAMED("kulbu_hardware_interface", "gpio/set-value"); return fd; } if (value) write(fd, "1", 2); else write(fd, "0", 2); close(fd); return 0; } namespace kulbu_hardware { KulbuHardwareInterface::KulbuHardwareInterface( ros::NodeHandle& nh, int joint_mode) : nh_(nh), joint_mode_(joint_mode) { // Initialize shared memory and interfaces here init(); // this implementation loads from rosparam ROS_INFO_NAMED("kulbu_hardware_interface", "Loaded kulbu_hardware_interface."); } void KulbuHardwareInterface::init() { ROS_INFO_STREAM_NAMED("kulbu_hardware_interface", "Reading rosparams from namespace: " << nh_.getNamespace()); nh_.getParam("hardware_interface/steps_per_m", steps_per_m_); if (!steps_per_m_ > 0) { ROS_FATAL_STREAM_NAMED("kulbu_hardware_interface", "No step per metre found on parameter server." << " Namespace: " << nh_.getNamespace()); exit(-1); } // Get joint names nh_.getParam("hardware_interface/joints", joint_names_); if (joint_names_.size() == 0) { ROS_FATAL_STREAM_NAMED("kulbu_hardware_interface", "No joints found on parameter server" << " Namespace: " << nh_.getNamespace()); exit(-1); } num_joints_ = joint_names_.size(); nh_.getParam("hardware_interface/dirs", pin_dirs_); if (pin_dirs_.size() == 0) { ROS_FATAL_STREAM_NAMED("kulbu_hardware_interface", "No GPIO direction pins found on parameter server." << " Namespace: " << nh_.getNamespace()); exit(-1); } nh_.getParam("hardware_interface/steps", pin_steps_); if (pin_steps_.size() == 0) { ROS_FATAL_STREAM_NAMED("kulbu_hardware_interface", "No GPIO step pins found on parameter server." << " Namespace: " << nh_.getNamespace()); exit(-1); } // Resize vectors joint_position_.resize(num_joints_); joint_velocity_.resize(num_joints_); joint_effort_.resize(num_joints_); joint_position_command_.resize(num_joints_); joint_velocity_command_.resize(num_joints_); joint_effort_command_.resize(num_joints_); // Initialize controller for (std::size_t i = 0; i < num_joints_; ++i) { ROS_DEBUG_STREAM_NAMED("kulbu_hardware_interface", "Loading joint name: " << joint_names_[i]); // Start with PWM turned off and 50/50 duty cycle. pwm_enable(pin_steps_[i], 0); pwm_duty(pin_steps_[i], 512); // Set direction pins to forward by default. gpio_set(pin_dirs_[i], 0); // Create joint state interface joint_state_interface_.registerHandle(hardware_interface::JointStateHandle( joint_names_[i], &joint_position_[i], &joint_velocity_[i], &joint_effort_[i])); switch (joint_mode_) { case 0: // Create position joint interface position_joint_interface_ .registerHandle(hardware_interface::JointHandle( joint_state_interface_.getHandle( joint_names_[i]), &joint_position_command_[i])); break; case 1: // Create velocity joint interface velocity_joint_interface_ .registerHandle(hardware_interface::JointHandle( joint_state_interface_.getHandle( joint_names_[i]), &joint_velocity_command_[i])); break; case 2: // Create effort joint interface effort_joint_interface_ .registerHandle(hardware_interface::JointHandle( joint_state_interface_.getHandle( joint_names_[i]), &joint_effort_command_[i])); break; } } registerInterface(&joint_state_interface_); // From RobotHW base class. registerInterface(&position_joint_interface_); // From RobotHW base class. registerInterface(&velocity_joint_interface_); // From RobotHW base class. registerInterface(&effort_joint_interface_); // From RobotHW base class. } void KulbuHardwareInterface::read(ros::Duration elapsed_time) { // Read the joint states from your hardware here // e.g. // for (std::size_t i = 0; i < num_joints_; ++i) // { // joint_position_[i] = robot_api_.getJointPosition(i); // joint_velocity_[i] = robot_api_.getJointVelocity(i); // joint_effort_[i] = robot_api_.getJointEffort(i); // } } void KulbuHardwareInterface::write(ros::Duration elapsed_time) { int freq = 0; int dir = 0; // Send commands in different modes for (std::size_t i = 0; i < num_joints_; ++i) { // Skip joints with no pins defined if (pin_dirs_[i] == -1 || pin_steps_[i] == -1) continue; switch (joint_mode_) { case 1: // hardware_interface::MODE_VELOCITY: // Calc PWM frequency. freq = joint_velocity_command_[i] * steps_per_m_; // Reverse flips direction. if (freq < 0) { freq = abs(freq); dir = 1; } else { dir = 0; } // Disable PWM when stopped. if (freq < 1) { freq = 0; pwm_enable(pin_steps_[i], 0); } else { pwm_enable(pin_steps_[i], 1); } // Set direction pin. gpio_set(pin_dirs_[i], dir); // Set PWM frequency. pwm_freq(pin_steps_[i], freq); ROS_DEBUG_STREAM_NAMED("kulbu_hardware_interface", "\ni: " << i << "\ncmd: " << joint_velocity_command_[i] << "\ndist: " << steps_per_m_ << "\nfreq: " << freq << "\ndir: " << dir << "\njoint: " << joint_names_[i] << "\ndir: " << pin_dirs_[i] << "\nstep: " << pin_steps_[i]); break; default: ROS_ERROR_STREAM_NAMED("kulbu_hardware_interface", "Joint mode not implemented"); break; } } } } // namespace kulbu_hardware <|endoftext|>
<commit_before>/* * GCM GHASH * (C) 2013,2015,2017 Jack Lloyd * (C) 2016 Daniel Neus, Rohde & Schwarz Cybersecurity * * Botan is released under the Simplified BSD License (see license.txt) */ #include <botan/ghash.h> #include <botan/internal/ct_utils.h> #include <botan/loadstor.h> #include <botan/cpuid.h> #if defined(BOTAN_HAS_GCM_CLMUL) #include <botan/internal/clmul.h> #endif #if defined(BOTAN_HAS_GCM_CLMUL_SSSE3) #include <botan/internal/clmul_ssse3.h> #endif #if defined(BOTAN_HAS_GCM_PMULL) #include <botan/internal/pmull.h> #endif namespace Botan { std::string GHASH::provider() const { #if defined(BOTAN_HAS_GCM_CLMUL) if(CPUID::has_clmul()) return "clmul"; #endif #if defined(BOTAN_HAS_GCM_CLMUL_SSSE3) if(CPUID::has_ssse3()) return "ssse3"; #endif #if defined(BOTAN_HAS_GCM_PMULL) if(CPUID::has_arm_pmull()) return "pmull"; #endif return "base"; } void GHASH::gcm_multiply(secure_vector<uint8_t>& x, const uint8_t input[], size_t blocks) { #if defined(BOTAN_HAS_GCM_CLMUL) if(CPUID::has_clmul()) { return gcm_multiply_clmul(x.data(), m_H_pow.data(), input, blocks); } #endif #if defined(BOTAN_HAS_GCM_CLMUL_SSSE3) if(CPUID::has_ssse3()) { return gcm_multiply_ssse3(x.data(), m_HM.data(), input, blocks); } #endif #if defined(BOTAN_HAS_GCM_PMULL) if(CPUID::has_arm_pmull()) { return gcm_multiply_pmull(x.data(), m_H_pow.data(), input, blocks); } #endif CT::poison(x.data(), x.size()); const uint64_t ALL_BITS = 0xFFFFFFFFFFFFFFFF; uint64_t X[2] = { load_be<uint64_t>(x.data(), 0), load_be<uint64_t>(x.data(), 1) }; for(size_t b = 0; b != blocks; ++b) { X[0] ^= load_be<uint64_t>(input, 2*b); X[1] ^= load_be<uint64_t>(input, 2*b+1); uint64_t Z[2] = { 0, 0 }; for(size_t i = 0; i != 64; ++i) { const uint64_t X0MASK = (ALL_BITS + (X[0] >> 63)) ^ ALL_BITS; const uint64_t X1MASK = (ALL_BITS + (X[1] >> 63)) ^ ALL_BITS; X[0] <<= 1; X[1] <<= 1; Z[0] ^= m_HM[4*i ] & X0MASK; Z[1] ^= m_HM[4*i+1] & X0MASK; Z[0] ^= m_HM[4*i+2] & X1MASK; Z[1] ^= m_HM[4*i+3] & X1MASK; } X[0] = Z[0]; X[1] = Z[1]; } store_be<uint64_t>(x.data(), X[0], X[1]); CT::unpoison(x.data(), x.size()); } void GHASH::ghash_update(secure_vector<uint8_t>& ghash, const uint8_t input[], size_t length) { /* This assumes if less than block size input then we're just on the final block and should pad with zeros */ const size_t full_blocks = length / GCM_BS; const size_t final_bytes = length - (full_blocks * GCM_BS); if(full_blocks > 0) { gcm_multiply(ghash, input, full_blocks); } if(final_bytes) { secure_vector<uint8_t> last_block(GCM_BS); copy_mem(last_block.data(), input + full_blocks * GCM_BS, final_bytes); gcm_multiply(ghash, last_block.data(), 1); } } void GHASH::key_schedule(const uint8_t key[], size_t length) { m_H.assign(key, key+length); m_H_ad.resize(GCM_BS); m_ad_len = 0; m_text_len = 0; uint64_t H0 = load_be<uint64_t>(m_H.data(), 0); uint64_t H1 = load_be<uint64_t>(m_H.data(), 1); const uint64_t R = 0xE100000000000000; m_HM.resize(256); // precompute the multiples of H for(size_t i = 0; i != 2; ++i) { for(size_t j = 0; j != 64; ++j) { /* we interleave H^1, H^65, H^2, H^66, H3, H67, H4, H68 to make indexing nicer in the multiplication code */ m_HM[4*j+2*i] = H0; m_HM[4*j+2*i+1] = H1; // GCM's bit ops are reversed so we carry out of the bottom const uint64_t carry = R * (H1 & 1); H1 = (H1 >> 1) | (H0 << 63); H0 = (H0 >> 1) ^ carry; } } #if defined(BOTAN_HAS_GCM_CLMUL) if(CPUID::has_clmul()) { m_H_pow.resize(8); gcm_clmul_precompute(m_H.data(), m_H_pow.data()); } #endif #if defined(BOTAN_HAS_GCM_PMULL) if(CPUID::has_arm_pmull()) { m_H_pow.resize(8); gcm_pmull_precompute(m_H.data(), m_H_pow.data()); } #endif } void GHASH::start(const uint8_t nonce[], size_t len) { m_nonce.assign(nonce, nonce + len); m_ghash = m_H_ad; } void GHASH::set_associated_data(const uint8_t input[], size_t length) { zeroise(m_H_ad); ghash_update(m_H_ad, input, length); m_ad_len = length; } void GHASH::update_associated_data(const uint8_t ad[], size_t length) { verify_key_set(m_ghash.size() == GCM_BS); m_ad_len += length; ghash_update(m_ghash, ad, length); } void GHASH::update(const uint8_t input[], size_t length) { BOTAN_ASSERT(m_ghash.size() == GCM_BS, "Key was set"); m_text_len += length; ghash_update(m_ghash, input, length); } void GHASH::add_final_block(secure_vector<uint8_t>& hash, size_t ad_len, size_t text_len) { /* * stack buffer is fine here since the text len is public * and the length of the AD is probably not sensitive either. */ uint8_t final_block[GCM_BS]; store_be<uint64_t>(final_block, 8*ad_len, 8*text_len); ghash_update(hash, final_block, GCM_BS); } secure_vector<uint8_t> GHASH::final() { add_final_block(m_ghash, m_ad_len, m_text_len); secure_vector<uint8_t> mac; mac.swap(m_ghash); mac ^= m_nonce; m_text_len = 0; return mac; } secure_vector<uint8_t> GHASH::nonce_hash(const uint8_t nonce[], size_t nonce_len) { BOTAN_ASSERT(m_ghash.size() == 0, "nonce_hash called during wrong time"); secure_vector<uint8_t> y0(GCM_BS); ghash_update(y0, nonce, nonce_len); add_final_block(y0, 0, nonce_len); return y0; } void GHASH::clear() { zeroise(m_H); zeroise(m_HM); reset(); } void GHASH::reset() { zeroise(m_H_ad); m_ghash.clear(); m_nonce.clear(); m_text_len = m_ad_len = 0; } } <commit_msg>GHASH - use explicit function to check for key being set<commit_after>/* * GCM GHASH * (C) 2013,2015,2017 Jack Lloyd * (C) 2016 Daniel Neus, Rohde & Schwarz Cybersecurity * * Botan is released under the Simplified BSD License (see license.txt) */ #include <botan/ghash.h> #include <botan/internal/ct_utils.h> #include <botan/loadstor.h> #include <botan/cpuid.h> #if defined(BOTAN_HAS_GCM_CLMUL) #include <botan/internal/clmul.h> #endif #if defined(BOTAN_HAS_GCM_CLMUL_SSSE3) #include <botan/internal/clmul_ssse3.h> #endif #if defined(BOTAN_HAS_GCM_PMULL) #include <botan/internal/pmull.h> #endif namespace Botan { std::string GHASH::provider() const { #if defined(BOTAN_HAS_GCM_CLMUL) if(CPUID::has_clmul()) return "clmul"; #endif #if defined(BOTAN_HAS_GCM_CLMUL_SSSE3) if(CPUID::has_ssse3()) return "ssse3"; #endif #if defined(BOTAN_HAS_GCM_PMULL) if(CPUID::has_arm_pmull()) return "pmull"; #endif return "base"; } void GHASH::gcm_multiply(secure_vector<uint8_t>& x, const uint8_t input[], size_t blocks) { #if defined(BOTAN_HAS_GCM_CLMUL) if(CPUID::has_clmul()) { return gcm_multiply_clmul(x.data(), m_H_pow.data(), input, blocks); } #endif #if defined(BOTAN_HAS_GCM_CLMUL_SSSE3) if(CPUID::has_ssse3()) { return gcm_multiply_ssse3(x.data(), m_HM.data(), input, blocks); } #endif #if defined(BOTAN_HAS_GCM_PMULL) if(CPUID::has_arm_pmull()) { return gcm_multiply_pmull(x.data(), m_H_pow.data(), input, blocks); } #endif CT::poison(x.data(), x.size()); const uint64_t ALL_BITS = 0xFFFFFFFFFFFFFFFF; uint64_t X[2] = { load_be<uint64_t>(x.data(), 0), load_be<uint64_t>(x.data(), 1) }; for(size_t b = 0; b != blocks; ++b) { X[0] ^= load_be<uint64_t>(input, 2*b); X[1] ^= load_be<uint64_t>(input, 2*b+1); uint64_t Z[2] = { 0, 0 }; for(size_t i = 0; i != 64; ++i) { const uint64_t X0MASK = (ALL_BITS + (X[0] >> 63)) ^ ALL_BITS; const uint64_t X1MASK = (ALL_BITS + (X[1] >> 63)) ^ ALL_BITS; X[0] <<= 1; X[1] <<= 1; Z[0] ^= m_HM[4*i ] & X0MASK; Z[1] ^= m_HM[4*i+1] & X0MASK; Z[0] ^= m_HM[4*i+2] & X1MASK; Z[1] ^= m_HM[4*i+3] & X1MASK; } X[0] = Z[0]; X[1] = Z[1]; } store_be<uint64_t>(x.data(), X[0], X[1]); CT::unpoison(x.data(), x.size()); } void GHASH::ghash_update(secure_vector<uint8_t>& ghash, const uint8_t input[], size_t length) { /* This assumes if less than block size input then we're just on the final block and should pad with zeros */ const size_t full_blocks = length / GCM_BS; const size_t final_bytes = length - (full_blocks * GCM_BS); if(full_blocks > 0) { gcm_multiply(ghash, input, full_blocks); } if(final_bytes) { secure_vector<uint8_t> last_block(GCM_BS); copy_mem(last_block.data(), input + full_blocks * GCM_BS, final_bytes); gcm_multiply(ghash, last_block.data(), 1); } } void GHASH::key_schedule(const uint8_t key[], size_t length) { m_H.assign(key, key+length); m_H_ad.resize(GCM_BS); m_ad_len = 0; m_text_len = 0; uint64_t H0 = load_be<uint64_t>(m_H.data(), 0); uint64_t H1 = load_be<uint64_t>(m_H.data(), 1); const uint64_t R = 0xE100000000000000; m_HM.resize(256); // precompute the multiples of H for(size_t i = 0; i != 2; ++i) { for(size_t j = 0; j != 64; ++j) { /* we interleave H^1, H^65, H^2, H^66, H3, H67, H4, H68 to make indexing nicer in the multiplication code */ m_HM[4*j+2*i] = H0; m_HM[4*j+2*i+1] = H1; // GCM's bit ops are reversed so we carry out of the bottom const uint64_t carry = R * (H1 & 1); H1 = (H1 >> 1) | (H0 << 63); H0 = (H0 >> 1) ^ carry; } } #if defined(BOTAN_HAS_GCM_CLMUL) if(CPUID::has_clmul()) { m_H_pow.resize(8); gcm_clmul_precompute(m_H.data(), m_H_pow.data()); } #endif #if defined(BOTAN_HAS_GCM_PMULL) if(CPUID::has_arm_pmull()) { m_H_pow.resize(8); gcm_pmull_precompute(m_H.data(), m_H_pow.data()); } #endif } void GHASH::start(const uint8_t nonce[], size_t len) { m_nonce.assign(nonce, nonce + len); m_ghash = m_H_ad; } void GHASH::set_associated_data(const uint8_t input[], size_t length) { zeroise(m_H_ad); ghash_update(m_H_ad, input, length); m_ad_len = length; } void GHASH::update_associated_data(const uint8_t ad[], size_t length) { verify_key_set(m_ghash.size() == GCM_BS); m_ad_len += length; ghash_update(m_ghash, ad, length); } void GHASH::update(const uint8_t input[], size_t length) { verify_key_set(m_ghash.size() == GCM_BS); m_text_len += length; ghash_update(m_ghash, input, length); } void GHASH::add_final_block(secure_vector<uint8_t>& hash, size_t ad_len, size_t text_len) { /* * stack buffer is fine here since the text len is public * and the length of the AD is probably not sensitive either. */ uint8_t final_block[GCM_BS]; store_be<uint64_t>(final_block, 8*ad_len, 8*text_len); ghash_update(hash, final_block, GCM_BS); } secure_vector<uint8_t> GHASH::final() { add_final_block(m_ghash, m_ad_len, m_text_len); secure_vector<uint8_t> mac; mac.swap(m_ghash); mac ^= m_nonce; m_text_len = 0; return mac; } secure_vector<uint8_t> GHASH::nonce_hash(const uint8_t nonce[], size_t nonce_len) { BOTAN_ASSERT(m_ghash.size() == 0, "nonce_hash called during wrong time"); secure_vector<uint8_t> y0(GCM_BS); ghash_update(y0, nonce, nonce_len); add_final_block(y0, 0, nonce_len); return y0; } void GHASH::clear() { zeroise(m_H); zeroise(m_HM); reset(); } void GHASH::reset() { zeroise(m_H_ad); m_ghash.clear(); m_nonce.clear(); m_text_len = m_ad_len = 0; } } <|endoftext|>
<commit_before>/* * * Copyright (c) 2020 Project CHIP Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @file * Source implementation of an input / output stream for stdio targets. */ #include "shell.h" #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <termio.h> #include <unistd.h> namespace chip { namespace Shell { static struct termios the_original_stdin_termios; static void streamer_restore_termios(void) { int in_fd = fileno(stdin); tcsetattr(in_fd, TCSAFLUSH, &the_original_stdin_termios); } int streamer_stdio_init(streamer_t * streamer) { int ret = 0; int in_fd = fileno(stdin); struct termios termios; if (isatty(in_fd)) { ret = tcgetattr(in_fd, &the_original_stdin_termios); atexit(&streamer_restore_termios); ret = tcgetattr(in_fd, &termios); termios.c_lflag &= ~ECHO; // Disable echo mode termios.c_lflag &= ~ICANON; // Disable canonical line editing mode ret = tcsetattr(in_fd, TCSANOW, &termios); } return ret; } int streamer_stdio_read(streamer_t * streamer, char * buf, size_t len) { return read(STDIN_FILENO, buf, len); } int streamer_stdio_write(streamer_t * streamer, const char * buf, size_t len) { return write(STDOUT_FILENO, buf, len); } static streamer_t streamer_stdio = { .init_cb = streamer_stdio_init, .read_cb = streamer_stdio_read, .write_cb = streamer_stdio_write, }; streamer_t * streamer_get(void) { return &streamer_stdio; } } // namespace Shell } // namespace chip <commit_msg>[shell] Fix #1074: iOS build - use latest posix include. (#1076)<commit_after>/* * * Copyright (c) 2020 Project CHIP Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @file * Source implementation of an input / output stream for stdio targets. */ #include "shell.h" #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <termios.h> #include <unistd.h> namespace chip { namespace Shell { static struct termios the_original_stdin_termios; static void streamer_restore_termios(void) { int in_fd = fileno(stdin); tcsetattr(in_fd, TCSAFLUSH, &the_original_stdin_termios); } int streamer_stdio_init(streamer_t * streamer) { int ret = 0; int in_fd = fileno(stdin); struct termios termios; if (isatty(in_fd)) { ret = tcgetattr(in_fd, &the_original_stdin_termios); atexit(&streamer_restore_termios); ret = tcgetattr(in_fd, &termios); termios.c_lflag &= ~ECHO; // Disable echo mode termios.c_lflag &= ~ICANON; // Disable canonical line editing mode ret = tcsetattr(in_fd, TCSANOW, &termios); } return ret; } int streamer_stdio_read(streamer_t * streamer, char * buf, size_t len) { return read(STDIN_FILENO, buf, len); } int streamer_stdio_write(streamer_t * streamer, const char * buf, size_t len) { return write(STDOUT_FILENO, buf, len); } static streamer_t streamer_stdio = { .init_cb = streamer_stdio_init, .read_cb = streamer_stdio_read, .write_cb = streamer_stdio_write, }; streamer_t * streamer_get(void) { return &streamer_stdio; } } // namespace Shell } // namespace chip <|endoftext|>
<commit_before>// Copyright (c) 2014 libmv authors. // // 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 "libmv/base/aligned_malloc.h" #if !defined(__APPLE__) && !defined(__FreeBSD__) && !defined(__NetBSD__) // Needed for memalign on Linux and _aligned_alloc on Windows. # ifdef FREE_WINDOWS /* make sure _aligned_malloc is included */ # ifdef __MSVCRT_VERSION__ # undef __MSVCRT_VERSION__ # endif # define __MSVCRT_VERSION__ 0x0700 # endif // FREE_WINDOWS # include <malloc.h> #else // Apple's malloc is 16-byte aligned, and does not have malloc.h, so include // stdilb instead. # include <cstdlib> #endif namespace libmv { void *aligned_malloc(int size, int alignment) { #ifdef _WIN32 return _aligned_malloc(size, alignment); #elif __APPLE__ // On Mac OS X, both the heap and the stack are guaranteed 16-byte aligned so // they work natively with SSE types with no further work. CHECK_EQ(alignment, 16); return malloc(size); #elif defined(__FreeBSD__) || defined(__NetBSD__) void *result; if (posix_memalign(&result, alignment, size)) { // non-zero means allocation error // either no allocation or bad alignment value return NULL; } return result; #else // This is for Linux. return memalign(alignment, size); #endif } void aligned_free(void *ptr) { #ifdef _WIN32 _aligned_free(ptr); #else free(ptr); #endif } } // namespace libmv <commit_msg>Fix compilation on OSX after previous commit<commit_after>// Copyright (c) 2014 libmv authors. // // 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 "libmv/base/aligned_malloc.h" #include "libmv/logging/logging.h" #if !defined(__APPLE__) && !defined(__FreeBSD__) && !defined(__NetBSD__) // Needed for memalign on Linux and _aligned_alloc on Windows. # ifdef FREE_WINDOWS /* make sure _aligned_malloc is included */ # ifdef __MSVCRT_VERSION__ # undef __MSVCRT_VERSION__ # endif # define __MSVCRT_VERSION__ 0x0700 # endif // FREE_WINDOWS # include <malloc.h> #else // Apple's malloc is 16-byte aligned, and does not have malloc.h, so include // stdilb instead. # include <cstdlib> #endif namespace libmv { void *aligned_malloc(int size, int alignment) { #ifdef _WIN32 return _aligned_malloc(size, alignment); #elif __APPLE__ // On Mac OS X, both the heap and the stack are guaranteed 16-byte aligned so // they work natively with SSE types with no further work. CHECK_EQ(alignment, 16); return malloc(size); #elif defined(__FreeBSD__) || defined(__NetBSD__) void *result; if (posix_memalign(&result, alignment, size)) { // non-zero means allocation error // either no allocation or bad alignment value return NULL; } return result; #else // This is for Linux. return memalign(alignment, size); #endif } void aligned_free(void *ptr) { #ifdef _WIN32 _aligned_free(ptr); #else free(ptr); #endif } } // namespace libmv <|endoftext|>
<commit_before>#include "Camera.h" #include <opencv2/opencv.hpp> #include <thread> #define DOUBLE_BUFFERING Camera::Camera(const std::string &device): ThreadedClass("Camera") { cap = new cv::VideoCapture(device.c_str()); if (!cap->isOpened()) // if not success, exit program { throw std::runtime_error("Camera not found"); } Init(); } void Camera::Init() { paused = false; frameCount = (int)(cap->get(CV_CAP_PROP_FRAME_COUNT)); //cap->set(CV_CAP_PROP_FPS, 60); // cap->set(CV_CAP_PROP_GAIN, 0.5); // cap->set(CV_CAP_PROP_EXPOSURE, 2); // [[960 x 960 from (175, 60)]] // cap->set(CV_CAP_PROP_XI_MANUAL_WB, 1); #ifndef WIN32 // ! cap->set(CV_CAP_PROP_FRAME_WIDTH , 960); cap->set(CV_CAP_PROP_FRAME_HEIGHT , 960); cap->set(CV_CAP_PROP_XI_OFFSET_X, 160); cap->set(CV_CAP_PROP_XI_OFFSET_Y, 0); cap->set(CV_CAP_PROP_XI_OFFSET_Y, 0); #endif // cap->set(CV_CAP_PROP_EXPOSURE, 10000); // cap->set(CV_CAP_PROP_XI_OFFSET_Y, 0); *cap >> frame; frameSize = cv::Size(frame.size()); frame.copyTo(frame1); frame.copyTo(frame2); //auto _roi = roi; if (frame.cols < roi.br().y || frame.rows < roi.br().x) { auto _roi = roi; roi = cv::Rect(0, 0, frameSize.width, frameSize.height); std::cout << "Camera ROI [" << _roi << "] is bigger than frame size [" << frameSize << "], using full frame" << std::endl; std::cout << "Camera ROI [" << roi << "]" << std::endl; } frame1_roi = frame1(roi); frame2_roi = frame2(roi); // frameSize = cv::Size((int)cap->get(CV_CAP_PROP_FRAME_WIDTH), // Acquire input size // (int)cap->get(CV_CAP_PROP_FRAME_HEIGHT)); // maskedImage = cv::Mat(roi.height, roi.width, CV_8UC3, cv::Scalar(255, 0, 255)); // mask = cv::Mat(roi.height, roi.width, CV_8U, cv::Scalar::all(0)); // int radius = roi.height / 2; // cv::circle(mask, cv::Point(radius, radius), radius, cv::Scalar(255, 255, 255), -1, 8, 0); if (frameCount == 1) { // image #ifndef VIRTUAL_FLIP cv::flip(frame, frame, 1); #endif return; } /* cap->set(CV_CAP_PROP_FRAME_WIDTH, 1280); cap->set(CV_CAP_PROP_FRAME_HEIGHT, 720); */ /* https://github.com/jaantti/Firestarter/blob/master/2014/run.sh cap->set(CV_CAP_PROP_EXPOSURE, -5); cap->set(CV_CAP_PROP_BRIGHTNESS, 0); cap->set(CV_CAP_PROP_HUE, 0); cap->set(CV_CAP_PROP_SATURATION, 80); cap->set(CV_CAP_PROP_CONTRAST, 5); cap->set(CV_CAP_PROP_RECTIFICATION, 1);*/ #ifdef DOUBLE_BUFFERING Start(); #endif } Camera::Camera(int device) { cap = new cv::VideoCapture(device); if (!cap->isOpened()) // if not success, exit program { throw std::runtime_error("Camera is missing"); } Init(); } cv::Mat &Camera::GetLastFrame(bool bFullFrame){ return *m_pFrame; } cv::Mat &Camera::Capture(bool bFullFrame) { if (frameCount == 1) { // image frame.copyTo(frame1); // return clean copy //return frame1_roi; } else { #ifndef DOUBLE_BUFFERING if (cap->isOpened()){ *cap >> *m_pFrame; #ifndef VIRTUAL_FLIP cv::flip(*m_pFrame, *m_pFrame, 1); #endif } #else if (bCaptureNextFrame) { // std::cout << "Requesting too fast, next frame not ready!" << std::endl; while (bCaptureNextFrame && !stop_thread){ std::this_thread::sleep_for(std::chrono::milliseconds(1)); } } #endif } if (frames > 4) { double t2 = (double)cv::getTickCount(); double dt = (t2 - time) / cv::getTickFrequency(); fps = frames / dt; time = t2; frames = 0; } else { frames++; } bCaptureNextFrame = true; return *m_pFrame; /* m_pFrame->copyTo(maskedImage, mask); return maskedImage;*/ } const cv::Mat &Camera::CaptureHSV() { cvtColor(frame, buffer, cv::COLOR_BGR2HSV); //Convert the captured frame from BGR to HSV return buffer; } void Camera::Run(){ while (!stop_thread) { if (!bCaptureNextFrame || paused) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); continue; } cv::Mat &nextFrame = bCaptureFrame1 ? frame1 : frame2; cv::Mat &nextRoi = bCaptureFrame1 ? frame1_roi : frame2_roi; if (cap->isOpened()) { *cap >> nextFrame; #ifndef VIRTUAL_FLIP cv::flip(nextFrame, nextFrame, 1); #endif } else { bCaptureNextFrame = false; } if (frameCount >0 && cap->get(CV_CAP_PROP_POS_FRAMES) >= frameCount){ //restartVideo cap->set(CV_CAP_PROP_POS_FRAMES, 0); continue; } if (nextFrame.size().height == 0) { cap->set(CV_CAP_PROP_POS_FRAMES, 0); bCaptureNextFrame = true; std::cout << "Invalid frame captured " << frame1.size() << std::endl; continue; } //maskimine koos pildi viksemaks likamisega //frame_roi = nextFrame(cv::Rect(175, 60, frameSize.width, frameSize.height)); m_pFrame = &nextRoi; // without mask bCaptureFrame1 = !bCaptureFrame1; bCaptureNextFrame = false; } }<commit_msg>auto white balance off<commit_after>#include "Camera.h" #include <opencv2/opencv.hpp> #include <thread> #define DOUBLE_BUFFERING Camera::Camera(const std::string &device): ThreadedClass("Camera") { cap = new cv::VideoCapture(device.c_str()); if (!cap->isOpened()) // if not success, exit program { throw std::runtime_error("Camera not found"); } Init(); } void Camera::Init() { paused = false; frameCount = (int)(cap->get(CV_CAP_PROP_FRAME_COUNT)); //cap->set(CV_CAP_PROP_FPS, 60); // cap->set(CV_CAP_PROP_GAIN, 0.5); // cap->set(CV_CAP_PROP_EXPOSURE, 2); // [[960 x 960 from (175, 60)]] #ifndef WIN32 // ! cap->set(CV_CAP_PROP_FRAME_WIDTH , 960); cap->set(CV_CAP_PROP_FRAME_HEIGHT , 960); cap->set(CV_CAP_PROP_XI_OFFSET_X, 160); cap->set(CV_CAP_PROP_XI_OFFSET_Y, 0); cap->set(CV_CAP_PROP_XI_OFFSET_Y, 0); cap->set(CV_CAP_PROP_XI_AUTO_WB, 0); #endif // cap->set(CV_CAP_PROP_EXPOSURE, 10000); // cap->set(CV_CAP_PROP_XI_OFFSET_Y, 0); *cap >> frame; frameSize = cv::Size(frame.size()); frame.copyTo(frame1); frame.copyTo(frame2); //auto _roi = roi; if (frame.cols < roi.br().y || frame.rows < roi.br().x) { auto _roi = roi; roi = cv::Rect(0, 0, frameSize.width, frameSize.height); std::cout << "Camera ROI [" << _roi << "] is bigger than frame size [" << frameSize << "], using full frame" << std::endl; std::cout << "Camera ROI [" << roi << "]" << std::endl; } frame1_roi = frame1(roi); frame2_roi = frame2(roi); // frameSize = cv::Size((int)cap->get(CV_CAP_PROP_FRAME_WIDTH), // Acquire input size // (int)cap->get(CV_CAP_PROP_FRAME_HEIGHT)); // maskedImage = cv::Mat(roi.height, roi.width, CV_8UC3, cv::Scalar(255, 0, 255)); // mask = cv::Mat(roi.height, roi.width, CV_8U, cv::Scalar::all(0)); // int radius = roi.height / 2; // cv::circle(mask, cv::Point(radius, radius), radius, cv::Scalar(255, 255, 255), -1, 8, 0); if (frameCount == 1) { // image #ifndef VIRTUAL_FLIP cv::flip(frame, frame, 1); #endif return; } /* cap->set(CV_CAP_PROP_FRAME_WIDTH, 1280); cap->set(CV_CAP_PROP_FRAME_HEIGHT, 720); */ /* https://github.com/jaantti/Firestarter/blob/master/2014/run.sh cap->set(CV_CAP_PROP_EXPOSURE, -5); cap->set(CV_CAP_PROP_BRIGHTNESS, 0); cap->set(CV_CAP_PROP_HUE, 0); cap->set(CV_CAP_PROP_SATURATION, 80); cap->set(CV_CAP_PROP_CONTRAST, 5); cap->set(CV_CAP_PROP_RECTIFICATION, 1);*/ #ifdef DOUBLE_BUFFERING Start(); #endif } Camera::Camera(int device) { cap = new cv::VideoCapture(device); if (!cap->isOpened()) // if not success, exit program { throw std::runtime_error("Camera is missing"); } Init(); } cv::Mat &Camera::GetLastFrame(bool bFullFrame){ return *m_pFrame; } cv::Mat &Camera::Capture(bool bFullFrame) { if (frameCount == 1) { // image frame.copyTo(frame1); // return clean copy //return frame1_roi; } else { #ifndef DOUBLE_BUFFERING if (cap->isOpened()){ *cap >> *m_pFrame; #ifndef VIRTUAL_FLIP cv::flip(*m_pFrame, *m_pFrame, 1); #endif } #else if (bCaptureNextFrame) { // std::cout << "Requesting too fast, next frame not ready!" << std::endl; while (bCaptureNextFrame && !stop_thread){ std::this_thread::sleep_for(std::chrono::milliseconds(1)); } } #endif } if (frames > 4) { double t2 = (double)cv::getTickCount(); double dt = (t2 - time) / cv::getTickFrequency(); fps = frames / dt; time = t2; frames = 0; } else { frames++; } bCaptureNextFrame = true; return *m_pFrame; /* m_pFrame->copyTo(maskedImage, mask); return maskedImage;*/ } const cv::Mat &Camera::CaptureHSV() { cvtColor(frame, buffer, cv::COLOR_BGR2HSV); //Convert the captured frame from BGR to HSV return buffer; } void Camera::Run(){ while (!stop_thread) { if (!bCaptureNextFrame || paused) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); continue; } cv::Mat &nextFrame = bCaptureFrame1 ? frame1 : frame2; cv::Mat &nextRoi = bCaptureFrame1 ? frame1_roi : frame2_roi; if (cap->isOpened()) { *cap >> nextFrame; #ifndef VIRTUAL_FLIP cv::flip(nextFrame, nextFrame, 1); #endif } else { bCaptureNextFrame = false; } if (frameCount >0 && cap->get(CV_CAP_PROP_POS_FRAMES) >= frameCount){ //restartVideo cap->set(CV_CAP_PROP_POS_FRAMES, 0); continue; } if (nextFrame.size().height == 0) { cap->set(CV_CAP_PROP_POS_FRAMES, 0); bCaptureNextFrame = true; std::cout << "Invalid frame captured " << frame1.size() << std::endl; continue; } //maskimine koos pildi viksemaks likamisega //frame_roi = nextFrame(cv::Rect(175, 60, frameSize.width, frameSize.height)); m_pFrame = &nextRoi; // without mask bCaptureFrame1 = !bCaptureFrame1; bCaptureNextFrame = false; } }<|endoftext|>
<commit_before>#include "pattern.h" #include <OpenEXR/ImathMatrix.h> namespace lightfields { Pattern::Pattern() : m_lensPitch(1.0), m_pixelPitch(1.0), m_rotation(0.0), m_scaleFactor(1.0, 1.0), m_sensorResolution(100, 100) { } Pattern::Pattern(double lensPitch, double pixelPitch, double rotation, Imath::V2d scaleFactor, Imath::V3d sensorOffset, Imath::V2i sensorResolution) : m_lensPitch(lensPitch), m_pixelPitch(pixelPitch), m_rotation(rotation), m_scaleFactor(scaleFactor), m_sensorOffset(sensorOffset), m_sensorResolution(sensorResolution) { } bool Pattern::operator == (const Pattern& f) const { return m_lensPitch == f.m_lensPitch && m_pixelPitch == f.m_pixelPitch && m_rotation == f.m_rotation && m_scaleFactor == f.m_scaleFactor && m_sensorOffset == f.m_sensorOffset && m_sensorResolution == f.m_sensorResolution; } bool Pattern::operator != (const Pattern& f) const { return m_lensPitch != f.m_lensPitch || m_pixelPitch != f.m_pixelPitch || m_rotation != f.m_rotation || m_scaleFactor != f.m_scaleFactor || m_sensorOffset != f.m_sensorOffset || m_sensorResolution != f.m_sensorResolution; } Imath::V4d Pattern::sample(const Imath::V2i& pixelPos) const { Imath::V4d result; const double cs = cos(m_rotation); const double sn = sin(m_rotation); Imath::M33d transform; transform.makeIdentity(); const double scale = m_pixelPitch / m_lensPitch; transform[0][0] = scale/m_scaleFactor[0] * cs; transform[0][1] = scale/m_scaleFactor[1] * -sn / sqrt(3.0/4.0); transform[1][0] = scale/m_scaleFactor[0] * sn; transform[1][1] = scale/m_scaleFactor[1] * cs / sqrt(3.0/4.0); transform[2][0] = m_sensorOffset[0] / m_pixelPitch * (scale/m_scaleFactor[0]); transform[2][1] = m_sensorOffset[1] / m_pixelPitch * (scale/m_scaleFactor[1] / sqrt(3.0/4.0)); Imath::V3d pos(pixelPos[0], pixelPos[1], 1.0); pos = pos * transform; if(((int)round(pos[1] + 100.0)) % 2 == 1) pos[0] += 0.5; result[2] = (pos[0] + 100.0 - round(pos[0] + 100.0)); result[3] = (pos[1] + 100.0 - round(pos[1] + 100.0)); result[0] = (double)pixelPos[0] - result[2] * m_lensPitch / m_pixelPitch * m_scaleFactor[0]; result[1] = (double)pixelPos[1] - result[3] * m_lensPitch * sqrt(3.0/4.0) / m_pixelPitch * m_scaleFactor[1]; result[2] *= 2.0; result[3] *= 2.0; return result; } const Imath::V2i& Pattern::sensorResolution() const { return m_sensorResolution; } std::ostream& operator << (std::ostream& out, const Pattern& f) { out << "(lightfields pattern)"; return out; } } <commit_msg>Replaced round() with floor() in lightfield patter computation<commit_after>#include "pattern.h" #include <OpenEXR/ImathMatrix.h> namespace lightfields { Pattern::Pattern() : m_lensPitch(1.0), m_pixelPitch(1.0), m_rotation(0.0), m_scaleFactor(1.0, 1.0), m_sensorResolution(100, 100) { } Pattern::Pattern(double lensPitch, double pixelPitch, double rotation, Imath::V2d scaleFactor, Imath::V3d sensorOffset, Imath::V2i sensorResolution) : m_lensPitch(lensPitch), m_pixelPitch(pixelPitch), m_rotation(rotation), m_scaleFactor(scaleFactor), m_sensorOffset(sensorOffset), m_sensorResolution(sensorResolution) { } bool Pattern::operator == (const Pattern& f) const { return m_lensPitch == f.m_lensPitch && m_pixelPitch == f.m_pixelPitch && m_rotation == f.m_rotation && m_scaleFactor == f.m_scaleFactor && m_sensorOffset == f.m_sensorOffset && m_sensorResolution == f.m_sensorResolution; } bool Pattern::operator != (const Pattern& f) const { return m_lensPitch != f.m_lensPitch || m_pixelPitch != f.m_pixelPitch || m_rotation != f.m_rotation || m_scaleFactor != f.m_scaleFactor || m_sensorOffset != f.m_sensorOffset || m_sensorResolution != f.m_sensorResolution; } Imath::V4d Pattern::sample(const Imath::V2i& pixelPos) const { Imath::V4d result; const double cs = cos(m_rotation); const double sn = sin(m_rotation); Imath::M33d transform; transform.makeIdentity(); const double scale_x = m_pixelPitch / m_lensPitch / m_scaleFactor[0]; const double scale_y = m_pixelPitch / m_lensPitch / m_scaleFactor[1] / sqrt(3.0/4.0); transform[0][0] = scale_x * cs; transform[0][1] = scale_y * -sn; transform[1][0] = scale_x * sn; transform[1][1] = scale_y * cs; transform[2][0] = scale_x * m_sensorOffset[0] / m_pixelPitch; transform[2][1] = scale_y * m_sensorOffset[1] / m_pixelPitch; Imath::V3d pos(pixelPos[0], pixelPos[1], 1.0); pos = pos * transform; if(((int)floor(pos[1] - 0.5)) % 2 == 0) pos[0] -= 0.5; result[2] = (pos[0] - floor(pos[0] + 0.5)); result[3] = (pos[1] - floor(pos[1] + 0.5)); result[0] = (double)pixelPos[0] - result[2] / scale_x; result[1] = (double)pixelPos[1] - result[3] / scale_y; result[2] *= 2.0; result[3] *= 2.0; return result; } const Imath::V2i& Pattern::sensorResolution() const { return m_sensorResolution; } std::ostream& operator << (std::ostream& out, const Pattern& f) { out << "(lightfields pattern)"; return out; } } <|endoftext|>
<commit_before> /* * Copyright 2009-2019 The VOTCA Development Team (http://www.votca.org) * * 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 <iostream> #include <votca/xtp/matrixfreeoperator.h> namespace votca { namespace xtp { Eigen::VectorXd MatrixFreeOperator::diagonal() const { Eigen::VectorXd D = Eigen::VectorXd::Zero(_size); Eigen::RowVectorXd row_data; #pragma omp parallel for for (int i = 0; i < _size; i++) { row_data = this->row(i); D(i) = row_data(i); } return D; } // get the full matrix if we have to Eigen::MatrixXd MatrixFreeOperator::get_full_matrix() const { Eigen::MatrixXd matrix = Eigen::MatrixXd::Zero(_size, _size); #pragma omp parallel for for (int i = 0; i < _size; i++) { matrix.row(i) = this->row(i); } return matrix; } // get the size int MatrixFreeOperator::size() const { return this->_size; } // set the size void MatrixFreeOperator::set_size(int size) { this->_size = size; } } // namespace xtp } // namespace votca <commit_msg>forgot to fix race condition<commit_after> /* * Copyright 2009-2019 The VOTCA Development Team (http://www.votca.org) * * 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 <iostream> #include <votca/xtp/matrixfreeoperator.h> namespace votca { namespace xtp { Eigen::VectorXd MatrixFreeOperator::diagonal() const { Eigen::VectorXd D = Eigen::VectorXd::Zero(_size); #pragma omp parallel for for (int i = 0; i < _size; i++) { Eigen::RowVectorXd row_data = this->row(i); D(i) = row_data(i); } return D; } // get the full matrix if we have to Eigen::MatrixXd MatrixFreeOperator::get_full_matrix() const { Eigen::MatrixXd matrix = Eigen::MatrixXd::Zero(_size, _size); #pragma omp parallel for for (int i = 0; i < _size; i++) { matrix.row(i) = this->row(i); } return matrix; } // get the size int MatrixFreeOperator::size() const { return this->_size; } // set the size void MatrixFreeOperator::set_size(int size) { this->_size = size; } } // namespace xtp } // namespace votca <|endoftext|>
<commit_before>#include "FlagStatus.hpp" #include "RemapUtil.hpp" #include "Config.hpp" namespace org_pqrs_KeyRemap4MacBook { namespace FlagStatus { Item item[ModifierFlag::listsize]; void Item::initialize(ModifierFlag::ModifierFlag _flag) { flag = _flag; key = RemapUtil::getModifierKeyCode(_flag); count = 0; temporary_count = 0; lock_count = 0; } void Item::set(const RemapParams &remapParams) { temporary_count = 0; if ((remapParams.params)->eventType != KeyEvent::MODIFY) return; if (remapParams.ex_origKey != static_cast<unsigned int>(key)) return; if (RemapUtil::isModifierOn(remapParams, flag)) { increase(); } else { decrease(); } } // ---------------------------------------------------------------------- void initialize(void) { for (int i = 0; i < ModifierFlag::listsize; ++i) { item[i].initialize(ModifierFlag::list[i]); } } void set(const RemapParams &remapParams) { for (int i = 0; i < ModifierFlag::listsize; ++i) { item[i].set(remapParams); } } void reset(void) { if (config.debug_devel) { printf("KeyRemap4MacBook FlagStatus::reset\n"); } for (int i = 0; i < ModifierFlag::listsize; ++i) { item[i].reset(); } } void reset_lock(void) { if (config.debug_devel) { printf("KeyRemap4MacBook FlagStatus::reset_lock\n"); } for (int i = 0; i < ModifierFlag::listsize; ++i) { item[i].reset_lock(); } } unsigned int makeFlags(unsigned int keyCode) { unsigned int flags = 0; for (int i = 0; i < ModifierFlag::listsize; ++i) { flags |= item[i].makeFlag(); } if (keyCode == KeyCode::KEYPAD_0 || keyCode == KeyCode::KEYPAD_1 || keyCode == KeyCode::KEYPAD_2 || keyCode == KeyCode::KEYPAD_3 || keyCode == KeyCode::KEYPAD_4 || keyCode == KeyCode::KEYPAD_5 || keyCode == KeyCode::KEYPAD_6 || keyCode == KeyCode::KEYPAD_7 || keyCode == KeyCode::KEYPAD_8 || keyCode == KeyCode::KEYPAD_9 || keyCode == KeyCode::KEYPAD_DOT || keyCode == KeyCode::KEYPAD_MULTIPLY || keyCode == KeyCode::KEYPAD_PLUS || keyCode == KeyCode::KEYPAD_CLEAR || keyCode == KeyCode::KEYPAD_SLASH || keyCode == KeyCode::KEYPAD_MINUS || keyCode == KeyCode::KEYPAD_EQUAL || keyCode == KeyCode::KEYPAD_COMMA) { flags |= ModifierFlag::KEYPAD; } if (keyCode == KeyCode::CURSOR_UP || keyCode == KeyCode::CURSOR_DOWN || keyCode == KeyCode::CURSOR_LEFT || keyCode == KeyCode::CURSOR_RIGHT) { flags |= ModifierFlag::CURSOR; } return flags; } unsigned int makeFlags(const RemapParams &remapParams) { return makeFlags((remapParams.params)->key); } Item * getFlagStatus(ModifierFlag::ModifierFlag flag) { for (int i = 0; i < ModifierFlag::listsize; ++i) { if (flag == ModifierFlag::list[i]) return item + i; } return NULL; } // ---------------------------------------- bool isHeldDown(ModifierFlag::ModifierFlag flag) { Item *p = getFlagStatus(flag); if (! p) return false; return p->isHeldDown(); } void increase(ModifierFlag::ModifierFlag flag) { Item *p = getFlagStatus(flag); if (! p) return; return p->increase(); } void decrease(ModifierFlag::ModifierFlag flag) { Item *p = getFlagStatus(flag); if (! p) return; return p->decrease(); } void temporary_increase(ModifierFlag::ModifierFlag flag) { Item *p = getFlagStatus(flag); if (! p) return; return p->temporary_increase(); } void temporary_decrease(ModifierFlag::ModifierFlag flag) { Item *p = getFlagStatus(flag); if (! p) return; return p->temporary_decrease(); } void lock_increase(ModifierFlag::ModifierFlag flag) { Item *p = getFlagStatus(flag); if (! p) return; return p->lock_increase(); } void lock_decrease(ModifierFlag::ModifierFlag flag) { Item *p = getFlagStatus(flag); if (! p) return; return p->lock_decrease(); } } } <commit_msg>add debuginfo @ src/core/kext<commit_after>#include "FlagStatus.hpp" #include "RemapUtil.hpp" #include "Config.hpp" namespace org_pqrs_KeyRemap4MacBook { namespace FlagStatus { Item item[ModifierFlag::listsize]; void Item::initialize(ModifierFlag::ModifierFlag _flag) { flag = _flag; key = RemapUtil::getModifierKeyCode(_flag); count = 0; temporary_count = 0; lock_count = 0; } void Item::set(const RemapParams &remapParams) { temporary_count = 0; if ((remapParams.params)->eventType != KeyEvent::MODIFY) return; if (remapParams.ex_origKey != static_cast<unsigned int>(key)) return; if (RemapUtil::isModifierOn(remapParams, flag)) { increase(); } else { decrease(); } } // ---------------------------------------------------------------------- void initialize(void) { for (int i = 0; i < ModifierFlag::listsize; ++i) { item[i].initialize(ModifierFlag::list[i]); } } void set(const RemapParams &remapParams) { for (int i = 0; i < ModifierFlag::listsize; ++i) { item[i].set(remapParams); } } void reset(void) { if (config.debug_devel) { printf("KeyRemap4MacBook FlagStatus::reset\n"); } for (int i = 0; i < ModifierFlag::listsize; ++i) { item[i].reset(); } } void reset_lock(void) { if (config.debug_devel) { printf("KeyRemap4MacBook FlagStatus::reset_lock\n"); } for (int i = 0; i < ModifierFlag::listsize; ++i) { item[i].reset_lock(); } } unsigned int makeFlags(unsigned int keyCode) { unsigned int flags = 0; for (int i = 0; i < ModifierFlag::listsize; ++i) { flags |= item[i].makeFlag(); } if (keyCode == KeyCode::KEYPAD_0 || keyCode == KeyCode::KEYPAD_1 || keyCode == KeyCode::KEYPAD_2 || keyCode == KeyCode::KEYPAD_3 || keyCode == KeyCode::KEYPAD_4 || keyCode == KeyCode::KEYPAD_5 || keyCode == KeyCode::KEYPAD_6 || keyCode == KeyCode::KEYPAD_7 || keyCode == KeyCode::KEYPAD_8 || keyCode == KeyCode::KEYPAD_9 || keyCode == KeyCode::KEYPAD_DOT || keyCode == KeyCode::KEYPAD_MULTIPLY || keyCode == KeyCode::KEYPAD_PLUS || keyCode == KeyCode::KEYPAD_CLEAR || keyCode == KeyCode::KEYPAD_SLASH || keyCode == KeyCode::KEYPAD_MINUS || keyCode == KeyCode::KEYPAD_EQUAL || keyCode == KeyCode::KEYPAD_COMMA) { flags |= ModifierFlag::KEYPAD; } if (keyCode == KeyCode::CURSOR_UP || keyCode == KeyCode::CURSOR_DOWN || keyCode == KeyCode::CURSOR_LEFT || keyCode == KeyCode::CURSOR_RIGHT) { flags |= ModifierFlag::CURSOR; } if (config.debug_devel) { printf("KeyRemap4MacBook -INFO- FlagStatus::makeFlags = 0x%x\n", flags); } return flags; } unsigned int makeFlags(const RemapParams &remapParams) { return makeFlags((remapParams.params)->key); } Item * getFlagStatus(ModifierFlag::ModifierFlag flag) { for (int i = 0; i < ModifierFlag::listsize; ++i) { if (flag == ModifierFlag::list[i]) return item + i; } return NULL; } // ---------------------------------------- bool isHeldDown(ModifierFlag::ModifierFlag flag) { Item *p = getFlagStatus(flag); if (! p) return false; return p->isHeldDown(); } void increase(ModifierFlag::ModifierFlag flag) { Item *p = getFlagStatus(flag); if (! p) return; return p->increase(); } void decrease(ModifierFlag::ModifierFlag flag) { Item *p = getFlagStatus(flag); if (! p) return; return p->decrease(); } void temporary_increase(ModifierFlag::ModifierFlag flag) { Item *p = getFlagStatus(flag); if (! p) return; return p->temporary_increase(); } void temporary_decrease(ModifierFlag::ModifierFlag flag) { Item *p = getFlagStatus(flag); if (! p) return; return p->temporary_decrease(); } void lock_increase(ModifierFlag::ModifierFlag flag) { Item *p = getFlagStatus(flag); if (! p) return; return p->lock_increase(); } void lock_decrease(ModifierFlag::ModifierFlag flag) { Item *p = getFlagStatus(flag); if (! p) return; return p->lock_decrease(); } } } <|endoftext|>
<commit_before>/* * The MIT License (MIT) * * Copyright (c) 2015 Microsoft Corporation * * -=- Robust Distributed System Nucleus (rDSN) -=- * * 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. */ /* * Description: * What is this file about? * * Revision history: * xxxx-xx-xx, author, first version * xxxx-xx-xx, author, fix bug about xxx */ /************************************************************ * hpc_logger (High-Performance Computing logger) * * Editor: Chang Lou (v-chlou@microsoft.com) * * * The structure of the logger is like the following graph. * * For each thread: * ------------------------- ------------------------- * | new single log | -> | | * ------------------------- | --------------------- | * | | * | --------------------- | * | | * | --------------------- | * | | * | --------------------- | * ... * | --------------------- | * | | * ------------------------- * buffer (per thread) * | * | when the buffer is full, * | push the buffer and buffer size into _write_list, * | malloc a new buffer for the thread to use * V * ========================================================================================================== _write_list_lock * * ------------------------------------------------------------- * {buf1, buf1_size} | {buf2, buf2_size} | {buf3, buf3_size} | ... * ------------------------------------------------------------- * _write_list * * ========================================================================================================== _write_list_lock * | * | when the _write_list is not empty, * | daemon thread is notified by _write_list_cond * V * * Daemon thread * * || * ===========> log.x.txt * * Some other facts: * 1. The log file size is restricted, when max size is achieved, a new log file will be established. * 2. When exiting, the logger flushes, in other words, print out the retained log info in buffers of each thread and buffers in the buffer list. ************************************************************/ # include "hpc_logger.h" # include <dsn/internal/singleton_store.h> # include <dsn/cpp/utils.h> # include <dsn/internal/command.h> # include <cstdlib> # include <sstream> # include <fstream> # include <iostream> #define MAX_FILE_SIZE 30 * 1024 * 1024 namespace dsn { namespace tools { typedef struct __hpc_log_info__ { uint32_t magic; char* buffer; char* next_write_ptr; } hpc_log_tls_info; //log ptr for each thread static __thread hpc_log_tls_info s_hpc_log_tls_info; //store log ptr for each thread typedef ::dsn::utils::safe_singleton_store<int, hpc_log_tls_info*> hpc_log_manager; //daemon thread void hpc_logger::log_thread() { std::vector<buffer_info> saved_list; while (!_stop_thread) { _write_list_lock.lock(); _write_list_cond.wait(_write_list_lock, [=]{ return _stop_thread || _write_list.size() > 0; }); saved_list = std::move(_write_list); _write_list.clear(); _write_list_lock.unlock(); write_buffer_list(saved_list); } _write_list_lock.lock(); saved_list = _write_list; _write_list.clear(); _write_list_lock.unlock(); write_buffer_list(saved_list); } hpc_logger::hpc_logger(const char* log_dir) : logging_provider(log_dir), _stop_thread(false) { _log_dir = std::string(log_dir); _per_thread_buffer_bytes = config()->get_value<int>( "tools.hpc_logger", "per_thread_buffer_bytes", 64 * 1024, // 64 KB by default "buffer size for per-thread logging" ); _start_index = 0; _index = 1; _current_log_file_bytes = 0; // check existing log files and decide start_index std::vector<std::string> sub_list; if (!dsn::utils::filesystem::get_subfiles(_log_dir, sub_list, false)) { dassert(false, "Fail to get subfiles in %s.", _log_dir.c_str()); } for (auto& fpath : sub_list) { auto&& name = dsn::utils::filesystem::get_file_name(fpath); if (name.length() <= 5 || name.substr(0, 4) != "log.") continue; int index; if (1 != sscanf(name.c_str(), "log.%d.txt", &index) || index < 1) continue; if (index > _index) _index = index; if (_start_index == 0 || index < _start_index) _start_index = index; } sub_list.clear(); if (_start_index == 0) _start_index = _index; else _index++; _current_log = nullptr; create_log_file(); _log_thread = std::thread(&hpc_logger::log_thread, this); } void hpc_logger::create_log_file() { std::stringstream log; log << _log_dir << "/log." << _index++ << ".txt"; _current_log = new std::ofstream(log.str().c_str(), std::ofstream::out | std::ofstream::app | std::ofstream::binary); _current_log_file_bytes = 0; // TODO: move gc out of criticial path while (_index - _start_index > 20) { std::stringstream str2; str2 << "log." << _start_index++ << ".txt"; auto dp = utils::filesystem::path_combine(_log_dir, str2.str()); if (::remove(dp.c_str()) != 0) { printf("Failed to remove garbage log file %s\n", dp.c_str()); _start_index--; break; } } } hpc_logger::~hpc_logger(void) { if (!_stop_thread) { _stop_thread = true; _write_list_cond.notify_one(); _log_thread.join(); } _current_log->close(); delete _current_log; } void hpc_logger::flush() { //dangerous operation //print retained log in the buffers of threads //this is only used at process exit flush_all_buffers_at_exit(); _stop_thread = true; _write_list_cond.notify_one(); _log_thread.join(); } void hpc_logger::flush_all_buffers_at_exit() { std::vector<int> threads; hpc_log_manager::instance().get_all_keys(threads); for (auto& tid : threads) { __hpc_log_info__* log; if (!hpc_log_manager::instance().get(tid, log)) continue; buffer_push(log->buffer, static_cast<int>(log->next_write_ptr - log->buffer)); hpc_log_manager::instance().remove(tid); } } void hpc_logger::dsn_logv(const char *file, const char *function, const int line, dsn_log_level_t log_level, const char* title, const char *fmt, va_list args ) { if (s_hpc_log_tls_info.magic != 0xdeadbeef) { s_hpc_log_tls_info.buffer = (char*)malloc(_per_thread_buffer_bytes); s_hpc_log_tls_info.next_write_ptr = s_hpc_log_tls_info.buffer; hpc_log_manager::instance().put(::dsn::utils::get_current_tid(), &s_hpc_log_tls_info); s_hpc_log_tls_info.magic = 0xdeadbeef; } // get enough write space >= 1K if (s_hpc_log_tls_info.next_write_ptr + 1024 > s_hpc_log_tls_info.buffer + _per_thread_buffer_bytes) { _write_list_lock.lock(); buffer_push(s_hpc_log_tls_info.buffer, static_cast<int>(s_hpc_log_tls_info.next_write_ptr - s_hpc_log_tls_info.buffer)); _write_list_lock.unlock(); _write_list_cond.notify_one(); s_hpc_log_tls_info.buffer = (char*)malloc(_per_thread_buffer_bytes); s_hpc_log_tls_info.next_write_ptr = s_hpc_log_tls_info.buffer; } char* ptr = s_hpc_log_tls_info.next_write_ptr; char* ptr0 = ptr; // remember it size_t capacity = static_cast<size_t>(s_hpc_log_tls_info.buffer + _per_thread_buffer_bytes - ptr); // print verbose log header uint64_t ts = 0; int tid = ::dsn::utils::get_current_tid(); if (::dsn::tools::is_engine_ready()) ts = dsn_now_ns(); char str[24]; ::dsn::utils::time_ms_to_string(ts / 1000000, str); auto wn = snprintf_p(ptr, capacity, "%s (%" PRIu64 " %04x) ", str, ts, tid); ptr += wn; capacity -= wn; auto t = task::get_current_task_id(); if (t) { if (nullptr != task::get_current_worker2()) { wn = snprintf_p(ptr, capacity, "%6s.%7s%u.%016llx: ", task::get_current_node_name(), task::get_current_worker2()->pool_spec().name.c_str(), task::get_current_worker2()->index(), static_cast<long long unsigned int>(t) ); } else { wn = snprintf_p(ptr, capacity, "%6s.%7s.%05d.%016llx: ", task::get_current_node_name(), "io-thrd", tid, static_cast<long long unsigned int>(t) ); } } else { wn = snprintf_p(ptr, capacity, "%6s.%7s.%05d: ", task::get_current_node_name(), "io-thrd", tid ); } ptr += wn; capacity -= wn; // print body wn = std::vsnprintf(ptr, capacity - 1, fmt, args); if (wn < 0) { wn = snprintf_p(ptr, capacity, "-- log entry is too long ---"); } *(ptr + wn) = '\n'; ptr += (wn + 1); capacity -= (wn + 1); // set next write ptr s_hpc_log_tls_info.next_write_ptr = ptr; // dump critical logs on screen if (log_level >= LOG_LEVEL_WARNING) { std::cout.write(ptr0, ptr - ptr0); } } //log operation void hpc_logger::buffer_push(char* buffer, int size) { _write_list.emplace_back(buffer, size); } void hpc_logger::write_buffer_list(std::vector<buffer_info>& llist) { for (auto& new_buffer_info : llist) { if (_current_log_file_bytes + new_buffer_info.buffer_size >= MAX_FILE_SIZE) { _current_log->close(); delete _current_log; _current_log = nullptr; create_log_file(); } if (new_buffer_info.buffer_size > 0) { _current_log->write(new_buffer_info.buffer, new_buffer_info.buffer_size); _current_log_file_bytes += new_buffer_info.buffer_size; } free(new_buffer_info.buffer); } llist.clear(); } } } <commit_msg>fix hpc logger for reserving one bytes for end '\n' char<commit_after>/* * The MIT License (MIT) * * Copyright (c) 2015 Microsoft Corporation * * -=- Robust Distributed System Nucleus (rDSN) -=- * * 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. */ /* * Description: * What is this file about? * * Revision history: * xxxx-xx-xx, author, first version * xxxx-xx-xx, author, fix bug about xxx */ /************************************************************ * hpc_logger (High-Performance Computing logger) * * Editor: Chang Lou (v-chlou@microsoft.com) * * * The structure of the logger is like the following graph. * * For each thread: * ------------------------- ------------------------- * | new single log | -> | | * ------------------------- | --------------------- | * | | * | --------------------- | * | | * | --------------------- | * | | * | --------------------- | * ... * | --------------------- | * | | * ------------------------- * buffer (per thread) * | * | when the buffer is full, * | push the buffer and buffer size into _write_list, * | malloc a new buffer for the thread to use * V * ========================================================================================================== _write_list_lock * * ------------------------------------------------------------- * {buf1, buf1_size} | {buf2, buf2_size} | {buf3, buf3_size} | ... * ------------------------------------------------------------- * _write_list * * ========================================================================================================== _write_list_lock * | * | when the _write_list is not empty, * | daemon thread is notified by _write_list_cond * V * * Daemon thread * * || * ===========> log.x.txt * * Some other facts: * 1. The log file size is restricted, when max size is achieved, a new log file will be established. * 2. When exiting, the logger flushes, in other words, print out the retained log info in buffers of each thread and buffers in the buffer list. ************************************************************/ # include "hpc_logger.h" # include <dsn/internal/singleton_store.h> # include <dsn/cpp/utils.h> # include <dsn/internal/command.h> # include <cstdlib> # include <sstream> # include <fstream> # include <iostream> #define MAX_FILE_SIZE 30 * 1024 * 1024 namespace dsn { namespace tools { typedef struct __hpc_log_info__ { uint32_t magic; char* buffer; char* next_write_ptr; } hpc_log_tls_info; //log ptr for each thread static __thread hpc_log_tls_info s_hpc_log_tls_info; //store log ptr for each thread typedef ::dsn::utils::safe_singleton_store<int, hpc_log_tls_info*> hpc_log_manager; //daemon thread void hpc_logger::log_thread() { std::vector<buffer_info> saved_list; while (!_stop_thread) { _write_list_lock.lock(); _write_list_cond.wait(_write_list_lock, [=]{ return _stop_thread || _write_list.size() > 0; }); saved_list = std::move(_write_list); _write_list.clear(); _write_list_lock.unlock(); write_buffer_list(saved_list); } _write_list_lock.lock(); saved_list = _write_list; _write_list.clear(); _write_list_lock.unlock(); write_buffer_list(saved_list); } hpc_logger::hpc_logger(const char* log_dir) : logging_provider(log_dir), _stop_thread(false) { _log_dir = std::string(log_dir); _per_thread_buffer_bytes = config()->get_value<int>( "tools.hpc_logger", "per_thread_buffer_bytes", 64 * 1024, // 64 KB by default "buffer size for per-thread logging" ); _start_index = 0; _index = 1; _current_log_file_bytes = 0; // check existing log files and decide start_index std::vector<std::string> sub_list; if (!dsn::utils::filesystem::get_subfiles(_log_dir, sub_list, false)) { dassert(false, "Fail to get subfiles in %s.", _log_dir.c_str()); } for (auto& fpath : sub_list) { auto&& name = dsn::utils::filesystem::get_file_name(fpath); if (name.length() <= 5 || name.substr(0, 4) != "log.") continue; int index; if (1 != sscanf(name.c_str(), "log.%d.txt", &index) || index < 1) continue; if (index > _index) _index = index; if (_start_index == 0 || index < _start_index) _start_index = index; } sub_list.clear(); if (_start_index == 0) _start_index = _index; else _index++; _current_log = nullptr; create_log_file(); _log_thread = std::thread(&hpc_logger::log_thread, this); } void hpc_logger::create_log_file() { std::stringstream log; log << _log_dir << "/log." << _index++ << ".txt"; _current_log = new std::ofstream(log.str().c_str(), std::ofstream::out | std::ofstream::app | std::ofstream::binary); _current_log_file_bytes = 0; // TODO: move gc out of criticial path while (_index - _start_index > 20) { std::stringstream str2; str2 << "log." << _start_index++ << ".txt"; auto dp = utils::filesystem::path_combine(_log_dir, str2.str()); if (::remove(dp.c_str()) != 0) { printf("Failed to remove garbage log file %s\n", dp.c_str()); _start_index--; break; } } } hpc_logger::~hpc_logger(void) { if (!_stop_thread) { _stop_thread = true; _write_list_cond.notify_one(); _log_thread.join(); } _current_log->close(); delete _current_log; } void hpc_logger::flush() { //dangerous operation //print retained log in the buffers of threads //this is only used at process exit flush_all_buffers_at_exit(); _stop_thread = true; _write_list_cond.notify_one(); _log_thread.join(); } void hpc_logger::flush_all_buffers_at_exit() { std::vector<int> threads; hpc_log_manager::instance().get_all_keys(threads); for (auto& tid : threads) { __hpc_log_info__* log; if (!hpc_log_manager::instance().get(tid, log)) continue; buffer_push(log->buffer, static_cast<int>(log->next_write_ptr - log->buffer)); hpc_log_manager::instance().remove(tid); } } void hpc_logger::dsn_logv(const char *file, const char *function, const int line, dsn_log_level_t log_level, const char* title, const char *fmt, va_list args ) { if (s_hpc_log_tls_info.magic != 0xdeadbeef) { s_hpc_log_tls_info.buffer = (char*)malloc(_per_thread_buffer_bytes); s_hpc_log_tls_info.next_write_ptr = s_hpc_log_tls_info.buffer; hpc_log_manager::instance().put(::dsn::utils::get_current_tid(), &s_hpc_log_tls_info); s_hpc_log_tls_info.magic = 0xdeadbeef; } // get enough write space >= 1K if (s_hpc_log_tls_info.next_write_ptr + 1024 > s_hpc_log_tls_info.buffer + _per_thread_buffer_bytes) { _write_list_lock.lock(); buffer_push(s_hpc_log_tls_info.buffer, static_cast<int>(s_hpc_log_tls_info.next_write_ptr - s_hpc_log_tls_info.buffer)); _write_list_lock.unlock(); _write_list_cond.notify_one(); s_hpc_log_tls_info.buffer = (char*)malloc(_per_thread_buffer_bytes); s_hpc_log_tls_info.next_write_ptr = s_hpc_log_tls_info.buffer; } char* ptr = s_hpc_log_tls_info.next_write_ptr; char* ptr0 = ptr; // remember it size_t capacity = static_cast<size_t>(s_hpc_log_tls_info.buffer + _per_thread_buffer_bytes - ptr); // print verbose log header uint64_t ts = 0; int tid = ::dsn::utils::get_current_tid(); if (::dsn::tools::is_engine_ready()) ts = dsn_now_ns(); char str[24]; ::dsn::utils::time_ms_to_string(ts / 1000000, str); auto wn = snprintf_p(ptr, capacity, "%s (%" PRIu64 " %04x) ", str, ts, tid); ptr += wn; capacity -= wn; auto t = task::get_current_task_id(); if (t) { if (nullptr != task::get_current_worker2()) { wn = snprintf_p(ptr, capacity, "%6s.%7s%u.%016llx: ", task::get_current_node_name(), task::get_current_worker2()->pool_spec().name.c_str(), task::get_current_worker2()->index(), static_cast<long long unsigned int>(t) ); } else { wn = snprintf_p(ptr, capacity, "%6s.%7s.%05d.%016llx: ", task::get_current_node_name(), "io-thrd", tid, static_cast<long long unsigned int>(t) ); } } else { wn = snprintf_p(ptr, capacity, "%6s.%7s.%05d: ", task::get_current_node_name(), "io-thrd", tid ); } ptr += wn; capacity -= wn; // print body wn = std::vsnprintf(ptr, capacity - 1, fmt, args); if (wn < 0) { wn = snprintf_p(ptr, capacity - 1, "-- log entry is too long ---"); } *(ptr + wn) = '\n'; ptr += (wn + 1); capacity -= (wn + 1); // set next write ptr s_hpc_log_tls_info.next_write_ptr = ptr; // dump critical logs on screen if (log_level >= LOG_LEVEL_WARNING) { std::cout.write(ptr0, ptr - ptr0); } } //log operation void hpc_logger::buffer_push(char* buffer, int size) { _write_list.emplace_back(buffer, size); } void hpc_logger::write_buffer_list(std::vector<buffer_info>& llist) { for (auto& new_buffer_info : llist) { if (_current_log_file_bytes + new_buffer_info.buffer_size >= MAX_FILE_SIZE) { _current_log->close(); delete _current_log; _current_log = nullptr; create_log_file(); } if (new_buffer_info.buffer_size > 0) { _current_log->write(new_buffer_info.buffer, new_buffer_info.buffer_size); _current_log_file_bytes += new_buffer_info.buffer_size; } free(new_buffer_info.buffer); } llist.clear(); } } } <|endoftext|>
<commit_before>#include "ClassSpaceSymbolTable.h" #include <algorithm> #include "CompilationExceptions.h" ClassSpaceSymbolTable::ClassSpaceSymbolTable() { analyzer.reference = this; } ClassSpaceSymbolTable::~ClassSpaceSymbolTable() { for(map<string, pair<PropertySymbolTable*, bool> >::iterator it = classes.begin(); it != classes.end(); ++it) { delete it->second.first; } } boost::optional<SemanticError*> ClassSpaceSymbolTable::addClass(string name) { addingclass_name = name; if(classes.count(addingclass_name)) { return boost::optional<SemanticError*>(new SemanticError(MULTIPLE_CLASS_DEFINITION)); } addingclass_symbol = new PropertySymbolTable(&analyzer); addingclass_symbol->classname = name; addingclass_hassubclass = false; classes[addingclass_name] = pair<PropertySymbolTable*, bool>(addingclass_symbol, true); return boost::optional<SemanticError*>(); } boost::optional<SemanticError*> ClassSpaceSymbolTable::importClass(PropertySymbolTable* table) { if(classes.count(addingclass_name)) { return boost::optional<SemanticError*>(new SemanticError(MULTIPLE_CLASS_DEFINITION)); } classes[table->classname] = pair<PropertySymbolTable*, bool>(table, false); return boost::optional<SemanticError*>(); } PropertySymbolTable* ClassSpaceSymbolTable::getEmptyPropertySymbolTable() { return new PropertySymbolTable(&analyzer); } vector<PropertySymbolTable*> ClassSpaceSymbolTable::getDefinedClasses() { vector<PropertySymbolTable*> response; for(map<string, pair<PropertySymbolTable*, bool> >::iterator it = classes.begin(); it != classes.end(); ++it) { if(it->second.second) response.push_back(it->second.first); } return response; } boost::optional<SemanticError*> ClassSpaceSymbolTable::addInheritance(string childname, bool as_subclass) { if(addingclass_hassubclass && as_subclass) { return boost::optional<SemanticError*>(new SemanticError(MORE_THAN_ONE_SUBCLASS)); } if(childname == addingclass_name) { return boost::optional<SemanticError*>(new SemanticError(SELF_INHERITANCE)); } if(analyzer.isASubtypeOfB(childname, addingclass_name)) { return boost::optional<SemanticError*>(new SemanticError(CIRCULAR_INHERITANCE)); } if(addingclass_symbol->parentage.count(childname)) { return boost::optional<SemanticError*>(new SemanticError(MULTIPLE_INHERITANCE)); } addingclass_hassubclass = addingclass_symbol->parentage[childname] = as_subclass; return boost::optional<SemanticError*>(); } void ClassSpaceSymbolTable::propagateInheritance() { map<string, pair<PropertySymbolTable*, bool> > passed; for(map<string, pair<PropertySymbolTable*, bool> >::iterator it = classes.begin(); it != classes.end(); ++it) { inheritances_gathered[it->first] = pair<PropertySymbolTable*, bool>(it->second.first, false); } for(map<string, pair<PropertySymbolTable*, bool> >::iterator it = inheritances_gathered.begin(); it != inheritances_gathered.end(); ++it) { propagateInheritanceToParent(it->first); } //for(map<string, pair<PropertySymbolTable*, bool> >::iterator it = inheritances_gathered.begin(); it != inheritances_gathered.end(); ++it) { //delete it->second; //} } void ClassSpaceSymbolTable::propagateInheritanceToParent(string childname) { cout << childname << endl; bool defined = classes.find(childname)->second.second; if(!defined) return; cout << "wasn't skipped" << endl; pair<PropertySymbolTable*, bool>* current = &inheritances_gathered.find(childname)->second; if(current->second) return; // Already propagated for(map<string, bool>::iterator it = current->first->parentage.begin(); it != current->first->parentage.end(); ++it) { cout << "propagate to " << childname << " from " << it->first << endl; propagateInheritanceToParent(it->first); propagateInheritanceTables(current->first, findModifiable(it->first), it->second); } current->second = true; } ReadOnlyPropertySymbolTable* ClassSpaceSymbolTable::find(Type* type) { PropertySymbolTable* table = findModifiable(type); if(type->typedata._class.parameters == NULL) { if(table->getParameters().size()) { SymbolNotFoundException* error = new SymbolNotFoundException(); error->errormsg = "Type " + string(type->typedata._class.classname) + " cannot be used without type parameters";; throw error; } return table; } else { if(table->getParameters().size() != type->typedata._class.parameters->typecount) { SymbolNotFoundException* error = new SymbolNotFoundException(); error->errormsg = "Type " + string(type->typedata._class.classname) + " is used with the wrong number of type parameters";; throw error; } else { // TODO check lower and upper bounds on type parameters vector<Type*> temp; for(int i = 0; i < type->typedata._class.parameters->typecount; i++) { temp.push_back(type->typedata._class.parameters->types[i]); } return table->resolveParameters(temp); } } } ReadOnlyPropertySymbolTable* ClassSpaceSymbolTable::find(string name) { return findModifiable(name); } PropertySymbolTable* ClassSpaceSymbolTable::findModifiable(Type* type) { return findModifiable(type->typedata._class.classname); } PropertySymbolTable* ClassSpaceSymbolTable::findModifiable(string name) { std::map<string, pair<PropertySymbolTable*, bool> >::iterator searcher = classes.find(name); if(!classes.count(name)) { SymbolNotFoundException* error = new SymbolNotFoundException(); error->errormsg = "Could not find symbol "; error->errormsg += name; error->errormsg += " in object table"; throw error; } return searcher->second.first; } void ClassSpaceSymbolTable::assertTypeIsValid(Type* type) { if(type->type == TYPE_PARAMETERIZED) return; if(type->type == TYPE_CLASS) { if(classes.count(type->typedata._class.classname)) { std::map<string, pair<PropertySymbolTable*, bool> >::iterator searcher = classes.find(type->typedata._class.classname); PropertySymbolTable* table = searcher->second.first; vector<Type*> parameterizations; if(type->typedata._class.parameters != NULL) { int i; for(i = 0; i < type->typedata._class.parameters->typecount; i++) { assertTypeIsValid(type->typedata._class.parameters->types[i]); parameterizations.push_back(type->typedata._class.parameters->types[i]); } } // @TODO check upper and lower bounds against parameterizations if(table->getParameters().size() != parameterizations.size()) { throw new SemanticError(INVALID_GENERIC_TYPE, type->typedata._class.classname + string(" requires fewer type parameters, or more, or none.")); } return; } throw new SemanticError(CLASSNAME_NOT_FOUND, type->typedata._class.classname + string(" is not a valid type")); } else { if(type->typedata.lambda.returntype != NULL) assertTypeIsValid(type->typedata.lambda.returntype); if(type->typedata.lambda.arguments == NULL) return; int i; for(i = 0; i < type->typedata.lambda.arguments->typecount; i++) assertTypeIsValid(type->typedata.lambda.arguments->types[i]); } } void ClassSpaceSymbolTable::printEntryPoints(EntryPointAnalyzer* entryanalyzer) { for(map<string, pair<PropertySymbolTable*, bool> >::iterator it = classes.begin(); it != classes.end(); ++it) { if(!entryanalyzer->checkClassNeedsCanBeMain(it->second.first->getNeeds())) continue; entryanalyzer->printClass(it->first); it->second.first->printEntryPoints(entryanalyzer); } } TypeAnalyzer* ClassSpaceSymbolTable::getAnalyzer() { return &analyzer; } void ClassSpaceSymbolTable::assertNoNeedsAreCircular() { for(map<string, pair<PropertySymbolTable*, bool> >::iterator it = classes.begin(); it != classes.end(); ++it) { for(auto needit = it->second.first->getNeeds()->begin(); needit != it->second.first->getNeeds()->end(); ++needit) { analyzer.assertNeedIsNotCircular(it->first, *needit); } } } <commit_msg>Removed couts<commit_after>#include "ClassSpaceSymbolTable.h" #include <algorithm> #include "CompilationExceptions.h" ClassSpaceSymbolTable::ClassSpaceSymbolTable() { analyzer.reference = this; } ClassSpaceSymbolTable::~ClassSpaceSymbolTable() { for(map<string, pair<PropertySymbolTable*, bool> >::iterator it = classes.begin(); it != classes.end(); ++it) { delete it->second.first; } } boost::optional<SemanticError*> ClassSpaceSymbolTable::addClass(string name) { addingclass_name = name; if(classes.count(addingclass_name)) { return boost::optional<SemanticError*>(new SemanticError(MULTIPLE_CLASS_DEFINITION)); } addingclass_symbol = new PropertySymbolTable(&analyzer); addingclass_symbol->classname = name; addingclass_hassubclass = false; classes[addingclass_name] = pair<PropertySymbolTable*, bool>(addingclass_symbol, true); return boost::optional<SemanticError*>(); } boost::optional<SemanticError*> ClassSpaceSymbolTable::importClass(PropertySymbolTable* table) { if(classes.count(addingclass_name)) { return boost::optional<SemanticError*>(new SemanticError(MULTIPLE_CLASS_DEFINITION)); } classes[table->classname] = pair<PropertySymbolTable*, bool>(table, false); return boost::optional<SemanticError*>(); } PropertySymbolTable* ClassSpaceSymbolTable::getEmptyPropertySymbolTable() { return new PropertySymbolTable(&analyzer); } vector<PropertySymbolTable*> ClassSpaceSymbolTable::getDefinedClasses() { vector<PropertySymbolTable*> response; for(map<string, pair<PropertySymbolTable*, bool> >::iterator it = classes.begin(); it != classes.end(); ++it) { if(it->second.second) response.push_back(it->second.first); } return response; } boost::optional<SemanticError*> ClassSpaceSymbolTable::addInheritance(string childname, bool as_subclass) { if(addingclass_hassubclass && as_subclass) { return boost::optional<SemanticError*>(new SemanticError(MORE_THAN_ONE_SUBCLASS)); } if(childname == addingclass_name) { return boost::optional<SemanticError*>(new SemanticError(SELF_INHERITANCE)); } if(analyzer.isASubtypeOfB(childname, addingclass_name)) { return boost::optional<SemanticError*>(new SemanticError(CIRCULAR_INHERITANCE)); } if(addingclass_symbol->parentage.count(childname)) { return boost::optional<SemanticError*>(new SemanticError(MULTIPLE_INHERITANCE)); } addingclass_hassubclass = addingclass_symbol->parentage[childname] = as_subclass; return boost::optional<SemanticError*>(); } void ClassSpaceSymbolTable::propagateInheritance() { map<string, pair<PropertySymbolTable*, bool> > passed; for(map<string, pair<PropertySymbolTable*, bool> >::iterator it = classes.begin(); it != classes.end(); ++it) { inheritances_gathered[it->first] = pair<PropertySymbolTable*, bool>(it->second.first, false); } for(map<string, pair<PropertySymbolTable*, bool> >::iterator it = inheritances_gathered.begin(); it != inheritances_gathered.end(); ++it) { propagateInheritanceToParent(it->first); } //for(map<string, pair<PropertySymbolTable*, bool> >::iterator it = inheritances_gathered.begin(); it != inheritances_gathered.end(); ++it) { //delete it->second; //} } void ClassSpaceSymbolTable::propagateInheritanceToParent(string childname) { bool defined = classes.find(childname)->second.second; if(!defined) return; pair<PropertySymbolTable*, bool>* current = &inheritances_gathered.find(childname)->second; if(current->second) return; // Already propagated for(map<string, bool>::iterator it = current->first->parentage.begin(); it != current->first->parentage.end(); ++it) { propagateInheritanceToParent(it->first); propagateInheritanceTables(current->first, findModifiable(it->first), it->second); } current->second = true; } ReadOnlyPropertySymbolTable* ClassSpaceSymbolTable::find(Type* type) { PropertySymbolTable* table = findModifiable(type); if(type->typedata._class.parameters == NULL) { if(table->getParameters().size()) { SymbolNotFoundException* error = new SymbolNotFoundException(); error->errormsg = "Type " + string(type->typedata._class.classname) + " cannot be used without type parameters";; throw error; } return table; } else { if(table->getParameters().size() != type->typedata._class.parameters->typecount) { SymbolNotFoundException* error = new SymbolNotFoundException(); error->errormsg = "Type " + string(type->typedata._class.classname) + " is used with the wrong number of type parameters";; throw error; } else { // TODO check lower and upper bounds on type parameters vector<Type*> temp; for(int i = 0; i < type->typedata._class.parameters->typecount; i++) { temp.push_back(type->typedata._class.parameters->types[i]); } return table->resolveParameters(temp); } } } ReadOnlyPropertySymbolTable* ClassSpaceSymbolTable::find(string name) { return findModifiable(name); } PropertySymbolTable* ClassSpaceSymbolTable::findModifiable(Type* type) { return findModifiable(type->typedata._class.classname); } PropertySymbolTable* ClassSpaceSymbolTable::findModifiable(string name) { std::map<string, pair<PropertySymbolTable*, bool> >::iterator searcher = classes.find(name); if(!classes.count(name)) { SymbolNotFoundException* error = new SymbolNotFoundException(); error->errormsg = "Could not find symbol "; error->errormsg += name; error->errormsg += " in object table"; throw error; } return searcher->second.first; } void ClassSpaceSymbolTable::assertTypeIsValid(Type* type) { if(type->type == TYPE_PARAMETERIZED) return; if(type->type == TYPE_CLASS) { if(classes.count(type->typedata._class.classname)) { std::map<string, pair<PropertySymbolTable*, bool> >::iterator searcher = classes.find(type->typedata._class.classname); PropertySymbolTable* table = searcher->second.first; vector<Type*> parameterizations; if(type->typedata._class.parameters != NULL) { int i; for(i = 0; i < type->typedata._class.parameters->typecount; i++) { assertTypeIsValid(type->typedata._class.parameters->types[i]); parameterizations.push_back(type->typedata._class.parameters->types[i]); } } // @TODO check upper and lower bounds against parameterizations if(table->getParameters().size() != parameterizations.size()) { throw new SemanticError(INVALID_GENERIC_TYPE, type->typedata._class.classname + string(" requires fewer type parameters, or more, or none.")); } return; } throw new SemanticError(CLASSNAME_NOT_FOUND, type->typedata._class.classname + string(" is not a valid type")); } else { if(type->typedata.lambda.returntype != NULL) assertTypeIsValid(type->typedata.lambda.returntype); if(type->typedata.lambda.arguments == NULL) return; int i; for(i = 0; i < type->typedata.lambda.arguments->typecount; i++) assertTypeIsValid(type->typedata.lambda.arguments->types[i]); } } void ClassSpaceSymbolTable::printEntryPoints(EntryPointAnalyzer* entryanalyzer) { for(map<string, pair<PropertySymbolTable*, bool> >::iterator it = classes.begin(); it != classes.end(); ++it) { if(!entryanalyzer->checkClassNeedsCanBeMain(it->second.first->getNeeds())) continue; entryanalyzer->printClass(it->first); it->second.first->printEntryPoints(entryanalyzer); } } TypeAnalyzer* ClassSpaceSymbolTable::getAnalyzer() { return &analyzer; } void ClassSpaceSymbolTable::assertNoNeedsAreCircular() { for(map<string, pair<PropertySymbolTable*, bool> >::iterator it = classes.begin(); it != classes.end(); ++it) { for(auto needit = it->second.first->getNeeds()->begin(); needit != it->second.first->getNeeds()->end(); ++needit) { analyzer.assertNeedIsNotCircular(it->first, *needit); } } } <|endoftext|>
<commit_before>// Copyright 2015, University of Freiburg, // Chair of Algorithms and Data Structures. // Author: Björn Buchhold (buchhold@informatik.uni-freiburg.de) #include <string> #include <sstream> #include <algorithm> #include "./QueryExecutionTree.h" #include "./IndexScan.h" #include "./Join.h" #include "./Sort.h" #include "./OrderBy.h" #include "./Filter.h" #include "./Distinct.h" #include "TextOperationForContexts.h" #include "TextOperationWithFilter.h" #include "TextOperationWithoutFilter.h" #include "TwoColumnJoin.h" using std::string; // _____________________________________________________________________________ QueryExecutionTree::QueryExecutionTree(QueryExecutionContext* qec) : _qec(qec), _variableColumnMap(), _rootOperation(nullptr), _type(OperationType::UNDEFINED), _contextVars(), _asString(), _sizeEstimate(std::numeric_limits<size_t>::max()) { } // _____________________________________________________________________________ string QueryExecutionTree::asString(size_t indent) { string indentStr; for (size_t i = 0; i < indent; ++i) { indentStr += " "; } if (_asString.size() == 0) { if (_rootOperation) { std::ostringstream os; os << indentStr << "{\n" << _rootOperation->asString(indent + 2) << "\n" << indentStr << " qet-width: " << getResultWidth() << " "; if (LOGLEVEL >= DEBUG && _qec) { os << " [estimated size: " << getSizeEstimate() << "]"; os << " [multiplicities: "; for (size_t i = 0; i < getResultWidth(); ++i) { os << getMultiplicity(i) << ' '; } os << "]"; } os << '\n' << indentStr << '}'; _asString = os.str(); } else { _asString = "<Empty QueryExecutionTree>"; } } return _asString; } // _____________________________________________________________________________ void QueryExecutionTree::setOperation(QueryExecutionTree::OperationType type, std::shared_ptr<Operation> op) { _type = type; _rootOperation = op; _asString = ""; _sizeEstimate = std::numeric_limits<size_t>::max(); } // _____________________________________________________________________________ void QueryExecutionTree::setVariableColumn(const string& variable, size_t column) { _variableColumnMap[variable] = column; } // _____________________________________________________________________________ size_t QueryExecutionTree::getVariableColumn(const string& variable) const { if (_variableColumnMap.count(variable) == 0) { AD_THROW(ad_semsearch::Exception::CHECK_FAILED, "Variable could not be mapped to result column. Var: " + variable); } return _variableColumnMap.find(variable)->second; } // _____________________________________________________________________________ void QueryExecutionTree::setVariableColumns( std::unordered_map<string, size_t> const& map) { _variableColumnMap = map; } // _____________________________________________________________________________ void QueryExecutionTree::writeResultToStream(std::ostream& out, const vector<string>& selectVars, size_t limit, size_t offset, char sep) const { // They may trigger computation (but does not have to). const ResultTable& res = getResult(); LOG(DEBUG) << "Resolving strings for finished binary result...\n"; vector<pair<size_t, OutputType>> validIndices; for (auto var : selectVars) { OutputType outputType = OutputType::KB; if (ad_utility::startsWith(var, "SCORE(") || isContextvar(var)) { outputType = OutputType::VERBATIM; } if (ad_utility::startsWith(var, "TEXT(")) { outputType = OutputType::TEXT; var = var.substr(5, var.rfind(')') - 5); } if (getVariableColumnMap().find(var) != getVariableColumnMap().end()) { validIndices.push_back( pair<size_t, OutputType>(getVariableColumnMap().find(var)->second, outputType)); } } if (validIndices.size() == 0) { return; } if (res._nofColumns == 1) { auto data = static_cast<vector<array<Id, 1>>*>(res._fixedSizeData); size_t upperBound = std::min<size_t>(offset + limit, data->size()); writeTable(*data, sep, offset, upperBound, validIndices, out); } else if (res._nofColumns == 2) { auto data = static_cast<vector<array<Id, 2>>*>(res._fixedSizeData); size_t upperBound = std::min<size_t>(offset + limit, data->size()); writeTable(*data, sep, offset, upperBound, validIndices, out); } else if (res._nofColumns == 3) { auto data = static_cast<vector<array<Id, 3>>*>(res._fixedSizeData); size_t upperBound = std::min<size_t>(offset + limit, data->size()); writeTable(*data, sep, offset, upperBound, validIndices, out); } else if (res._nofColumns == 4) { auto data = static_cast<vector<array<Id, 4>>*>(res._fixedSizeData); size_t upperBound = std::min<size_t>(offset + limit, data->size()); writeTable(*data, sep, offset, upperBound, validIndices, out); } else if (res._nofColumns == 5) { auto data = static_cast<vector<array<Id, 5>>*>(res._fixedSizeData); size_t upperBound = std::min<size_t>(offset + limit, data->size()); writeTable(*data, sep, offset, upperBound, validIndices, out); } else { size_t upperBound = std::min<size_t>(offset + limit, res._varSizeData.size()); writeTable(res._varSizeData, sep, offset, upperBound, validIndices, out); } LOG(DEBUG) << "Done creating readable result.\n"; } // _____________________________________________________________________________ void QueryExecutionTree::writeResultToStreamAsJson( std::ostream& out, const vector<string>& selectVars, size_t limit, size_t offset, size_t maxSend) const { out << "[\r\n"; // They may trigger computation (but does not have to). const ResultTable& res = getResult(); LOG(DEBUG) << "Resolving strings for finished binary result...\n"; vector<pair<size_t, OutputType>> validIndices; for (auto var : selectVars) { OutputType outputType = OutputType::KB; if (ad_utility::startsWith(var, "SCORE(") || isContextvar(var)) { outputType = OutputType::VERBATIM; } if (ad_utility::startsWith(var, "TEXT(")) { outputType = OutputType::TEXT; var = var.substr(5, var.rfind(')') - 5); } auto vc = getVariableColumnMap().find(var); if (vc != getVariableColumnMap().end()) { validIndices.push_back( pair<size_t, OutputType>(vc->second, outputType)); } } if (validIndices.size() == 0) { return; } if (res._nofColumns == 1) { auto data = static_cast<vector<array<Id, 1>>*>(res._fixedSizeData); size_t upperBound = std::min<size_t>(offset + limit, data->size()); writeJsonTable(*data, offset, upperBound, validIndices, maxSend, out); } else if (res._nofColumns == 2) { auto data = static_cast<vector<array<Id, 2>>*>(res._fixedSizeData); size_t upperBound = std::min<size_t>(offset + limit, data->size()); writeJsonTable(*data, offset, upperBound, validIndices, maxSend, out); } else if (res._nofColumns == 3) { auto data = static_cast<vector<array<Id, 3>>*>(res._fixedSizeData); size_t upperBound = std::min<size_t>(offset + limit, data->size()); writeJsonTable(*data, offset, upperBound, validIndices, maxSend, out); } else if (res._nofColumns == 4) { auto data = static_cast<vector<array<Id, 4>>*>(res._fixedSizeData); size_t upperBound = std::min<size_t>(offset + limit, data->size()); writeJsonTable(*data, offset, upperBound, validIndices, maxSend, out); } else if (res._nofColumns == 5) { auto data = static_cast<vector<array<Id, 5>>*>(res._fixedSizeData); size_t upperBound = std::min<size_t>(offset + limit, data->size()); writeJsonTable(*data, offset, upperBound, validIndices, maxSend, out); } else { size_t upperBound = std::min<size_t>(offset + limit, res._varSizeData.size()); writeJsonTable(res._varSizeData, offset, upperBound, validIndices, maxSend, out); } out << "]"; LOG(DEBUG) << "Done creating readable result.\n"; } // _____________________________________________________________________________ size_t QueryExecutionTree::getCostEstimate() { if (_type == QueryExecutionTree::SCAN && getResultWidth() == 1) { return getSizeEstimate(); } else { return _rootOperation->getCostEstimate(); } } // _____________________________________________________________________________ size_t QueryExecutionTree::getSizeEstimate() { if (_sizeEstimate == std::numeric_limits<size_t>::max()) { if (_qec) { if (_type == QueryExecutionTree::SCAN && getResultWidth() == 1) { _sizeEstimate = getResult().size(); } else { _sizeEstimate = _rootOperation->getSizeEstimate(); } } else { // For test cases without index only: // Make it deterministic by using the asString. _sizeEstimate = 1000 + std::hash<string>{}(_rootOperation->asString()) % 1000; } } return _sizeEstimate; } // _____________________________________________________________________________ bool QueryExecutionTree::knownEmptyResult() { return getSizeEstimate() == 0; } // _____________________________________________________________________________ bool QueryExecutionTree::varCovered(string var) const { return _variableColumnMap.count(var) > 0; } <commit_msg>Fixed a problem with the JSON result when no selected variable occurred in the where clauses<commit_after>// Copyright 2015, University of Freiburg, // Chair of Algorithms and Data Structures. // Author: Björn Buchhold (buchhold@informatik.uni-freiburg.de) #include <string> #include <sstream> #include <algorithm> #include "./QueryExecutionTree.h" #include "./IndexScan.h" #include "./Join.h" #include "./Sort.h" #include "./OrderBy.h" #include "./Filter.h" #include "./Distinct.h" #include "TextOperationForContexts.h" #include "TextOperationWithFilter.h" #include "TextOperationWithoutFilter.h" #include "TwoColumnJoin.h" using std::string; // _____________________________________________________________________________ QueryExecutionTree::QueryExecutionTree(QueryExecutionContext* qec) : _qec(qec), _variableColumnMap(), _rootOperation(nullptr), _type(OperationType::UNDEFINED), _contextVars(), _asString(), _sizeEstimate(std::numeric_limits<size_t>::max()) { } // _____________________________________________________________________________ string QueryExecutionTree::asString(size_t indent) { string indentStr; for (size_t i = 0; i < indent; ++i) { indentStr += " "; } if (_asString.size() == 0) { if (_rootOperation) { std::ostringstream os; os << indentStr << "{\n" << _rootOperation->asString(indent + 2) << "\n" << indentStr << " qet-width: " << getResultWidth() << " "; if (LOGLEVEL >= DEBUG && _qec) { os << " [estimated size: " << getSizeEstimate() << "]"; os << " [multiplicities: "; for (size_t i = 0; i < getResultWidth(); ++i) { os << getMultiplicity(i) << ' '; } os << "]"; } os << '\n' << indentStr << '}'; _asString = os.str(); } else { _asString = "<Empty QueryExecutionTree>"; } } return _asString; } // _____________________________________________________________________________ void QueryExecutionTree::setOperation(QueryExecutionTree::OperationType type, std::shared_ptr<Operation> op) { _type = type; _rootOperation = op; _asString = ""; _sizeEstimate = std::numeric_limits<size_t>::max(); } // _____________________________________________________________________________ void QueryExecutionTree::setVariableColumn(const string& variable, size_t column) { _variableColumnMap[variable] = column; } // _____________________________________________________________________________ size_t QueryExecutionTree::getVariableColumn(const string& variable) const { if (_variableColumnMap.count(variable) == 0) { AD_THROW(ad_semsearch::Exception::CHECK_FAILED, "Variable could not be mapped to result column. Var: " + variable); } return _variableColumnMap.find(variable)->second; } // _____________________________________________________________________________ void QueryExecutionTree::setVariableColumns( std::unordered_map<string, size_t> const& map) { _variableColumnMap = map; } // _____________________________________________________________________________ void QueryExecutionTree::writeResultToStream(std::ostream& out, const vector<string>& selectVars, size_t limit, size_t offset, char sep) const { // They may trigger computation (but does not have to). const ResultTable& res = getResult(); LOG(DEBUG) << "Resolving strings for finished binary result...\n"; vector<pair<size_t, OutputType>> validIndices; for (auto var : selectVars) { OutputType outputType = OutputType::KB; if (ad_utility::startsWith(var, "SCORE(") || isContextvar(var)) { outputType = OutputType::VERBATIM; } if (ad_utility::startsWith(var, "TEXT(")) { outputType = OutputType::TEXT; var = var.substr(5, var.rfind(')') - 5); } if (getVariableColumnMap().find(var) != getVariableColumnMap().end()) { validIndices.push_back( pair<size_t, OutputType>(getVariableColumnMap().find(var)->second, outputType)); } } if (validIndices.size() == 0) { return; } if (res._nofColumns == 1) { auto data = static_cast<vector<array<Id, 1>>*>(res._fixedSizeData); size_t upperBound = std::min<size_t>(offset + limit, data->size()); writeTable(*data, sep, offset, upperBound, validIndices, out); } else if (res._nofColumns == 2) { auto data = static_cast<vector<array<Id, 2>>*>(res._fixedSizeData); size_t upperBound = std::min<size_t>(offset + limit, data->size()); writeTable(*data, sep, offset, upperBound, validIndices, out); } else if (res._nofColumns == 3) { auto data = static_cast<vector<array<Id, 3>>*>(res._fixedSizeData); size_t upperBound = std::min<size_t>(offset + limit, data->size()); writeTable(*data, sep, offset, upperBound, validIndices, out); } else if (res._nofColumns == 4) { auto data = static_cast<vector<array<Id, 4>>*>(res._fixedSizeData); size_t upperBound = std::min<size_t>(offset + limit, data->size()); writeTable(*data, sep, offset, upperBound, validIndices, out); } else if (res._nofColumns == 5) { auto data = static_cast<vector<array<Id, 5>>*>(res._fixedSizeData); size_t upperBound = std::min<size_t>(offset + limit, data->size()); writeTable(*data, sep, offset, upperBound, validIndices, out); } else { size_t upperBound = std::min<size_t>(offset + limit, res._varSizeData.size()); writeTable(res._varSizeData, sep, offset, upperBound, validIndices, out); } LOG(DEBUG) << "Done creating readable result.\n"; } // _____________________________________________________________________________ void QueryExecutionTree::writeResultToStreamAsJson( std::ostream& out, const vector<string>& selectVars, size_t limit, size_t offset, size_t maxSend) const { out << "[\r\n"; // They may trigger computation (but does not have to). const ResultTable& res = getResult(); LOG(DEBUG) << "Resolving strings for finished binary result...\n"; vector<pair<size_t, OutputType>> validIndices; for (auto var : selectVars) { OutputType outputType = OutputType::KB; if (ad_utility::startsWith(var, "SCORE(") || isContextvar(var)) { outputType = OutputType::VERBATIM; } if (ad_utility::startsWith(var, "TEXT(")) { outputType = OutputType::TEXT; var = var.substr(5, var.rfind(')') - 5); } auto vc = getVariableColumnMap().find(var); if (vc != getVariableColumnMap().end()) { validIndices.push_back( pair<size_t, OutputType>(vc->second, outputType)); } } if (validIndices.size() == 0) { out << "]"; return; } if (res._nofColumns == 1) { auto data = static_cast<vector<array<Id, 1>>*>(res._fixedSizeData); size_t upperBound = std::min<size_t>(offset + limit, data->size()); writeJsonTable(*data, offset, upperBound, validIndices, maxSend, out); } else if (res._nofColumns == 2) { auto data = static_cast<vector<array<Id, 2>>*>(res._fixedSizeData); size_t upperBound = std::min<size_t>(offset + limit, data->size()); writeJsonTable(*data, offset, upperBound, validIndices, maxSend, out); } else if (res._nofColumns == 3) { auto data = static_cast<vector<array<Id, 3>>*>(res._fixedSizeData); size_t upperBound = std::min<size_t>(offset + limit, data->size()); writeJsonTable(*data, offset, upperBound, validIndices, maxSend, out); } else if (res._nofColumns == 4) { auto data = static_cast<vector<array<Id, 4>>*>(res._fixedSizeData); size_t upperBound = std::min<size_t>(offset + limit, data->size()); writeJsonTable(*data, offset, upperBound, validIndices, maxSend, out); } else if (res._nofColumns == 5) { auto data = static_cast<vector<array<Id, 5>>*>(res._fixedSizeData); size_t upperBound = std::min<size_t>(offset + limit, data->size()); writeJsonTable(*data, offset, upperBound, validIndices, maxSend, out); } else { size_t upperBound = std::min<size_t>(offset + limit, res._varSizeData.size()); writeJsonTable(res._varSizeData, offset, upperBound, validIndices, maxSend, out); } out << "]"; LOG(DEBUG) << "Done creating readable result.\n"; } // _____________________________________________________________________________ size_t QueryExecutionTree::getCostEstimate() { if (_type == QueryExecutionTree::SCAN && getResultWidth() == 1) { return getSizeEstimate(); } else { return _rootOperation->getCostEstimate(); } } // _____________________________________________________________________________ size_t QueryExecutionTree::getSizeEstimate() { if (_sizeEstimate == std::numeric_limits<size_t>::max()) { if (_qec) { if (_type == QueryExecutionTree::SCAN && getResultWidth() == 1) { _sizeEstimate = getResult().size(); } else { _sizeEstimate = _rootOperation->getSizeEstimate(); } } else { // For test cases without index only: // Make it deterministic by using the asString. _sizeEstimate = 1000 + std::hash<string>{}(_rootOperation->asString()) % 1000; } } return _sizeEstimate; } // _____________________________________________________________________________ bool QueryExecutionTree::knownEmptyResult() { return getSizeEstimate() == 0; } // _____________________________________________________________________________ bool QueryExecutionTree::varCovered(string var) const { return _variableColumnMap.count(var) > 0; } <|endoftext|>
<commit_before>/* * Copyright 2014 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkAdvancedTypefaceMetrics.h" #include "SkBitmap.h" #include "SkCanvas.h" #include "SkDescriptor.h" #include "SkFontDescriptor.h" #include "SkGlyph.h" #include "SkMask.h" // #include "SkOTUtils.h" #include "SkScalerContext.h" #include "SkTestScalerContext.h" #include "SkTypefaceCache.h" SkTestFont::SkTestFont(const SkTestFontData& fontData) : INHERITED() , fCharCodes(fontData.fCharCodes) , fCharCodesCount(fontData.fCharCodesCount) , fWidths(fontData.fWidths) , fMetrics(fontData.fMetrics) , fName(fontData.fName) , fPaths(NULL) { init(fontData.fPoints, fontData.fVerbs); #ifdef SK_DEBUG sk_bzero(fDebugBits, sizeof(fDebugBits)); sk_bzero(fDebugOverage, sizeof(fDebugOverage)); #endif } SkTestFont::~SkTestFont() { for (unsigned index = 0; index < fCharCodesCount; ++index) { SkDELETE(fPaths[index]); } SkDELETE_ARRAY(fPaths); } #ifdef SK_DEBUG #include "SkThread.h" SK_DECLARE_STATIC_MUTEX(gUsedCharsMutex); #endif int SkTestFont::codeToIndex(SkUnichar charCode) const { #ifdef SK_DEBUG // detect missing test font data { SkAutoMutexAcquire ac(gUsedCharsMutex); if (charCode >= ' ' && charCode <= '~') { int bitOffset = charCode - ' '; fDebugBits[bitOffset >> 3] |= 1 << (bitOffset & 7); } else { int index = 0; while (fDebugOverage[index] != 0 && fDebugOverage[index] != charCode && index < (int) sizeof(fDebugOverage)) { ++index; } SkASSERT(index < (int) sizeof(fDebugOverage)); if (fDebugOverage[index] == 0) { fDebugOverage[index] = charCode; } } } #endif for (unsigned index = 0; index < fCharCodesCount; ++index) { if (fCharCodes[index] == (unsigned) charCode) { return (int) index; } } SkDEBUGF(("missing '%c' (%d) from %s %d\n", (char) charCode, charCode, fDebugName, fDebugStyle)); return 0; } void SkTestFont::init(const SkScalar* pts, const unsigned char* verbs) { fPaths = SkNEW_ARRAY(SkPath*, fCharCodesCount); for (unsigned index = 0; index < fCharCodesCount; ++index) { SkPath* path = SkNEW(SkPath); SkPath::Verb verb; while ((verb = (SkPath::Verb) *verbs++) != SkPath::kDone_Verb) { switch (verb) { case SkPath::kMove_Verb: path->moveTo(pts[0], pts[1]); pts += 2; break; case SkPath::kLine_Verb: path->lineTo(pts[0], pts[1]); pts += 2; break; case SkPath::kQuad_Verb: path->quadTo(pts[0], pts[1], pts[2], pts[3]); pts += 4; break; case SkPath::kCubic_Verb: path->cubicTo(pts[0], pts[1], pts[2], pts[3], pts[4], pts[5]); pts += 6; break; case SkPath::kClose_Verb: path->close(); break; default: SkDEBUGFAIL("bad verb"); return; } } fPaths[index] = path; } } SkTestTypeface::SkTestTypeface(SkTestFont* testFont, const SkFontStyle& style) : SkTypeface(style, SkTypefaceCache::NewFontID(), false) , fTestFont(testFont) { } void SkTestTypeface::getAdvance(SkGlyph* glyph) { glyph->fAdvanceX = fTestFont->fWidths[glyph->getGlyphID()]; glyph->fAdvanceY = 0; } void SkTestTypeface::getFontMetrics(SkPaint::FontMetrics* metrics) { *metrics = fTestFont->fMetrics; } void SkTestTypeface::getMetrics(SkGlyph* glyph) { glyph->fAdvanceX = fTestFont->fWidths[glyph->getGlyphID()]; glyph->fAdvanceY = 0; } void SkTestTypeface::getPath(const SkGlyph& glyph, SkPath* path) { *path = *fTestFont->fPaths[glyph.getGlyphID()]; } void SkTestTypeface::onFilterRec(SkScalerContextRec* rec) const { rec->setHinting(SkPaint::kNo_Hinting); } SkAdvancedTypefaceMetrics* SkTestTypeface::onGetAdvancedTypefaceMetrics( PerGlyphInfo , const uint32_t* glyphIDs, uint32_t glyphIDsCount) const { // pdf only SkAdvancedTypefaceMetrics* info = new SkAdvancedTypefaceMetrics; info->fEmSize = 0; info->fLastGlyphID = SkToU16(onCountGlyphs() - 1); info->fStyle = 0; info->fFontName.set(fTestFont->fName); info->fType = SkAdvancedTypefaceMetrics::kOther_Font; info->fItalicAngle = 0; info->fAscent = 0; info->fDescent = 0; info->fStemV = 0; info->fCapHeight = 0; info->fBBox = SkIRect::MakeEmpty(); return info; } void SkTestTypeface::onGetFontDescriptor(SkFontDescriptor* desc, bool* isLocal) const { desc->setFamilyName(fTestFont->fName); *isLocal = false; } int SkTestTypeface::onCharsToGlyphs(const void* chars, Encoding encoding, uint16_t glyphs[], int glyphCount) const { SkASSERT(encoding == kUTF16_Encoding); for (int index = 0; index < glyphCount; ++index) { SkUnichar ch = ((SkUnichar*) chars)[index]; glyphs[index] = fTestFont->codeToIndex(ch); } return glyphCount; } void SkTestTypeface::onGetFamilyName(SkString* familyName) const { *familyName = fTestFont->fName; } SkTypeface::LocalizedStrings* SkTestTypeface::onCreateFamilyNameIterator() const { SkString familyName(fTestFont->fName); SkString language("und"); //undetermined SkASSERT(0); // incomplete return NULL; // return new SkOTUtils::LocalizedStrings_SingleName(familyName, language); } class SkTestScalerContext : public SkScalerContext { public: SkTestScalerContext(SkTestTypeface* face, const SkDescriptor* desc) : SkScalerContext(face, desc) , fFace(face) { fRec.getSingleMatrix(&fMatrix); this->forceGenerateImageFromPath(); } virtual ~SkTestScalerContext() { } protected: unsigned generateGlyphCount() override { return fFace->onCountGlyphs(); } uint16_t generateCharToGlyph(SkUnichar uni) override { uint16_t glyph; (void) fFace->onCharsToGlyphs((const void *) &uni, SkTypeface::kUTF16_Encoding, &glyph, 1); return glyph; } void generateAdvance(SkGlyph* glyph) override { fFace->getAdvance(glyph); const SkVector advance = fMatrix.mapXY(SkFixedToScalar(glyph->fAdvanceX), SkFixedToScalar(glyph->fAdvanceY)); glyph->fAdvanceX = SkScalarToFixed(advance.fX); glyph->fAdvanceY = SkScalarToFixed(advance.fY); } void generateMetrics(SkGlyph* glyph) override { fFace->getMetrics(glyph); const SkVector advance = fMatrix.mapXY(SkFixedToScalar(glyph->fAdvanceX), SkFixedToScalar(glyph->fAdvanceY)); glyph->fAdvanceX = SkScalarToFixed(advance.fX); glyph->fAdvanceY = SkScalarToFixed(advance.fY); SkPath path; fFace->getPath(*glyph, &path); path.transform(fMatrix); SkRect storage; const SkPaint paint; const SkRect& newBounds = paint.doComputeFastBounds(path.getBounds(), &storage, SkPaint::kFill_Style); SkIRect ibounds; newBounds.roundOut(&ibounds); glyph->fLeft = ibounds.fLeft; glyph->fTop = ibounds.fTop; glyph->fWidth = ibounds.width(); glyph->fHeight = ibounds.height(); } void generateImage(const SkGlyph& glyph) override { SkPath path; fFace->getPath(glyph, &path); SkBitmap bm; bm.installPixels(SkImageInfo::MakeN32Premul(glyph.fWidth, glyph.fHeight), glyph.fImage, glyph.rowBytes()); bm.eraseColor(0); SkCanvas canvas(bm); canvas.translate(-SkIntToScalar(glyph.fLeft), -SkIntToScalar(glyph.fTop)); canvas.concat(fMatrix); SkPaint paint; paint.setAntiAlias(true); canvas.drawPath(path, paint); } void generatePath(const SkGlyph& glyph, SkPath* path) override { fFace->getPath(glyph, path); path->transform(fMatrix); } void generateFontMetrics(SkPaint::FontMetrics* metrics) override { fFace->getFontMetrics(metrics); if (metrics) { SkScalar scale = fMatrix.getScaleY(); metrics->fTop = SkScalarMul(metrics->fTop, scale); metrics->fAscent = SkScalarMul(metrics->fAscent, scale); metrics->fDescent = SkScalarMul(metrics->fDescent, scale); metrics->fBottom = SkScalarMul(metrics->fBottom, scale); metrics->fLeading = SkScalarMul(metrics->fLeading, scale); metrics->fAvgCharWidth = SkScalarMul(metrics->fAvgCharWidth, scale); metrics->fXMin = SkScalarMul(metrics->fXMin, scale); metrics->fXMax = SkScalarMul(metrics->fXMax, scale); metrics->fXHeight = SkScalarMul(metrics->fXHeight, scale); } } private: SkTestTypeface* fFace; SkMatrix fMatrix; }; SkScalerContext* SkTestTypeface::onCreateScalerContext(const SkDescriptor* desc) const { return SkNEW_ARGS(SkTestScalerContext, (const_cast<SkTestTypeface*>(this), desc)); } <commit_msg>initialize font metrics for pdf (found by valgrind)<commit_after>/* * Copyright 2014 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkAdvancedTypefaceMetrics.h" #include "SkBitmap.h" #include "SkCanvas.h" #include "SkDescriptor.h" #include "SkFontDescriptor.h" #include "SkGlyph.h" #include "SkMask.h" // #include "SkOTUtils.h" #include "SkScalerContext.h" #include "SkTestScalerContext.h" #include "SkTypefaceCache.h" SkTestFont::SkTestFont(const SkTestFontData& fontData) : INHERITED() , fCharCodes(fontData.fCharCodes) , fCharCodesCount(fontData.fCharCodesCount) , fWidths(fontData.fWidths) , fMetrics(fontData.fMetrics) , fName(fontData.fName) , fPaths(NULL) { init(fontData.fPoints, fontData.fVerbs); #ifdef SK_DEBUG sk_bzero(fDebugBits, sizeof(fDebugBits)); sk_bzero(fDebugOverage, sizeof(fDebugOverage)); #endif } SkTestFont::~SkTestFont() { for (unsigned index = 0; index < fCharCodesCount; ++index) { SkDELETE(fPaths[index]); } SkDELETE_ARRAY(fPaths); } #ifdef SK_DEBUG #include "SkThread.h" SK_DECLARE_STATIC_MUTEX(gUsedCharsMutex); #endif int SkTestFont::codeToIndex(SkUnichar charCode) const { #ifdef SK_DEBUG // detect missing test font data { SkAutoMutexAcquire ac(gUsedCharsMutex); if (charCode >= ' ' && charCode <= '~') { int bitOffset = charCode - ' '; fDebugBits[bitOffset >> 3] |= 1 << (bitOffset & 7); } else { int index = 0; while (fDebugOverage[index] != 0 && fDebugOverage[index] != charCode && index < (int) sizeof(fDebugOverage)) { ++index; } SkASSERT(index < (int) sizeof(fDebugOverage)); if (fDebugOverage[index] == 0) { fDebugOverage[index] = charCode; } } } #endif for (unsigned index = 0; index < fCharCodesCount; ++index) { if (fCharCodes[index] == (unsigned) charCode) { return (int) index; } } SkDEBUGF(("missing '%c' (%d) from %s %d\n", (char) charCode, charCode, fDebugName, fDebugStyle)); return 0; } void SkTestFont::init(const SkScalar* pts, const unsigned char* verbs) { fPaths = SkNEW_ARRAY(SkPath*, fCharCodesCount); for (unsigned index = 0; index < fCharCodesCount; ++index) { SkPath* path = SkNEW(SkPath); SkPath::Verb verb; while ((verb = (SkPath::Verb) *verbs++) != SkPath::kDone_Verb) { switch (verb) { case SkPath::kMove_Verb: path->moveTo(pts[0], pts[1]); pts += 2; break; case SkPath::kLine_Verb: path->lineTo(pts[0], pts[1]); pts += 2; break; case SkPath::kQuad_Verb: path->quadTo(pts[0], pts[1], pts[2], pts[3]); pts += 4; break; case SkPath::kCubic_Verb: path->cubicTo(pts[0], pts[1], pts[2], pts[3], pts[4], pts[5]); pts += 6; break; case SkPath::kClose_Verb: path->close(); break; default: SkDEBUGFAIL("bad verb"); return; } } fPaths[index] = path; } } SkTestTypeface::SkTestTypeface(SkTestFont* testFont, const SkFontStyle& style) : SkTypeface(style, SkTypefaceCache::NewFontID(), false) , fTestFont(testFont) { } void SkTestTypeface::getAdvance(SkGlyph* glyph) { glyph->fAdvanceX = fTestFont->fWidths[glyph->getGlyphID()]; glyph->fAdvanceY = 0; } void SkTestTypeface::getFontMetrics(SkPaint::FontMetrics* metrics) { *metrics = fTestFont->fMetrics; } void SkTestTypeface::getMetrics(SkGlyph* glyph) { glyph->fAdvanceX = fTestFont->fWidths[glyph->getGlyphID()]; glyph->fAdvanceY = 0; } void SkTestTypeface::getPath(const SkGlyph& glyph, SkPath* path) { *path = *fTestFont->fPaths[glyph.getGlyphID()]; } void SkTestTypeface::onFilterRec(SkScalerContextRec* rec) const { rec->setHinting(SkPaint::kNo_Hinting); } SkAdvancedTypefaceMetrics* SkTestTypeface::onGetAdvancedTypefaceMetrics( PerGlyphInfo , const uint32_t* glyphIDs, uint32_t glyphIDsCount) const { // pdf only SkAdvancedTypefaceMetrics* info = new SkAdvancedTypefaceMetrics; info->fFontName.set(fTestFont->fName); info->fType = SkAdvancedTypefaceMetrics::kOther_Font; info->fFlags = SkAdvancedTypefaceMetrics::kEmpty_FontFlag; info->fLastGlyphID = static_cast<uint16_t>(fTestFont->fCharCodesCount - 1); info->fEmSize = 0; info->fLastGlyphID = SkToU16(onCountGlyphs() - 1); info->fStyle = 0; info->fItalicAngle = 0; info->fAscent = 0; info->fDescent = 0; info->fStemV = 0; info->fCapHeight = 0; info->fBBox = SkIRect::MakeEmpty(); return info; } void SkTestTypeface::onGetFontDescriptor(SkFontDescriptor* desc, bool* isLocal) const { desc->setFamilyName(fTestFont->fName); *isLocal = false; } int SkTestTypeface::onCharsToGlyphs(const void* chars, Encoding encoding, uint16_t glyphs[], int glyphCount) const { SkASSERT(encoding == kUTF16_Encoding); for (int index = 0; index < glyphCount; ++index) { SkUnichar ch = ((SkUnichar*) chars)[index]; glyphs[index] = fTestFont->codeToIndex(ch); } return glyphCount; } void SkTestTypeface::onGetFamilyName(SkString* familyName) const { *familyName = fTestFont->fName; } SkTypeface::LocalizedStrings* SkTestTypeface::onCreateFamilyNameIterator() const { SkString familyName(fTestFont->fName); SkString language("und"); //undetermined SkASSERT(0); // incomplete return NULL; // return new SkOTUtils::LocalizedStrings_SingleName(familyName, language); } class SkTestScalerContext : public SkScalerContext { public: SkTestScalerContext(SkTestTypeface* face, const SkDescriptor* desc) : SkScalerContext(face, desc) , fFace(face) { fRec.getSingleMatrix(&fMatrix); this->forceGenerateImageFromPath(); } virtual ~SkTestScalerContext() { } protected: unsigned generateGlyphCount() override { return fFace->onCountGlyphs(); } uint16_t generateCharToGlyph(SkUnichar uni) override { uint16_t glyph; (void) fFace->onCharsToGlyphs((const void *) &uni, SkTypeface::kUTF16_Encoding, &glyph, 1); return glyph; } void generateAdvance(SkGlyph* glyph) override { fFace->getAdvance(glyph); const SkVector advance = fMatrix.mapXY(SkFixedToScalar(glyph->fAdvanceX), SkFixedToScalar(glyph->fAdvanceY)); glyph->fAdvanceX = SkScalarToFixed(advance.fX); glyph->fAdvanceY = SkScalarToFixed(advance.fY); } void generateMetrics(SkGlyph* glyph) override { fFace->getMetrics(glyph); const SkVector advance = fMatrix.mapXY(SkFixedToScalar(glyph->fAdvanceX), SkFixedToScalar(glyph->fAdvanceY)); glyph->fAdvanceX = SkScalarToFixed(advance.fX); glyph->fAdvanceY = SkScalarToFixed(advance.fY); SkPath path; fFace->getPath(*glyph, &path); path.transform(fMatrix); SkRect storage; const SkPaint paint; const SkRect& newBounds = paint.doComputeFastBounds(path.getBounds(), &storage, SkPaint::kFill_Style); SkIRect ibounds; newBounds.roundOut(&ibounds); glyph->fLeft = ibounds.fLeft; glyph->fTop = ibounds.fTop; glyph->fWidth = ibounds.width(); glyph->fHeight = ibounds.height(); } void generateImage(const SkGlyph& glyph) override { SkPath path; fFace->getPath(glyph, &path); SkBitmap bm; bm.installPixels(SkImageInfo::MakeN32Premul(glyph.fWidth, glyph.fHeight), glyph.fImage, glyph.rowBytes()); bm.eraseColor(0); SkCanvas canvas(bm); canvas.translate(-SkIntToScalar(glyph.fLeft), -SkIntToScalar(glyph.fTop)); canvas.concat(fMatrix); SkPaint paint; paint.setAntiAlias(true); canvas.drawPath(path, paint); } void generatePath(const SkGlyph& glyph, SkPath* path) override { fFace->getPath(glyph, path); path->transform(fMatrix); } void generateFontMetrics(SkPaint::FontMetrics* metrics) override { fFace->getFontMetrics(metrics); if (metrics) { SkScalar scale = fMatrix.getScaleY(); metrics->fTop = SkScalarMul(metrics->fTop, scale); metrics->fAscent = SkScalarMul(metrics->fAscent, scale); metrics->fDescent = SkScalarMul(metrics->fDescent, scale); metrics->fBottom = SkScalarMul(metrics->fBottom, scale); metrics->fLeading = SkScalarMul(metrics->fLeading, scale); metrics->fAvgCharWidth = SkScalarMul(metrics->fAvgCharWidth, scale); metrics->fXMin = SkScalarMul(metrics->fXMin, scale); metrics->fXMax = SkScalarMul(metrics->fXMax, scale); metrics->fXHeight = SkScalarMul(metrics->fXHeight, scale); } } private: SkTestTypeface* fFace; SkMatrix fMatrix; }; SkScalerContext* SkTestTypeface::onCreateScalerContext(const SkDescriptor* desc) const { return SkNEW_ARGS(SkTestScalerContext, (const_cast<SkTestTypeface*>(this), desc)); } <|endoftext|>
<commit_before>/********************************************************************** * * GEOS - Geometry Engine Open Source * http://geos.osgeo.org * * Copyright (C) 2011 Sandro Santilli <strk@kbt.io * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Public Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * ********************************************************************** * * Last port: geom/util/SineStarFactory.java r378 (JTS-1.12) * **********************************************************************/ #include <geos/constants.h> #include <geos/geom/util/SineStarFactory.h> #include <geos/geom/Coordinate.h> #include <geos/geom/CoordinateSequenceFactory.h> #include <geos/geom/CoordinateSequence.h> #include <geos/geom/GeometryFactory.h> #include <geos/geom/Envelope.h> #include <geos/geom/Polygon.h> #include <geos/geom/LinearRing.h> #include <vector> #include <cmath> #include <memory> namespace geos { namespace geom { // geos::geom namespace util { // geos::geom::util /* public */ std::unique_ptr<Polygon> SineStarFactory::createSineStar() const { std::unique_ptr<Envelope> env(dim.getEnvelope()); double radius = env->getWidth() / 2.0; double armRatio = armLengthRatio; if(armRatio < 0.0) { armRatio = 0.0; } if(armRatio > 1.0) { armRatio = 1.0; } double armMaxLen = armRatio * radius; double insideRadius = (1 - armRatio) * radius; double centreX = env->getMinX() + radius; double centreY = env->getMinY() + radius; std::vector<Coordinate> pts(nPts + 1); int iPt = 0; for(int i = 0; i < nPts; i++) { // the fraction of the way thru the current arm - in [0,1] double ptArcFrac = (i / (double) nPts) * numArms; double armAngFrac = ptArcFrac - floor(ptArcFrac); // the angle for the current arm - in [0,2Pi] // (each arm is a complete sine wave cycle) double armAng = 2 * MATH_PI * armAngFrac; // the current length of the arm double armLenFrac = (cos(armAng) + 1.0) / 2.0; // the current radius of the curve (core + arm) double curveRadius = insideRadius + armMaxLen * armLenFrac; // the current angle of the curve double ang = i * (2 * MATH_PI / nPts); double x = curveRadius * cos(ang) + centreX; double y = curveRadius * sin(ang) + centreY; pts[iPt++] = coord(x, y); } pts[iPt] = pts[0]; auto cs = geomFact->getCoordinateSequenceFactory()->create(std::move(pts)); auto ring = geomFact->createLinearRing(std::move(cs)); auto poly = geomFact->createPolygon(std::move(ring)); return poly; } } // namespace geos::geom::util } // namespace geos::geom } // namespace geos <commit_msg>SineStarFactory::createSineStar(): fix compiler warning about signed/unsigned comparison in for() comparison<commit_after>/********************************************************************** * * GEOS - Geometry Engine Open Source * http://geos.osgeo.org * * Copyright (C) 2011 Sandro Santilli <strk@kbt.io * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Public Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * ********************************************************************** * * Last port: geom/util/SineStarFactory.java r378 (JTS-1.12) * **********************************************************************/ #include <geos/constants.h> #include <geos/geom/util/SineStarFactory.h> #include <geos/geom/Coordinate.h> #include <geos/geom/CoordinateSequenceFactory.h> #include <geos/geom/CoordinateSequence.h> #include <geos/geom/GeometryFactory.h> #include <geos/geom/Envelope.h> #include <geos/geom/Polygon.h> #include <geos/geom/LinearRing.h> #include <vector> #include <cmath> #include <memory> namespace geos { namespace geom { // geos::geom namespace util { // geos::geom::util /* public */ std::unique_ptr<Polygon> SineStarFactory::createSineStar() const { std::unique_ptr<Envelope> env(dim.getEnvelope()); double radius = env->getWidth() / 2.0; double armRatio = armLengthRatio; if(armRatio < 0.0) { armRatio = 0.0; } if(armRatio > 1.0) { armRatio = 1.0; } double armMaxLen = armRatio * radius; double insideRadius = (1 - armRatio) * radius; double centreX = env->getMinX() + radius; double centreY = env->getMinY() + radius; std::vector<Coordinate> pts(nPts + 1); uint32_t iPt = 0; for(uint32_t i = 0; i < nPts; i++) { // the fraction of the way thru the current arm - in [0,1] double ptArcFrac = (i / (double) nPts) * numArms; double armAngFrac = ptArcFrac - floor(ptArcFrac); // the angle for the current arm - in [0,2Pi] // (each arm is a complete sine wave cycle) double armAng = 2 * MATH_PI * armAngFrac; // the current length of the arm double armLenFrac = (cos(armAng) + 1.0) / 2.0; // the current radius of the curve (core + arm) double curveRadius = insideRadius + armMaxLen * armLenFrac; // the current angle of the curve double ang = i * (2 * MATH_PI / nPts); double x = curveRadius * cos(ang) + centreX; double y = curveRadius * sin(ang) + centreY; pts[iPt++] = coord(x, y); } pts[iPt] = pts[0]; auto cs = geomFact->getCoordinateSequenceFactory()->create(std::move(pts)); auto ring = geomFact->createLinearRing(std::move(cs)); auto poly = geomFact->createPolygon(std::move(ring)); return poly; } } // namespace geos::geom::util } // namespace geos::geom } // namespace geos <|endoftext|>
<commit_before>/* * This file is part of Clockwork. * * Copyright (c) 2014-2016 Jeremy Othieno. * * The MIT License (MIT) * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef CLOCKWORK_FRAGMENT_HH #define CLOCKWORK_FRAGMENT_HH #include "RenderingAlgorithm.hh" #include "Vector3.hh" #include "ColorARGB.hh" namespace clockwork { namespace detail { /** * */ template<RenderingAlgorithm> struct Fragment { }; } // namespace detail /** * A fragment is the result of a per-vertex operation (vertex shader) applied to * a vertex, which then gets passed to the per-fragment operation (fragment shader). * A fragment contains the vertex's 2D screen space coordinates, depth value, * surface normal and a base color that will all be used to determine values that * will be written to the framebuffer's attachments. */ struct Fragment { /** * Instantiates a Fragment object. */ Fragment(); /** * Estimates the value of a fragment between two specified fragments. */ static Fragment estimate(const Fragment& from, const Fragment& to, const double interpolant); /** * The fragment's screen-space horizontal position. */ std::uint32_t x; /** * The fragment's screen-space vertical position. */ std::uint32_t y; /** * The fragment's depth. */ double z; /** * The fragment's normal vector. */ Vector3 normal; /** * The fragment's texture-space horizontal mapping coordinate. */ double u; /** * The fragment's texture-space vertical mapping coordinate. */ double v; /** * The fragment's color. */ ColorARGB color; /** * The fragment's stencil value. */ std::uint8_t stencil; }; } // namespace clockwork #endif // CLOCKWORK_FRAGMENT_HH <commit_msg>Implement the Fragment template class<commit_after>/* * This file is part of Clockwork. * * Copyright (c) 2014-2016 Jeremy Othieno. * * The MIT License (MIT) * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef CLOCKWORK_FRAGMENT_HH #define CLOCKWORK_FRAGMENT_HH #include "RenderingAlgorithm.hh" #include "Varying.hh" #include "Vector3.hh" #include "ColorARGB.hh" namespace clockwork { namespace detail { /** * */ template<RenderingAlgorithm algorithm> struct Fragment { /** * The fragment's screen-space horizontal position. */ std::uint32_t x; /** * The fragment's screen-space vertical position. */ std::uint32_t y; /** * The fragment's depth. */ double depth; /** * The fragment's stencil value. */ std::uint8_t stencil; /** * The fragment's varying variables. */ Varying<algorithm> varying; }; } // namespace detail #ifdef DEPRECATED /** * A fragment is the result of a per-vertex operation (vertex shader) applied to * a vertex, which then gets passed to the per-fragment operation (fragment shader). * A fragment contains the vertex's 2D screen space coordinates, depth value, * surface normal and a base color that will all be used to determine values that * will be written to the framebuffer's attachments. */ struct Fragment { /** * Instantiates a Fragment object. */ Fragment(); /** * Estimates the value of a fragment between two specified fragments. */ static Fragment estimate(const Fragment& from, const Fragment& to, const double interpolant); /** * The fragment's screen-space horizontal position. */ std::uint32_t x; /** * The fragment's screen-space vertical position. */ std::uint32_t y; /** * The fragment's depth. */ double z; /** * The fragment's normal vector. */ Vector3 normal; /** * The fragment's texture-space horizontal mapping coordinate. */ double u; /** * The fragment's texture-space vertical mapping coordinate. */ double v; /** * The fragment's color. */ ColorARGB color; /** * The fragment's stencil value. */ std::uint8_t stencil; }; #endif } // namespace clockwork #endif // CLOCKWORK_FRAGMENT_HH <|endoftext|>
<commit_before>/* * The MIT License (MIT) * * Copyright (c) 2020 Alexander Chumakov * * 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 "mstring.h" #include "wrap-mocks.h" #include <gtest/gtest.h> using namespace testing; class StringTest : public Test { protected: void SetUp() override { } void TearDown() override { } protected: StrictMock<MHwMockImpl> _mock; }; TEST_F(StringTest, MPutchSimple) { InSequence sequence; EXPECT_CALL(_mock, uart_write_char('a')) .Times(1); EXPECT_CALL(_mock, uart_write_char('b')) .Times(1); EXPECT_CALL(_mock, uart_write_char('c')) .Times(1); mprintstr("abc"); } <commit_msg>Implement more UTs for mstring API<commit_after>/* * The MIT License (MIT) * * Copyright (c) 2020 Alexander Chumakov * * 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 "mstring.h" #include "wrap-mocks.h" #include <gtest/gtest.h> using namespace testing; class StringTest : public Test { protected: void SetUp() override { } void TearDown() override { } protected: StrictMock<MHwMockImpl> _mock; }; TEST_F(StringTest, MPrintStrSimple) { InSequence sequence; EXPECT_CALL(_mock, uart_write_char('a')) .Times(1); EXPECT_CALL(_mock, uart_write_char('b')) .Times(1); EXPECT_CALL(_mock, uart_write_char('c')) .Times(1); mprintstr("abc"); } TEST_F(StringTest, MPrintStrLnSimple) { InSequence sequence; EXPECT_CALL(_mock, uart_write_char('d')).Times(1); EXPECT_CALL(_mock, uart_write_char('e')).Times(1); EXPECT_CALL(_mock, uart_write_char('f')).Times(1); EXPECT_CALL(_mock, uart_write_char('\r')).Times(1); EXPECT_CALL(_mock, uart_write_char('\n')).Times(1); mprintstrln("def"); } TEST_F(StringTest, MPrintBytesSimple) { InSequence sequence; EXPECT_CALL(_mock, uart_write_char('q')).Times(1); EXPECT_CALL(_mock, uart_write_char('w')).Times(1); EXPECT_CALL(_mock, uart_write_char('e')).Times(1); EXPECT_CALL(_mock, uart_write_char('r')).Times(1); mprintbytes("qwer", -1); } TEST_F(StringTest, MPrintBytesLnSimple) { InSequence sequence; EXPECT_CALL(_mock, uart_write_char('p')).Times(1); EXPECT_CALL(_mock, uart_write_char('o')).Times(1); EXPECT_CALL(_mock, uart_write_char('i')).Times(1); EXPECT_CALL(_mock, uart_write_char('u')).Times(1); EXPECT_CALL(_mock, uart_write_char('\r')).Times(1); EXPECT_CALL(_mock, uart_write_char('\n')).Times(1); mprintbytesln("poiu", -1); } TEST_F(StringTest, MPrintBytesWithLength) { InSequence sequence; EXPECT_CALL(_mock, uart_write_char('q')).Times(1); EXPECT_CALL(_mock, uart_write_char('w')).Times(1); mprintbytes("qwer", 2); } TEST_F(StringTest, MPrintBytesLnWithLength) { InSequence sequence; EXPECT_CALL(_mock, uart_write_char('p')).Times(1); EXPECT_CALL(_mock, uart_write_char('o')).Times(1); EXPECT_CALL(_mock, uart_write_char('\r')).Times(1); EXPECT_CALL(_mock, uart_write_char('\n')).Times(1); mprintbytesln("poiu", 2); } <|endoftext|>
<commit_before>/* * Copyright (c) 2010 Eduard Burtescu * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <processor/Processor.h> #include <usb/Usb.h> #include <usb/UsbDevice.h> #include <usb/UsbHub.h> #include <usb/UsbHubDevice.h> #include <usb/UsbHumanInterfaceDevice.h> #include <usb/UsbMassStorageDevice.h> #include <usb/FtdiSerialDevice.h> #include <utilities/ExtensibleBitmap.h> #include <LockGuard.h> void UsbHub::deviceConnected(uint8_t nPort, UsbSpeed speed) { //NOTICE("USB: Adding device on port "<<Dec<<nPort<<Hex<<"..."); // Create a bitmap to hold the used addresses ExtensibleBitmap *pUsedAddresses = new ExtensibleBitmap(); pUsedAddresses->set(0); // Find the root hub UsbHub *pRootHub = this; while(dynamic_cast<UsbHub*>(pRootHub->getParent())) pRootHub = dynamic_cast<UsbHub*>(pRootHub->getParent()); // Fill in the used addresses pRootHub->getUsedAddresses(pUsedAddresses); // Get first unused address and check it uint8_t nAddress = pUsedAddresses->getFirstClear(); if(nAddress > 127) FATAL("USB: HUB: Out of addresses!"); // Create the UsbDevice instance and set us as parent UsbDevice *pDevice = new UsbDevice(); pDevice->setParent(this); // Assign the address we've chosen pDevice->assignAddress(nAddress); // Set port number pDevice->setPort(nPort); // Set speed pDevice->setSpeed(speed); // Get all descriptors in place pDevice->populateDescriptors(); UsbDevice::DeviceDescriptor *pDes = pDevice->getDescriptor(); // Currently we only support the default configuration if(pDes->pConfigurations.count() > 1) NOTICE("USB: TODO: multiple configuration devices"); pDevice->useConfiguration(0); Vector<UsbDevice::Interface*> pInterfaces = pDevice->getConfiguration()->pInterfaces; for(size_t i = 0;i<pInterfaces.count();i++) { UsbDevice::Interface *pInterface = pInterfaces[i]; // Skip alternate settings if(pInterface->pDescriptor->nAlternateSetting) continue; // Just in case we have a single-interface device with the class code(s) in the device descriptor if(pInterfaces.count() == 1 && pDes->pDescriptor->nClass && !pInterface->pDescriptor->nClass) { pInterface->pDescriptor->nClass = pDes->pDescriptor->nClass; pInterface->pDescriptor->nSubclass = pDes->pDescriptor->nSubclass; pInterface->pDescriptor->nProtocol = pDes->pDescriptor->nProtocol; } // If we're not at the first interface, we have to clone the UsbDevice else if(i) { pDevice = new UsbDevice(pDevice); pDevice->setParent(this); } // Set the right interface pDevice->useInterface(i); NOTICE("USB: Device: "<<pDes->sVendor<<" "<<pDes->sProduct<<", class "<<Dec<<pInterface->pDescriptor->nClass<<":"<<pInterface->pDescriptor->nSubclass<<":"<<pInterface->pDescriptor->nProtocol<<Hex); // TODO: make this a bit more general... harcoding some numbers and some class names doesn't sound good :| addChild(pDevice); if(pInterface->pDescriptor->nClass == 9) replaceChild(pDevice, new UsbHubDevice(pDevice)); else if(pInterface->pDescriptor->nClass == 3) replaceChild(pDevice, new UsbHumanInterfaceDevice(pDevice)); else if(pInterface->pDescriptor->nClass == 8) replaceChild(pDevice, new UsbMassStorageDevice(pDevice)); else if(pDes->pDescriptor->nVendorId == 0x0403 && pDes->pDescriptor->nProductId == 0x6001) replaceChild(pDevice, new FtdiSerialDevice(pDevice)); return; } } void UsbHub::deviceDisconnected(uint8_t nPort) { for (size_t i = 0;i < m_Children.count();i++) { UsbDevice *pDevice = dynamic_cast<UsbDevice*>(m_Children[i]); if(pDevice && pDevice->getPort() == nPort) delete pDevice; } } void UsbHub::getUsedAddresses(ExtensibleBitmap *pBitmap) { for (size_t i = 0;i < m_Children.count();i++) { UsbDevice *pDevice = dynamic_cast<UsbDevice*>(m_Children[i]); if(pDevice) pBitmap->set(pDevice->getAddress()); UsbHub *pHub = dynamic_cast<UsbHub*>(m_Children[i]); if(pHub) pHub->getUsedAddresses(pBitmap); } } void UsbHub::syncCallback(uintptr_t pParam, ssize_t ret) { if(!pParam) return; UsbHub *pController = reinterpret_cast<UsbHub*>(pParam); pController->m_SyncRet = ret; pController->m_SyncSemaphore.release(); } ssize_t UsbHub::doSync(UsbEndpoint endpointInfo, uint8_t nPid, uintptr_t pBuffer, size_t nBytes, uint32_t timeout) { LockGuard<Mutex> guard(m_SyncMutex); doAsync(endpointInfo, nPid, pBuffer, nBytes, syncCallback, reinterpret_cast<uintptr_t>(static_cast<UsbHub*>(this))); m_SyncSemaphore.acquire(1);/*, 0, timeout * 1000); if(Processor::information().getCurrentThread()->wasInterrupted()) return -1; else */ return m_SyncRet; } <commit_msg>UsbDevice: Move address assignment after the speed and port number are set up instead of before<commit_after>/* * Copyright (c) 2010 Eduard Burtescu * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <processor/Processor.h> #include <usb/Usb.h> #include <usb/UsbDevice.h> #include <usb/UsbHub.h> #include <usb/UsbHubDevice.h> #include <usb/UsbHumanInterfaceDevice.h> #include <usb/UsbMassStorageDevice.h> #include <usb/FtdiSerialDevice.h> #include <utilities/ExtensibleBitmap.h> #include <LockGuard.h> void UsbHub::deviceConnected(uint8_t nPort, UsbSpeed speed) { //NOTICE("USB: Adding device on port "<<Dec<<nPort<<Hex<<"..."); // Create a bitmap to hold the used addresses ExtensibleBitmap *pUsedAddresses = new ExtensibleBitmap(); pUsedAddresses->set(0); // Find the root hub UsbHub *pRootHub = this; while(dynamic_cast<UsbHub*>(pRootHub->getParent())) pRootHub = dynamic_cast<UsbHub*>(pRootHub->getParent()); // Fill in the used addresses pRootHub->getUsedAddresses(pUsedAddresses); // Get first unused address and check it uint8_t nAddress = pUsedAddresses->getFirstClear(); if(nAddress > 127) FATAL("USB: HUB: Out of addresses!"); // Create the UsbDevice instance and set us as parent UsbDevice *pDevice = new UsbDevice(); pDevice->setParent(this); // Set port number pDevice->setPort(nPort); // Set speed pDevice->setSpeed(speed); // Assign the address we've chosen pDevice->assignAddress(nAddress); // Get all descriptors in place pDevice->populateDescriptors(); UsbDevice::DeviceDescriptor *pDes = pDevice->getDescriptor(); // Currently we only support the default configuration if(pDes->pConfigurations.count() > 1) NOTICE("USB: TODO: multiple configuration devices"); pDevice->useConfiguration(0); Vector<UsbDevice::Interface*> pInterfaces = pDevice->getConfiguration()->pInterfaces; for(size_t i = 0;i<pInterfaces.count();i++) { UsbDevice::Interface *pInterface = pInterfaces[i]; // Skip alternate settings if(pInterface->pDescriptor->nAlternateSetting) continue; // Just in case we have a single-interface device with the class code(s) in the device descriptor if(pInterfaces.count() == 1 && pDes->pDescriptor->nClass && !pInterface->pDescriptor->nClass) { pInterface->pDescriptor->nClass = pDes->pDescriptor->nClass; pInterface->pDescriptor->nSubclass = pDes->pDescriptor->nSubclass; pInterface->pDescriptor->nProtocol = pDes->pDescriptor->nProtocol; } // If we're not at the first interface, we have to clone the UsbDevice else if(i) { pDevice = new UsbDevice(pDevice); pDevice->setParent(this); } // Set the right interface pDevice->useInterface(i); NOTICE("USB: Device: "<<pDes->sVendor<<" "<<pDes->sProduct<<", class "<<Dec<<pInterface->pDescriptor->nClass<<":"<<pInterface->pDescriptor->nSubclass<<":"<<pInterface->pDescriptor->nProtocol<<Hex); // TODO: make this a bit more general... harcoding some numbers and some class names doesn't sound good :| addChild(pDevice); if(pInterface->pDescriptor->nClass == 9) replaceChild(pDevice, new UsbHubDevice(pDevice)); else if(pInterface->pDescriptor->nClass == 3) replaceChild(pDevice, new UsbHumanInterfaceDevice(pDevice)); else if(pInterface->pDescriptor->nClass == 8) replaceChild(pDevice, new UsbMassStorageDevice(pDevice)); else if(pDes->pDescriptor->nVendorId == 0x0403 && pDes->pDescriptor->nProductId == 0x6001) replaceChild(pDevice, new FtdiSerialDevice(pDevice)); return; } } void UsbHub::deviceDisconnected(uint8_t nPort) { for (size_t i = 0;i < m_Children.count();i++) { UsbDevice *pDevice = dynamic_cast<UsbDevice*>(m_Children[i]); if(pDevice && pDevice->getPort() == nPort) delete pDevice; } } void UsbHub::getUsedAddresses(ExtensibleBitmap *pBitmap) { for (size_t i = 0;i < m_Children.count();i++) { UsbDevice *pDevice = dynamic_cast<UsbDevice*>(m_Children[i]); if(pDevice) pBitmap->set(pDevice->getAddress()); UsbHub *pHub = dynamic_cast<UsbHub*>(m_Children[i]); if(pHub) pHub->getUsedAddresses(pBitmap); } } void UsbHub::syncCallback(uintptr_t pParam, ssize_t ret) { if(!pParam) return; UsbHub *pController = reinterpret_cast<UsbHub*>(pParam); pController->m_SyncRet = ret; pController->m_SyncSemaphore.release(); } ssize_t UsbHub::doSync(UsbEndpoint endpointInfo, uint8_t nPid, uintptr_t pBuffer, size_t nBytes, uint32_t timeout) { LockGuard<Mutex> guard(m_SyncMutex); doAsync(endpointInfo, nPid, pBuffer, nBytes, syncCallback, reinterpret_cast<uintptr_t>(static_cast<UsbHub*>(this))); m_SyncSemaphore.acquire(1);/*, 0, timeout * 1000); if(Processor::information().getCurrentThread()->wasInterrupted()) return -1; else */ return m_SyncRet; } <|endoftext|>
<commit_before>/******************************************************************************* * * MIT License * * Copyright (c) 2019 Advanced Micro Devices, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * *******************************************************************************/ #ifndef MIOPEN_GUARD_MLOPEN_ANY_SOLVER_HPP #define MIOPEN_GUARD_MLOPEN_ANY_SOLVER_HPP #include <miopen/conv_solution.hpp> #include <miopen/find_solution.hpp> #include <miopen/mlo_internal.hpp> #include <cassert> #include <memory> #include <typeinfo> namespace miopen { namespace solver { template<typename T> struct TunableSolution { template<typename U> static constexpr auto Test(U*) ->typename std::is_same< decltype(std::declval<U>().GetSolution(std::declval<const ConvolutionContext&>(), std::declval<const decltype(std::declval<U>().GetPerformanceConfig( std::declval<const ConvolutionContext&>()))&>(), std::declval<const bool>())), ConvSolution >::type; template<typename U> static constexpr std::false_type Test(...); using type = decltype(Test<T>(nullptr)); static constexpr bool Has = type::value; }; template <class TSolver> bool StatIsTunable(std::true_type) { return true; } template <class TSolver> bool StatIsTunable(std::false_type) { return false; } struct AnySolver { using Db = decltype(std::declval<mlo_construct_base>().GetDb()); AnySolver() : ptr_value(nullptr){}; template <class U> AnySolver(U src) : ptr_value(new AnySolver_tmpl<U>(std::forward<U>(src))){}; bool IsApplicable(const ConvolutionContext& ctx) const { assert(ptr_value != nullptr); return ptr_value->IsApplicable(ctx); }; bool IsTunable() const { assert(ptr_value != nullptr); return ptr_value->IsTunable(); }; bool IsDynamic() const { assert(ptr_value != nullptr); return ptr_value->IsDynamic(); }; float GetWti(const ConvolutionContext& ctx) const { assert(ptr_value != nullptr); return ptr_value->GetWti(ctx); }; const std::type_info& Type() const { assert(ptr_value != nullptr); return ptr_value->Type(); }; bool IsEmpty() const { return ptr_value == nullptr; }; ConvSolution FindSolution(const ConvolutionContext& ctx, Db& db, const miopen::AnyInvokeParams& invoke_ctx) const { assert(ptr_value != nullptr); return ptr_value->FindSolution(ctx, db, invoke_ctx); }; std::string GetSolverDbId() const { assert(ptr_value != nullptr); return ptr_value->GetSolverDbId(); } size_t GetWorkspaceSize(const ConvolutionContext& ctx) const { assert(ptr_value != nullptr); return ptr_value->GetWorkspaceSize(ctx); } // virtual base class struct AnySolver_base { using ptr = std::shared_ptr<const AnySolver_base>; virtual ~AnySolver_base(){}; virtual bool IsApplicable(const ConvolutionContext& ctx) const = 0; virtual bool IsTunable() const = 0; virtual bool IsDynamic() const = 0; virtual float GetWti(const ConvolutionContext& ctx) const = 0; virtual const std::type_info& Type() const = 0; virtual std::string GetSolverDbId() const = 0; virtual ConvSolution FindSolution(const ConvolutionContext& ctx, Db& db, const miopen::AnyInvokeParams& invoke_ctx) const = 0; virtual size_t GetWorkspaceSize(const ConvolutionContext& ctx) const = 0; }; // templated derived class template <class T> struct AnySolver_tmpl : AnySolver_base { AnySolver_tmpl(T obj) : value(std::move(obj)){}; bool IsApplicable(const ConvolutionContext& ctx) const override { return value.IsApplicable(ctx); } bool IsTunable() const override { return StatIsTunable<T>(std::integral_constant<bool, TunableSolution<T>::Has>()); } bool IsDynamic() const override { return value.IsDynamic(); } float GetWti(const ConvolutionContext& ctx) const override { return value.GetWti(ctx); } ConvSolution FindSolution(const ConvolutionContext& ctx, Db& db, const miopen::AnyInvokeParams& invoke_ctx) const override { return miopen::solver::FindSolution(value, ctx, db, invoke_ctx); }; size_t GetWorkspaceSize(const ConvolutionContext& ctx) const override { return value.GetWorkspaceSize(ctx); } const std::type_info& Type() const override { return typeid(T); }; std::string GetSolverDbId() const override { return ComputeSolverDbId(value); } private: T value; }; AnySolver_base::ptr ptr_value; }; } // namespace solver } // namespace miopen #endif <commit_msg>[TUNA] IsTunable code quality update (#1121)<commit_after>/******************************************************************************* * * MIT License * * Copyright (c) 2019 Advanced Micro Devices, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * *******************************************************************************/ #ifndef MIOPEN_GUARD_MLOPEN_ANY_SOLVER_HPP #define MIOPEN_GUARD_MLOPEN_ANY_SOLVER_HPP #include <miopen/conv_solution.hpp> #include <miopen/find_solution.hpp> #include <miopen/mlo_internal.hpp> #include <cassert> #include <memory> #include <typeinfo> namespace miopen { namespace solver { struct AnySolver { using Db = decltype(std::declval<mlo_construct_base>().GetDb()); AnySolver() : ptr_value(nullptr){}; template <class U> AnySolver(U src) : ptr_value(new AnySolver_tmpl<U>(std::forward<U>(src))){}; bool IsApplicable(const ConvolutionContext& ctx) const { assert(ptr_value != nullptr); return ptr_value->IsApplicable(ctx); }; bool IsTunable() const { assert(ptr_value != nullptr); return ptr_value->IsTunable(); }; bool IsDynamic() const { assert(ptr_value != nullptr); return ptr_value->IsDynamic(); }; float GetWti(const ConvolutionContext& ctx) const { assert(ptr_value != nullptr); return ptr_value->GetWti(ctx); }; const std::type_info& Type() const { assert(ptr_value != nullptr); return ptr_value->Type(); }; bool IsEmpty() const { return ptr_value == nullptr; }; ConvSolution FindSolution(const ConvolutionContext& ctx, Db& db, const miopen::AnyInvokeParams& invoke_ctx) const { assert(ptr_value != nullptr); return ptr_value->FindSolution(ctx, db, invoke_ctx); }; std::string GetSolverDbId() const { assert(ptr_value != nullptr); return ptr_value->GetSolverDbId(); } size_t GetWorkspaceSize(const ConvolutionContext& ctx) const { assert(ptr_value != nullptr); return ptr_value->GetWorkspaceSize(ctx); } // virtual base class struct AnySolver_base { using ptr = std::shared_ptr<const AnySolver_base>; virtual ~AnySolver_base(){}; virtual bool IsApplicable(const ConvolutionContext& ctx) const = 0; virtual bool IsTunable() const = 0; virtual bool IsDynamic() const = 0; virtual float GetWti(const ConvolutionContext& ctx) const = 0; virtual const std::type_info& Type() const = 0; virtual std::string GetSolverDbId() const = 0; virtual ConvSolution FindSolution(const ConvolutionContext& ctx, Db& db, const miopen::AnyInvokeParams& invoke_ctx) const = 0; virtual size_t GetWorkspaceSize(const ConvolutionContext& ctx) const = 0; }; // templated derived class template <class T> struct AnySolver_tmpl : AnySolver_base { struct TunableSolver { template<typename U> static constexpr auto Test(U*) ->typename std::is_same< decltype(std::declval<U>().GetSolution(std::declval<const ConvolutionContext&>(), std::declval<const decltype(std::declval<U>().GetPerformanceConfig( std::declval<const ConvolutionContext&>()))&>(), std::declval<const bool>())), ConvSolution >::type; template<typename U> static constexpr std::false_type Test(...); using type = decltype(Test<T>(nullptr)); static constexpr bool Is = type::value; }; AnySolver_tmpl(T obj) : value(std::move(obj)){}; bool IsApplicable(const ConvolutionContext& ctx) const override { return value.IsApplicable(ctx); } bool IsTunable() const override { return TunableSolver::Is; } bool IsDynamic() const override { return value.IsDynamic(); } float GetWti(const ConvolutionContext& ctx) const override { return value.GetWti(ctx); } ConvSolution FindSolution(const ConvolutionContext& ctx, Db& db, const miopen::AnyInvokeParams& invoke_ctx) const override { return miopen::solver::FindSolution(value, ctx, db, invoke_ctx); }; size_t GetWorkspaceSize(const ConvolutionContext& ctx) const override { return value.GetWorkspaceSize(ctx); } const std::type_info& Type() const override { return typeid(T); }; std::string GetSolverDbId() const override { return ComputeSolverDbId(value); } private: T value; }; AnySolver_base::ptr ptr_value; }; } // namespace solver } // namespace miopen #endif <|endoftext|>
<commit_before>#include "ingameelements/projectile.h" #include "engine.h" #include <cmath> Projectile::Projectile(double id_, Gamestate *state, EntityPtr owner_) : MovingEntity(id_, state), owner(owner_) { entitytype = PROJECTILE; } Projectile::~Projectile() { //dtor } void Projectile::midstep(Gamestate *state, double frametime) { if (isrectangular()) { if (state->currentmap->collides(x, y, getrect(), std::atan2(vspeed, hspeed))) { oncollision(state); } for (auto p : state->playerlist) { // DEBUGTOOL: Replace this check with checking whether p is on enemy team if (p != owner) { Character *c = state->get<Player>(p)->getcharacter(state); if (c != 0) { if (rectcollides(state, state->get<Player>(p)->character, std::atan2(vspeed, hspeed))) { oncollision(state, c); } } } } } } bool Projectile::rectcollides(Gamestate *state, EntityPtr otherentity, double angle) { MovingEntity *m = state->get<MovingEntity>(otherentity); Rect self = state->engine->maskloader.get_rect(getsprite(state, true)).offset(x, y); Rect other = state->engine->maskloader.get_rect(m->getsprite(state, true)).offset(m->x, m->y); double maxdist = std::max(std::hypot(self.w, self.h), std::hypot(other.w, other.h)); if (std::hypot(self.x - other.x, self.y - other.y) <= maxdist) { // We're close enough that an actual collision might happen // Check the sprites ALLEGRO_BITMAP *selfsprite = state->engine->maskloader.requestsprite(getsprite(state, true)); ALLEGRO_BITMAP *othersprite = state->engine->maskloader.requestsprite(m->getsprite(state, true)); double cosa = std::cos(angle); double sina = std::sin(angle); double tmpx, tmpy; for (int i=0; i<self.w; ++i) { for (int j=0; j<self.h; ++j) { tmpx = self.x + cosa*(self.x-x+i) - sina*(self.y-y+j); tmpy = self.y + sina*(self.x-x+i) + cosa*(self.y-y+j); if (al_get_pixel(selfsprite, i, j).a != 0 and al_get_pixel(othersprite, tmpx - other.x, tmpy - other.y).a != 0) { return true; } } } } return false; } bool Projectile::circlecollides(Gamestate *state, EntityPtr otherentity, double radius) { MovingEntity *m = state->get<MovingEntity>(otherentity); Rect other = state->engine->maskloader.get_rect(m->getsprite(state, true)).offset(m->x, m->y); if (std::hypot(x - other.x, y - other.y) <= radius + std::hypot(other.w, other.h)) { // We're close enough that an actual collision might happen // Check the sprites double r2 = radius*radius; ALLEGRO_BITMAP *othersprite = state->engine->maskloader.requestsprite(m->getsprite(state, true)); for (int i=-radius; i<radius; ++i) { for (int j=-radius; j<radius; ++j) { if (i*i+j*j <= r2 and al_get_pixel(othersprite, x+i - other.x, y+j - other.y).a != 0) { return true; } } } } return false; } void Projectile::oncollision(Gamestate *state, Character *c) { // Collided with player c->damage(state, damage()); destroy(state); } void Projectile::oncollision(Gamestate *state) { // Collided with wallmask destroy(state); } <commit_msg>Made sure bullets disappeared when damaging someone.<commit_after>#include "ingameelements/projectile.h" #include "engine.h" #include <cmath> Projectile::Projectile(double id_, Gamestate *state, EntityPtr owner_) : MovingEntity(id_, state), owner(owner_) { entitytype = PROJECTILE; } Projectile::~Projectile() { //dtor } void Projectile::midstep(Gamestate *state, double frametime) { if (isrectangular()) { if (state->currentmap->collides(x, y, getrect(), std::atan2(vspeed, hspeed))) { oncollision(state); } for (auto p : state->playerlist) { // DEBUGTOOL: Replace this check with checking whether p is on enemy team if (p != owner) { Character *c = state->get<Player>(p)->getcharacter(state); if (c != 0) { if (rectcollides(state, state->get<Player>(p)->character, std::atan2(vspeed, hspeed))) { oncollision(state, c); break; } } } } } } bool Projectile::rectcollides(Gamestate *state, EntityPtr otherentity, double angle) { MovingEntity *m = state->get<MovingEntity>(otherentity); Rect self = state->engine->maskloader.get_rect(getsprite(state, true)).offset(x, y); Rect other = state->engine->maskloader.get_rect(m->getsprite(state, true)).offset(m->x, m->y); double maxdist = std::max(std::hypot(self.w, self.h), std::hypot(other.w, other.h)); if (std::hypot(self.x - other.x, self.y - other.y) <= maxdist) { // We're close enough that an actual collision might happen // Check the sprites ALLEGRO_BITMAP *selfsprite = state->engine->maskloader.requestsprite(getsprite(state, true)); ALLEGRO_BITMAP *othersprite = state->engine->maskloader.requestsprite(m->getsprite(state, true)); double cosa = std::cos(angle); double sina = std::sin(angle); double tmpx, tmpy; for (int i=0; i<self.w; ++i) { for (int j=0; j<self.h; ++j) { tmpx = self.x + cosa*(self.x-x+i) - sina*(self.y-y+j); tmpy = self.y + sina*(self.x-x+i) + cosa*(self.y-y+j); if (al_get_pixel(selfsprite, i, j).a != 0 and al_get_pixel(othersprite, tmpx - other.x, tmpy - other.y).a != 0) { return true; } } } } return false; } bool Projectile::circlecollides(Gamestate *state, EntityPtr otherentity, double radius) { MovingEntity *m = state->get<MovingEntity>(otherentity); Rect other = state->engine->maskloader.get_rect(m->getsprite(state, true)).offset(m->x, m->y); if (std::hypot(x - other.x, y - other.y) <= radius + std::hypot(other.w, other.h)) { // We're close enough that an actual collision might happen // Check the sprites double r2 = radius*radius; ALLEGRO_BITMAP *othersprite = state->engine->maskloader.requestsprite(m->getsprite(state, true)); for (int i=-radius; i<radius; ++i) { for (int j=-radius; j<radius; ++j) { if (i*i+j*j <= r2 and al_get_pixel(othersprite, x+i - other.x, y+j - other.y).a != 0) { return true; } } } } return false; } void Projectile::oncollision(Gamestate *state, Character *c) { // Collided with player c->damage(state, damage()); destroy(state); } void Projectile::oncollision(Gamestate *state) { // Collided with wallmask destroy(state); } <|endoftext|>
<commit_before>// This code is in the public domain -- castanyo@yahoo.es #include <nvmath/SphericalHarmonic.h> using namespace nv; namespace { // Basic integer factorial. inline static int factorial( int v ) { if (v == 0) { return 1; } int result = v; while (--v > 0) { result *= v; } return result; } // Double factorial. // Defined as: n!! = n*(n - 2)*(n - 4)..., n!!(0,-1) = 1. inline static int doubleFactorial( int x ) { if (x == 0 || x == -1) { return 1; } int result = x; while ((x -= 2) > 0) { result *= x; } return result; } /// Normalization constant for spherical harmonic. /// @param l is the band. /// @param m is the argument, in the range [0, m] inline static float K( int l, int m ) { nvDebugCheck( m >= 0 ); return sqrtf(((2 * l + 1) * factorial(l - m)) / (4 * PI * factorial(l + m))); } /// Normalization constant for hemispherical harmonic. inline static float HK( int l, int m ) { nvDebugCheck( m >= 0 ); return sqrtf(((2 * l + 1) * factorial(l - m)) / (2 * PI * factorial(l + m))); } /// Evaluate Legendre polynomial. */ static float legendre( int l, int m, float x ) { // piDebugCheck( m >= 0 ); // piDebugCheck( m <= l ); // piDebugCheck( fabs(x) <= 1 ); // Rule 2 needs no previous results if (l == m) { return powf(-1.0f, float(m)) * doubleFactorial(2 * m - 1) * powf(1 - x*x, 0.5f * m); } // Rule 3 requires the result for the same argument of the previous band if (l == m + 1) { return x * (2 * m + 1) * legendrePolynomial(m, m, x); } // Main reccurence used by rule 1 that uses result of the same argument from // the previous two bands return (x * (2 * l - 1) * legendrePolynomial(l - 1, m, x) - (l + m - 1) * legendrePolynomial(l - 2, m, x)) / (l - m); } template <int l, int m> float legendre(float x); template <> float legendre<0, 0>(float x) { return 1; } template <> float legendre<1, 0>(float x) { return x; } template <> float legendre<1, 1>(float x) { return -sqrtf(1 - x * x); } template <> float legendre<2, 0>(float x) { return -0.5f + (3 * x * x) / 2; } template <> float legendre<2, 1>(float x) { return -3 * x * sqrtf(1 - x * x); } template <> float legendre<2, 2>(float x) { return -3 * (-1 + x * x); } template <> float legendre<3, 0>(float x) { return -(3 * x) / 2 + (5 * x * x * x) / 2; } template <> float legendre<3, 1>(float x) { return -3 * sqrtf(1 - x * x) / 2 * (-1 + 5 * x * x); } template <> float legendre<3, 2>(float x) { return -15 * (-x + x * x * x); } template <> float legendre<3, 3>(float x) { return -15 * powf(1 - x * x, 1.5f); } template <> float legendre<4, 0>(float x) { return 0.125f * (3.0f - 30.0f * x * x + 35.0f * x * x * x * x); } template <> float legendre<4, 1>(float x) { return -2.5f * x * sqrtf(1.0f - x * x) * (7.0f * x * x - 3.0f); } template <> float legendre<4, 2>(float x) { return -7.5f * (1.0f - 8.0f * x * x + 7.0f * x * x * x * x); } template <> float legendre<4, 3>(float x) { return -105.0f * x * powf(1 - x * x, 1.5f); } template <> float legendre<4, 4>(float x) { return 105.0f * (x * x - 1.0f) * (x * x - 1.0f); } } // namespace float nv::legendrePolynomial(int l, int m, float x) { switch(l) { case 0: return legendre<0, 0>(x); case 1: if(m == 0) return legendre<1, 0>(x); return legendre<1, 1>(x); case 2: if(m == 0) return legendre<2, 0>(x); else if(m == 1) return legendre<2, 1>(x); return legendre<2, 2>(x); case 3: if(m == 0) return legendre<3, 0>(x); else if(m == 1) return legendre<3, 1>(x); else if(m == 2) return legendre<3, 2>(x); return legendre<3, 3>(x); case 4: if(m == 0) return legendre<4, 0>(x); else if(m == 1) return legendre<4, 1>(x); else if(m == 2) return legendre<4, 2>(x); else if(m == 3) return legendre<4, 3>(x); else return legendre<4, 4>(x); } // Fallback to the expensive version. return legendre(l, m, x); } /** * Evaluate the spherical harmonic function for the given angles. * @param l is the band. * @param m is the argument, in the range [-l,l] * @param theta is the altitude, in the range [0, PI] * @param phi is the azimuth, in the range [0, 2*PI] */ float nv::y( int l, int m, float theta, float phi ) { if( m == 0 ) { // K(l, 0) = sqrt((2*l+1)/(4*PI)) return sqrtf((2 * l + 1) / (4 * PI)) * legendrePolynomial(l, 0, cosf(theta)); } else if( m > 0 ) { return sqrtf(2.0f) * K(l, m) * cosf(m * phi) * legendrePolynomial(l, m, cosf(theta)); } else { return sqrtf(2.0f) * K(l, -m) * sinf(-m * phi) * legendrePolynomial(l, -m, cosf(theta)); } } /** * Real spherical harmonic function of an unit vector. Uses the following * equalities to call the angular function: * x = sin(theta)*cos(phi) * y = sin(theta)*sin(phi) * z = cos(theta) */ float nv::y( int l, int m, Vector3::Arg v ) { float theta = acosf(v.z()); float phi = atan2f(v.y(), v.x()); return y( l, m, theta, phi ); } /** * Evaluate the hemispherical harmonic function for the given angles. * @param l is the band. * @param m is the argument, in the range [-l,l] * @param theta is the altitude, in the range [0, PI/2] * @param phi is the azimuth, in the range [0, 2*PI] */ float nv::hy( int l, int m, float theta, float phi ) { if( m == 0 ) { // HK(l, 0) = sqrt((2*l+1)/(2*PI)) return sqrtf((2 * l + 1) / (2 * PI)) * legendrePolynomial(l, 0, 2*cosf(theta)-1); } else if( m > 0 ) { return sqrtf(2.0f) * HK(l, m) * cosf(m * phi) * legendrePolynomial(l, m, 2*cosf(theta)-1); } else { return sqrtf(2.0f) * HK(l, -m) * sinf(-m * phi) * legendrePolynomial(l, -m, 2*cosf(theta)-1); } } /** * Real hemispherical harmonic function of an unit vector. Uses the following * equalities to call the angular function: * x = sin(theta)*cos(phi) * y = sin(theta)*sin(phi) * z = cos(theta) */ float nv::hy( int l, int m, Vector3::Arg v ) { float theta = acosf(v.z()); float phi = atan2f(v.y(), v.x()); return y( l, m, theta, phi ); } <commit_msg>factorial optimization suggested by pponywong.<commit_after>// This code is in the public domain -- castanyo@yahoo.es #include <nvmath/SphericalHarmonic.h> using namespace nv; namespace { // Basic integer factorial. inline static int factorial( int v ) { const static int fac_table[] = { 1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800 }; if(v <= 11){ return fac_table[v]; } int result = v; while (--v > 0) { result *= v; } return result; } // Double factorial. // Defined as: n!! = n*(n - 2)*(n - 4)..., n!!(0,-1) = 1. inline static int doubleFactorial( int x ) { if (x == 0 || x == -1) { return 1; } int result = x; while ((x -= 2) > 0) { result *= x; } return result; } /// Normalization constant for spherical harmonic. /// @param l is the band. /// @param m is the argument, in the range [0, m] inline static float K( int l, int m ) { nvDebugCheck( m >= 0 ); return sqrtf(((2 * l + 1) * factorial(l - m)) / (4 * PI * factorial(l + m))); } /// Normalization constant for hemispherical harmonic. inline static float HK( int l, int m ) { nvDebugCheck( m >= 0 ); return sqrtf(((2 * l + 1) * factorial(l - m)) / (2 * PI * factorial(l + m))); } /// Evaluate Legendre polynomial. */ static float legendre( int l, int m, float x ) { // piDebugCheck( m >= 0 ); // piDebugCheck( m <= l ); // piDebugCheck( fabs(x) <= 1 ); // Rule 2 needs no previous results if (l == m) { return powf(-1.0f, float(m)) * doubleFactorial(2 * m - 1) * powf(1 - x*x, 0.5f * m); } // Rule 3 requires the result for the same argument of the previous band if (l == m + 1) { return x * (2 * m + 1) * legendrePolynomial(m, m, x); } // Main reccurence used by rule 1 that uses result of the same argument from // the previous two bands return (x * (2 * l - 1) * legendrePolynomial(l - 1, m, x) - (l + m - 1) * legendrePolynomial(l - 2, m, x)) / (l - m); } template <int l, int m> float legendre(float x); template <> float legendre<0, 0>(float x) { return 1; } template <> float legendre<1, 0>(float x) { return x; } template <> float legendre<1, 1>(float x) { return -sqrtf(1 - x * x); } template <> float legendre<2, 0>(float x) { return -0.5f + (3 * x * x) / 2; } template <> float legendre<2, 1>(float x) { return -3 * x * sqrtf(1 - x * x); } template <> float legendre<2, 2>(float x) { return -3 * (-1 + x * x); } template <> float legendre<3, 0>(float x) { return -(3 * x) / 2 + (5 * x * x * x) / 2; } template <> float legendre<3, 1>(float x) { return -3 * sqrtf(1 - x * x) / 2 * (-1 + 5 * x * x); } template <> float legendre<3, 2>(float x) { return -15 * (-x + x * x * x); } template <> float legendre<3, 3>(float x) { return -15 * powf(1 - x * x, 1.5f); } template <> float legendre<4, 0>(float x) { return 0.125f * (3.0f - 30.0f * x * x + 35.0f * x * x * x * x); } template <> float legendre<4, 1>(float x) { return -2.5f * x * sqrtf(1.0f - x * x) * (7.0f * x * x - 3.0f); } template <> float legendre<4, 2>(float x) { return -7.5f * (1.0f - 8.0f * x * x + 7.0f * x * x * x * x); } template <> float legendre<4, 3>(float x) { return -105.0f * x * powf(1 - x * x, 1.5f); } template <> float legendre<4, 4>(float x) { return 105.0f * (x * x - 1.0f) * (x * x - 1.0f); } } // namespace float nv::legendrePolynomial(int l, int m, float x) { switch(l) { case 0: return legendre<0, 0>(x); case 1: if(m == 0) return legendre<1, 0>(x); return legendre<1, 1>(x); case 2: if(m == 0) return legendre<2, 0>(x); else if(m == 1) return legendre<2, 1>(x); return legendre<2, 2>(x); case 3: if(m == 0) return legendre<3, 0>(x); else if(m == 1) return legendre<3, 1>(x); else if(m == 2) return legendre<3, 2>(x); return legendre<3, 3>(x); case 4: if(m == 0) return legendre<4, 0>(x); else if(m == 1) return legendre<4, 1>(x); else if(m == 2) return legendre<4, 2>(x); else if(m == 3) return legendre<4, 3>(x); else return legendre<4, 4>(x); } // Fallback to the expensive version. return legendre(l, m, x); } /** * Evaluate the spherical harmonic function for the given angles. * @param l is the band. * @param m is the argument, in the range [-l,l] * @param theta is the altitude, in the range [0, PI] * @param phi is the azimuth, in the range [0, 2*PI] */ float nv::y( int l, int m, float theta, float phi ) { if( m == 0 ) { // K(l, 0) = sqrt((2*l+1)/(4*PI)) return sqrtf((2 * l + 1) / (4 * PI)) * legendrePolynomial(l, 0, cosf(theta)); } else if( m > 0 ) { return sqrtf(2.0f) * K(l, m) * cosf(m * phi) * legendrePolynomial(l, m, cosf(theta)); } else { return sqrtf(2.0f) * K(l, -m) * sinf(-m * phi) * legendrePolynomial(l, -m, cosf(theta)); } } /** * Real spherical harmonic function of an unit vector. Uses the following * equalities to call the angular function: * x = sin(theta)*cos(phi) * y = sin(theta)*sin(phi) * z = cos(theta) */ float nv::y( int l, int m, Vector3::Arg v ) { float theta = acosf(v.z()); float phi = atan2f(v.y(), v.x()); return y( l, m, theta, phi ); } /** * Evaluate the hemispherical harmonic function for the given angles. * @param l is the band. * @param m is the argument, in the range [-l,l] * @param theta is the altitude, in the range [0, PI/2] * @param phi is the azimuth, in the range [0, 2*PI] */ float nv::hy( int l, int m, float theta, float phi ) { if( m == 0 ) { // HK(l, 0) = sqrt((2*l+1)/(2*PI)) return sqrtf((2 * l + 1) / (2 * PI)) * legendrePolynomial(l, 0, 2*cosf(theta)-1); } else if( m > 0 ) { return sqrtf(2.0f) * HK(l, m) * cosf(m * phi) * legendrePolynomial(l, m, 2*cosf(theta)-1); } else { return sqrtf(2.0f) * HK(l, -m) * sinf(-m * phi) * legendrePolynomial(l, -m, 2*cosf(theta)-1); } } /** * Real hemispherical harmonic function of an unit vector. Uses the following * equalities to call the angular function: * x = sin(theta)*cos(phi) * y = sin(theta)*sin(phi) * z = cos(theta) */ float nv::hy( int l, int m, Vector3::Arg v ) { float theta = acosf(v.z()); float phi = atan2f(v.y(), v.x()); return y( l, m, theta, phi ); } <|endoftext|>
<commit_before> /* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #define WIN32_LEAN_AND_MEAN #include <Windows.h> #include <wincodec.h> #include "SkAutoCoInitialize.h" #include "SkImageDecoder.h" #include "SkImageEncoder.h" #include "SkIStream.h" #include "SkMovie.h" #include "SkStream.h" #include "SkTScopedComPtr.h" class SkImageDecoder_WIC : public SkImageDecoder { protected: virtual bool onDecode(SkStream* stream, SkBitmap* bm, Mode mode); }; bool SkImageDecoder_WIC::onDecode(SkStream* stream, SkBitmap* bm, Mode mode) { //Initialize COM. AutoCoInitialize scopedCo; HRESULT hr = scopedCo.getHR(); //Create Windows Imaging Component ImagingFactory. SkTScopedComPtr<IWICImagingFactory> piImagingFactory; if (SUCCEEDED(hr)) { hr = CoCreateInstance( CLSID_WICImagingFactory , NULL , CLSCTX_INPROC_SERVER , IID_PPV_ARGS(&piImagingFactory) ); } //Convert SkStream to IStream. SkTScopedComPtr<IStream> piStream; if (SUCCEEDED(hr)) { hr = SkIStream::CreateFromSkStream(stream, false, &piStream); } //Make sure we're at the beginning of the stream. if (SUCCEEDED(hr)) { LARGE_INTEGER liBeginning = { 0 }; hr = piStream->Seek(liBeginning, STREAM_SEEK_SET, NULL); } //Create the decoder from the stream content. SkTScopedComPtr<IWICBitmapDecoder> piBitmapDecoder; if (SUCCEEDED(hr)) { hr = piImagingFactory->CreateDecoderFromStream( piStream.get() //Image to be decoded , NULL //No particular vendor , WICDecodeMetadataCacheOnDemand //Cache metadata when needed , &piBitmapDecoder //Pointer to the decoder ); } //Get the first frame from the decoder. SkTScopedComPtr<IWICBitmapFrameDecode> piBitmapFrameDecode; if (SUCCEEDED(hr)) { hr = piBitmapDecoder->GetFrame(0, &piBitmapFrameDecode); } //Get the BitmapSource interface of the frame. SkTScopedComPtr<IWICBitmapSource> piBitmapSourceOriginal; if (SUCCEEDED(hr)) { hr = piBitmapFrameDecode->QueryInterface( IID_PPV_ARGS(&piBitmapSourceOriginal) ); } //Get the size of the bitmap. UINT width; UINT height; if (SUCCEEDED(hr)) { hr = piBitmapSourceOriginal->GetSize(&width, &height); } //Exit early if we're only looking for the bitmap bounds. if (SUCCEEDED(hr)) { bm->setConfig(SkBitmap::kARGB_8888_Config, width, height); if (SkImageDecoder::kDecodeBounds_Mode == mode) { return true; } if (!this->allocPixelRef(bm, NULL)) { return false; } } //Create a format converter. SkTScopedComPtr<IWICFormatConverter> piFormatConverter; if (SUCCEEDED(hr)) { hr = piImagingFactory->CreateFormatConverter(&piFormatConverter); } if (SUCCEEDED(hr)) { hr = piFormatConverter->Initialize( piBitmapSourceOriginal.get() //Input bitmap to convert , GUID_WICPixelFormat32bppPBGRA //Destination pixel format , WICBitmapDitherTypeNone //Specified dither patterm , NULL //Specify a particular palette , 0.f //Alpha threshold , WICBitmapPaletteTypeCustom //Palette translation type ); } //Get the BitmapSource interface of the format converter. SkTScopedComPtr<IWICBitmapSource> piBitmapSourceConverted; if (SUCCEEDED(hr)) { hr = piFormatConverter->QueryInterface( IID_PPV_ARGS(&piBitmapSourceConverted) ); } //Copy the pixels into the bitmap. if (SUCCEEDED(hr)) { bm->lockPixels(); bm->eraseColor(0); const int stride = bm->rowBytes(); hr = piBitmapSourceConverted->CopyPixels( NULL, //Get all the pixels stride, stride * height, reinterpret_cast<BYTE *>(bm->getPixels()) ); bm->unlockPixels(); } return SUCCEEDED(hr); } ///////////////////////////////////////////////////////////////////////// SkImageDecoder* SkImageDecoder::Factory(SkStream* stream) { return SkNEW(SkImageDecoder_WIC); } ///////////////////////////////////////////////////////////////////////// SkMovie* SkMovie::DecodeStream(SkStream* stream) { return NULL; } ///////////////////////////////////////////////////////////////////////// class SkImageEncoder_WIC : public SkImageEncoder { public: SkImageEncoder_WIC(Type t) : fType(t) {} protected: virtual bool onEncode(SkWStream* stream, const SkBitmap& bm, int quality); private: Type fType; }; bool SkImageEncoder_WIC::onEncode(SkWStream* stream , const SkBitmap& bm , int quality) { GUID type; switch (fType) { case kJPEG_Type: type = GUID_ContainerFormatJpeg; break; case kPNG_Type: type = GUID_ContainerFormatPng; break; default: return false; } //Initialize COM. AutoCoInitialize scopedCo; HRESULT hr = scopedCo.getHR(); //Create Windows Imaging Component ImagingFactory. SkTScopedComPtr<IWICImagingFactory> piImagingFactory; if (SUCCEEDED(hr)) { hr = CoCreateInstance( CLSID_WICImagingFactory , NULL , CLSCTX_INPROC_SERVER , IID_PPV_ARGS(&piImagingFactory) ); } //Convert the SkWStream to an IStream. SkTScopedComPtr<IStream> piStream; if (SUCCEEDED(hr)) { hr = SkWIStream::CreateFromSkWStream(stream, &piStream); } //Create an encode of the appropriate type. SkTScopedComPtr<IWICBitmapEncoder> piEncoder; if (SUCCEEDED(hr)) { hr = piImagingFactory->CreateEncoder(type, NULL, &piEncoder); } if (SUCCEEDED(hr)) { hr = piEncoder->Initialize(piStream.get(), WICBitmapEncoderNoCache); } //Create a the frame. SkTScopedComPtr<IWICBitmapFrameEncode> piBitmapFrameEncode; SkTScopedComPtr<IPropertyBag2> piPropertybag; if (SUCCEEDED(hr)) { hr = piEncoder->CreateNewFrame(&piBitmapFrameEncode, &piPropertybag); } if (SUCCEEDED(hr)) { PROPBAG2 name = { 0 }; name.dwType = PROPBAG2_TYPE_DATA; name.vt = VT_R4; name.pstrName = L"ImageQuality"; VARIANT value; VariantInit(&value); value.vt = VT_R4; value.fltVal = (FLOAT)(quality / 100.0); //Ignore result code. // This returns E_FAIL if the named property is not in the bag. //TODO(bungeman) enumerate the properties, // write and set hr iff property exists. piPropertybag->Write(1, &name, &value); } if (SUCCEEDED(hr)) { hr = piBitmapFrameEncode->Initialize(piPropertybag.get()); } //Set the size of the frame. const UINT width = bm.width(); const UINT height = bm.height(); if (SUCCEEDED(hr)) { hr = piBitmapFrameEncode->SetSize(width, height); } //Set the pixel format of the frame. const WICPixelFormatGUID formatDesired = GUID_WICPixelFormat32bppBGRA; WICPixelFormatGUID formatGUID = formatDesired; if (SUCCEEDED(hr)) { hr = piBitmapFrameEncode->SetPixelFormat(&formatGUID); } if (SUCCEEDED(hr)) { //Be sure the image format is the one requested. hr = IsEqualGUID(formatGUID, formatDesired) ? S_OK : E_FAIL; } //Write the pixels into the frame. if (SUCCEEDED(hr)) { hr = piBitmapFrameEncode->WritePixels( height , bm.rowBytes() , bm.rowBytes()*height , reinterpret_cast<BYTE*>(bm.getPixels())); } if (SUCCEEDED(hr)) { hr = piBitmapFrameEncode->Commit(); } if (SUCCEEDED(hr)) { hr = piEncoder->Commit(); } return SUCCEEDED(hr); } SkImageEncoder* SkImageEncoder::Create(Type t) { switch (t) { case kJPEG_Type: case kPNG_Type: break; default: return NULL; } return SkNEW_ARGS(SkImageEncoder_WIC, (t)); } <commit_msg>Windows image decoder should handle all bitmap formats. http://codereview.appspot.com/4801070/<commit_after> /* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #define WIN32_LEAN_AND_MEAN #include <Windows.h> #include <wincodec.h> #include "SkAutoCoInitialize.h" #include "SkImageDecoder.h" #include "SkImageEncoder.h" #include "SkIStream.h" #include "SkMovie.h" #include "SkStream.h" #include "SkTScopedComPtr.h" class SkImageDecoder_WIC : public SkImageDecoder { protected: virtual bool onDecode(SkStream* stream, SkBitmap* bm, Mode mode); }; bool SkImageDecoder_WIC::onDecode(SkStream* stream, SkBitmap* bm, Mode mode) { //Initialize COM. AutoCoInitialize scopedCo; HRESULT hr = scopedCo.getHR(); //Create Windows Imaging Component ImagingFactory. SkTScopedComPtr<IWICImagingFactory> piImagingFactory; if (SUCCEEDED(hr)) { hr = CoCreateInstance( CLSID_WICImagingFactory , NULL , CLSCTX_INPROC_SERVER , IID_PPV_ARGS(&piImagingFactory) ); } //Convert SkStream to IStream. SkTScopedComPtr<IStream> piStream; if (SUCCEEDED(hr)) { hr = SkIStream::CreateFromSkStream(stream, false, &piStream); } //Make sure we're at the beginning of the stream. if (SUCCEEDED(hr)) { LARGE_INTEGER liBeginning = { 0 }; hr = piStream->Seek(liBeginning, STREAM_SEEK_SET, NULL); } //Create the decoder from the stream content. SkTScopedComPtr<IWICBitmapDecoder> piBitmapDecoder; if (SUCCEEDED(hr)) { hr = piImagingFactory->CreateDecoderFromStream( piStream.get() //Image to be decoded , NULL //No particular vendor , WICDecodeMetadataCacheOnDemand //Cache metadata when needed , &piBitmapDecoder //Pointer to the decoder ); } //Get the first frame from the decoder. SkTScopedComPtr<IWICBitmapFrameDecode> piBitmapFrameDecode; if (SUCCEEDED(hr)) { hr = piBitmapDecoder->GetFrame(0, &piBitmapFrameDecode); } //Get the BitmapSource interface of the frame. SkTScopedComPtr<IWICBitmapSource> piBitmapSourceOriginal; if (SUCCEEDED(hr)) { hr = piBitmapFrameDecode->QueryInterface( IID_PPV_ARGS(&piBitmapSourceOriginal) ); } //Get the size of the bitmap. UINT width; UINT height; if (SUCCEEDED(hr)) { hr = piBitmapSourceOriginal->GetSize(&width, &height); } //Exit early if we're only looking for the bitmap bounds. if (SUCCEEDED(hr)) { bm->setConfig(SkBitmap::kARGB_8888_Config, width, height); if (SkImageDecoder::kDecodeBounds_Mode == mode) { return true; } if (!this->allocPixelRef(bm, NULL)) { return false; } } //Create a format converter. SkTScopedComPtr<IWICFormatConverter> piFormatConverter; if (SUCCEEDED(hr)) { hr = piImagingFactory->CreateFormatConverter(&piFormatConverter); } if (SUCCEEDED(hr)) { hr = piFormatConverter->Initialize( piBitmapSourceOriginal.get() //Input bitmap to convert , GUID_WICPixelFormat32bppPBGRA //Destination pixel format , WICBitmapDitherTypeNone //Specified dither patterm , NULL //Specify a particular palette , 0.f //Alpha threshold , WICBitmapPaletteTypeCustom //Palette translation type ); } //Get the BitmapSource interface of the format converter. SkTScopedComPtr<IWICBitmapSource> piBitmapSourceConverted; if (SUCCEEDED(hr)) { hr = piFormatConverter->QueryInterface( IID_PPV_ARGS(&piBitmapSourceConverted) ); } //Copy the pixels into the bitmap. if (SUCCEEDED(hr)) { bm->lockPixels(); bm->eraseColor(0); const int stride = bm->rowBytes(); hr = piBitmapSourceConverted->CopyPixels( NULL, //Get all the pixels stride, stride * height, reinterpret_cast<BYTE *>(bm->getPixels()) ); bm->unlockPixels(); } return SUCCEEDED(hr); } ///////////////////////////////////////////////////////////////////////// SkImageDecoder* SkImageDecoder::Factory(SkStream* stream) { return SkNEW(SkImageDecoder_WIC); } ///////////////////////////////////////////////////////////////////////// SkMovie* SkMovie::DecodeStream(SkStream* stream) { return NULL; } ///////////////////////////////////////////////////////////////////////// class SkImageEncoder_WIC : public SkImageEncoder { public: SkImageEncoder_WIC(Type t) : fType(t) {} protected: virtual bool onEncode(SkWStream* stream, const SkBitmap& bm, int quality); private: Type fType; }; bool SkImageEncoder_WIC::onEncode(SkWStream* stream , const SkBitmap& bitmapOrig , int quality) { GUID type; switch (fType) { case kJPEG_Type: type = GUID_ContainerFormatJpeg; break; case kPNG_Type: type = GUID_ContainerFormatPng; break; default: return false; } //Convert to 8888 if needed. const SkBitmap* bitmap; SkBitmap bitmapCopy; if (SkBitmap::kARGB_8888_Config == bitmapOrig.config()) { bitmap = &bitmapOrig; } else { if (!bitmapOrig.copyTo(&bitmapCopy, SkBitmap::kARGB_8888_Config)) { return false; } bitmap = &bitmapCopy; } //Initialize COM. AutoCoInitialize scopedCo; HRESULT hr = scopedCo.getHR(); //Create Windows Imaging Component ImagingFactory. SkTScopedComPtr<IWICImagingFactory> piImagingFactory; if (SUCCEEDED(hr)) { hr = CoCreateInstance( CLSID_WICImagingFactory , NULL , CLSCTX_INPROC_SERVER , IID_PPV_ARGS(&piImagingFactory) ); } //Convert the SkWStream to an IStream. SkTScopedComPtr<IStream> piStream; if (SUCCEEDED(hr)) { hr = SkWIStream::CreateFromSkWStream(stream, &piStream); } //Create an encode of the appropriate type. SkTScopedComPtr<IWICBitmapEncoder> piEncoder; if (SUCCEEDED(hr)) { hr = piImagingFactory->CreateEncoder(type, NULL, &piEncoder); } if (SUCCEEDED(hr)) { hr = piEncoder->Initialize(piStream.get(), WICBitmapEncoderNoCache); } //Create a the frame. SkTScopedComPtr<IWICBitmapFrameEncode> piBitmapFrameEncode; SkTScopedComPtr<IPropertyBag2> piPropertybag; if (SUCCEEDED(hr)) { hr = piEncoder->CreateNewFrame(&piBitmapFrameEncode, &piPropertybag); } if (SUCCEEDED(hr)) { PROPBAG2 name = { 0 }; name.dwType = PROPBAG2_TYPE_DATA; name.vt = VT_R4; name.pstrName = L"ImageQuality"; VARIANT value; VariantInit(&value); value.vt = VT_R4; value.fltVal = (FLOAT)(quality / 100.0); //Ignore result code. // This returns E_FAIL if the named property is not in the bag. //TODO(bungeman) enumerate the properties, // write and set hr iff property exists. piPropertybag->Write(1, &name, &value); } if (SUCCEEDED(hr)) { hr = piBitmapFrameEncode->Initialize(piPropertybag.get()); } //Set the size of the frame. const UINT width = bitmap->width(); const UINT height = bitmap->height(); if (SUCCEEDED(hr)) { hr = piBitmapFrameEncode->SetSize(width, height); } //Set the pixel format of the frame. const WICPixelFormatGUID formatDesired = GUID_WICPixelFormat32bppBGRA; WICPixelFormatGUID formatGUID = formatDesired; if (SUCCEEDED(hr)) { hr = piBitmapFrameEncode->SetPixelFormat(&formatGUID); } if (SUCCEEDED(hr)) { //Be sure the image format is the one requested. hr = IsEqualGUID(formatGUID, formatDesired) ? S_OK : E_FAIL; } //Write the pixels into the frame. if (SUCCEEDED(hr)) { hr = piBitmapFrameEncode->WritePixels( height , bitmap->rowBytes() , bitmap->rowBytes()*height , reinterpret_cast<BYTE*>(bitmap->getPixels())); } if (SUCCEEDED(hr)) { hr = piBitmapFrameEncode->Commit(); } if (SUCCEEDED(hr)) { hr = piEncoder->Commit(); } return SUCCEEDED(hr); } SkImageEncoder* SkImageEncoder::Create(Type t) { switch (t) { case kJPEG_Type: case kPNG_Type: break; default: return NULL; } return SkNEW_ARGS(SkImageEncoder_WIC, (t)); } <|endoftext|>
<commit_before>/* * Copyright (C) 2010 - 2015 Leonid Kostrykin * * Chair of Medical Engineering (mediTEC) * RWTH Aachen University * Pauwelsstr. 20 * 52074 Aachen * Germany * */ #include <Carna/presets/RayMarchingStage.h> #include <Carna/base/Mesh.h> #include <Carna/base/Vertex.h> #include <Carna/base/IndexBuffer.h> #include <Carna/base/ShaderManager.h> #include <Carna/base/RenderState.h> #include <Carna/base/ShaderUniform.h> #include <Carna/base/math.h> namespace Carna { namespace presets { // ---------------------------------------------------------------------------------- // RayMarchingStage :: Details // ---------------------------------------------------------------------------------- struct RayMarchingStage::Details { Details(); base::RenderTask* renderTask; const base::Viewport* viewPort; unsigned int mySampleRate; }; // RayMarchingStage :: Details RayMarchingStage::Details::Details() : renderTask( nullptr ) , viewPort( nullptr ) , mySampleRate( DEFAULT_SAMPLE_RATE ) { } // ---------------------------------------------------------------------------------- // RayMarchingStage :: VideoResources // ---------------------------------------------------------------------------------- struct RayMarchingStage::VideoResources { VideoResources( const base::ShaderProgram& shader ); ~VideoResources(); typedef base::Mesh< base::VertexBase, uint8_t > SliceMesh; SliceMesh& sliceMesh; const base::ShaderProgram& shader; std::map< unsigned int, base::Sampler* > samplers; void renderSlice ( RayMarchingStage& self , const base::Renderable& renderable , const base::math::Matrix4f& sliceTangentModel , const base::math::Matrix4f& modelView ); }; // RayMarchingStage :: VideoResources RayMarchingStage::VideoResources::VideoResources( const base::ShaderProgram& shader ) : sliceMesh( SliceMesh::create( base::IndexBufferBase::PRIMITIVE_TYPE_TRIANGLE_FAN ) ) , shader( shader ) { const float radius = std::sqrt( 3.f ) / 2; base::VertexBase vertices[ 4 ]; uint8_t indices[ 4 ]; vertices[ 0 ].x = -radius; vertices[ 0 ].y = -radius; indices [ 0 ] = 0; vertices[ 1 ].x = +radius; vertices[ 1 ].y = -radius; indices [ 1 ] = 1; vertices[ 2 ].x = +radius; vertices[ 2 ].y = +radius; indices [ 2 ] = 2; vertices[ 3 ].x = -radius; vertices[ 3 ].y = +radius; indices [ 3 ] = 3; sliceMesh.vertexBuffer().copy( vertices, 4 ); sliceMesh. indexBuffer().copy( indices, 4 ); } RayMarchingStage::VideoResources::~VideoResources() { sliceMesh.release(); } void RayMarchingStage::VideoResources::renderSlice ( RayMarchingStage& self , const base::Renderable& renderable , const base::math::Matrix4f& sliceTangentModel , const base::math::Matrix4f& modelView ) { unsigned int lastUnit = base::Texture3D::SETUP_UNIT; std::vector< unsigned int > roles; const base::Texture3D* anyTexture; renderable.geometry().visitFeatures( [&]( base::GeometryFeature& gf, unsigned int role ) { if( dynamic_cast< base::Texture3D* >( &gf ) != nullptr ) { const base::Texture3D& texture = static_cast< const base::Texture3D& >( gf ); anyTexture = &texture; texture.bind( ++lastUnit ); samplers[ role ]->bind( lastUnit ); roles.push_back( role ); } } ); /* We assume here that the texture coordinates correction is same for all * textures, i.e. all textures have same resolution. */ const base::math::Matrix4f modelTexture = ( anyTexture == nullptr ? base::math::identity4f() : anyTexture->textureCoordinatesCorrection() ) * base::math::translation4f( 0.5f, 0.5f, 0.5f ); /* Configure shader. */ base::ShaderUniform< base::math::Matrix4f >( "sliceTangentModel", sliceTangentModel ).upload(); base::ShaderUniform< base::math::Matrix4f >( "modelViewProjection", self.pimpl->renderTask->projection * modelView ).upload(); base::ShaderUniform< base::math::Matrix4f >( "modelTexture", modelTexture ).upload(); for( unsigned int samplerOffset = 0; samplerOffset < roles.size(); ++samplerOffset ) { const unsigned int role = roles[ samplerOffset ]; const unsigned int unit = base::Texture3D::SETUP_UNIT + 1 + samplerOffset; const std::string& uniformName = self.uniformName( role ); base::ShaderUniform< int >( uniformName, unit ).upload(); } /* Invoke shader. */ sliceMesh.render(); } // ---------------------------------------------------------------------------------- // RayMarchingStage // ---------------------------------------------------------------------------------- RayMarchingStage::RayMarchingStage( unsigned int geometryType ) : base::GeometryStage< base::Renderable::DepthOrder< base::Renderable::ORDER_BACK_TO_FRONT > > ::GeometryStage( geometryType ) , pimpl( new Details() ) { } RayMarchingStage::~RayMarchingStage() { activateGLContext(); if( vr.get() != nullptr ) { /* Release main shader. */ base::ShaderManager::instance().releaseShader( vr->shader ); /* Release texture samplers. */ for( auto samplerItr = vr->samplers.begin(); samplerItr != vr->samplers.end(); ++samplerItr ) { delete samplerItr->second; } } } void RayMarchingStage::render( base::GLContext& glc, const base::Renderable& renderable ) { using base::math::Matrix4f; using base::math::Vector4f; /* Hereinafter the term 'model' is identified with 'segment'. */ const Matrix4f& modelView = renderable.modelViewTransform(); /* Compute the directional vector from eye to segment center. * This vector needs to be renormalized since 'viewModel' may contain scalings. */ const Matrix4f viewModel = modelView.inverse(); const Vector4f viewDirectionInModelSpace = ( viewModel * Vector4f( 0, 0, -1, 0 ) ).normalized(); /* Construct billboard at segment center, i.e. plane that always faces the camera. */ const float s = std::sqrt( 2.f ) / 2; const Vector4f modelNormal = s * -viewDirectionInModelSpace; const Vector4f modelTangent = s * ( viewModel * Vector4f( 1, 0, 0, 0 ) ).normalized(); const Vector4f modelBitangent = s * ( viewModel * Vector4f( 0, 1, 0, 0 ) ).normalized(); const Matrix4f tangentModel = base::math::basis4f( modelTangent, modelBitangent, modelNormal ); /* NOTE: This can be optimized using geometry shader, by sending only the central * slice to the GPU and constructing the others in the shader. */ for( unsigned int sampleIdx = 0; sampleIdx < pimpl->mySampleRate; ++sampleIdx ) { const float progress = static_cast< float >( sampleIdx ) / ( pimpl->mySampleRate - 1 ); const float offset = std::sqrt( 3.f ) * ( 0.5f - progress ); /* Construct transformation from tangent to model space for specific slice. */ const Matrix4f sliceOffset = base::math::translation4f( viewDirectionInModelSpace * offset ); const Matrix4f sliceTangentModel = sliceOffset * tangentModel; vr->renderSlice( *this, renderable, sliceTangentModel, modelView ); } } void RayMarchingStage::loadVideoResources() { const base::ShaderProgram& shader = loadShader(); vr.reset( new VideoResources( shader ) ); createSamplers( [&]( unsigned int role, base::Sampler* sampler ) { CARNA_ASSERT( vr->samplers.find( role ) == vr->samplers.end() ); vr->samplers[ role ] = sampler; } ); } void RayMarchingStage::renderPass ( const base::math::Matrix4f& vt , base::RenderTask& rt , const base::Viewport& vp ) { if( vr.get() == nullptr ) { loadVideoResources(); } rt.renderer.glContext().setShader( vr->shader ); configureShader( rt.renderer.glContext() ); pimpl->renderTask = &rt; pimpl->viewPort = &vp; /* Configure proper OpenGL state. */ base::RenderState rs( rt.renderer.glContext() ); rs.setDepthWrite( false ); /* Do the rendering. */ base::GeometryStage< base::Renderable::DepthOrder< base::Renderable::ORDER_BACK_TO_FRONT > >::renderPass( vt, rt, vp ); /* There is no guarantee that 'renderTask' will be valid later. */ pimpl->renderTask = nullptr; } void RayMarchingStage::setSampleRate( unsigned int sampleRate ) { CARNA_ASSERT( sampleRate >= 2 ); pimpl->mySampleRate = sampleRate; } unsigned int RayMarchingStage::sampleRate() const { return pimpl->mySampleRate; } } // namespace Carna :: presets } // namespace Carna <commit_msg>Fixed issue described in last commit message.<commit_after>/* * Copyright (C) 2010 - 2015 Leonid Kostrykin * * Chair of Medical Engineering (mediTEC) * RWTH Aachen University * Pauwelsstr. 20 * 52074 Aachen * Germany * */ #include <Carna/presets/RayMarchingStage.h> #include <Carna/base/Mesh.h> #include <Carna/base/Vertex.h> #include <Carna/base/IndexBuffer.h> #include <Carna/base/ShaderManager.h> #include <Carna/base/RenderState.h> #include <Carna/base/ShaderUniform.h> #include <Carna/base/math.h> namespace Carna { namespace presets { // ---------------------------------------------------------------------------------- // RayMarchingStage :: Details // ---------------------------------------------------------------------------------- struct RayMarchingStage::Details { Details(); base::RenderTask* renderTask; const base::Viewport* viewPort; unsigned int mySampleRate; }; // RayMarchingStage :: Details RayMarchingStage::Details::Details() : renderTask( nullptr ) , viewPort( nullptr ) , mySampleRate( DEFAULT_SAMPLE_RATE ) { } // ---------------------------------------------------------------------------------- // RayMarchingStage :: VideoResources // ---------------------------------------------------------------------------------- struct RayMarchingStage::VideoResources { VideoResources( const base::ShaderProgram& shader ); ~VideoResources(); typedef base::Mesh< base::VertexBase, uint8_t > SliceMesh; SliceMesh& sliceMesh; const base::ShaderProgram& shader; std::map< unsigned int, base::Sampler* > samplers; void renderSlice ( RayMarchingStage& self , const base::Renderable& renderable , const base::math::Matrix4f& sliceTangentModel , const base::math::Matrix4f& modelView ); }; // RayMarchingStage :: VideoResources RayMarchingStage::VideoResources::VideoResources( const base::ShaderProgram& shader ) : sliceMesh( SliceMesh::create( base::IndexBufferBase::PRIMITIVE_TYPE_TRIANGLE_FAN ) ) , shader( shader ) { const float radius = std::sqrt( 3.f ); base::VertexBase vertices[ 4 ]; uint8_t indices[ 4 ]; vertices[ 0 ].x = -radius; vertices[ 0 ].y = -radius; indices [ 0 ] = 0; vertices[ 1 ].x = +radius; vertices[ 1 ].y = -radius; indices [ 1 ] = 1; vertices[ 2 ].x = +radius; vertices[ 2 ].y = +radius; indices [ 2 ] = 2; vertices[ 3 ].x = -radius; vertices[ 3 ].y = +radius; indices [ 3 ] = 3; sliceMesh.vertexBuffer().copy( vertices, 4 ); sliceMesh. indexBuffer().copy( indices, 4 ); } RayMarchingStage::VideoResources::~VideoResources() { sliceMesh.release(); } void RayMarchingStage::VideoResources::renderSlice ( RayMarchingStage& self , const base::Renderable& renderable , const base::math::Matrix4f& sliceTangentModel , const base::math::Matrix4f& modelView ) { unsigned int lastUnit = base::Texture3D::SETUP_UNIT; std::vector< unsigned int > roles; const base::Texture3D* anyTexture; renderable.geometry().visitFeatures( [&]( base::GeometryFeature& gf, unsigned int role ) { if( dynamic_cast< base::Texture3D* >( &gf ) != nullptr ) { const base::Texture3D& texture = static_cast< const base::Texture3D& >( gf ); anyTexture = &texture; texture.bind( ++lastUnit ); samplers[ role ]->bind( lastUnit ); roles.push_back( role ); } } ); /* We assume here that the texture coordinates correction is same for all * textures, i.e. all textures have same resolution. */ const base::math::Matrix4f modelTexture = ( anyTexture == nullptr ? base::math::identity4f() : anyTexture->textureCoordinatesCorrection() ) * base::math::translation4f( 0.5f, 0.5f, 0.5f ); /* Configure shader. */ base::ShaderUniform< base::math::Matrix4f >( "sliceTangentModel", sliceTangentModel ).upload(); base::ShaderUniform< base::math::Matrix4f >( "modelViewProjection", self.pimpl->renderTask->projection * modelView ).upload(); base::ShaderUniform< base::math::Matrix4f >( "modelTexture", modelTexture ).upload(); for( unsigned int samplerOffset = 0; samplerOffset < roles.size(); ++samplerOffset ) { const unsigned int role = roles[ samplerOffset ]; const unsigned int unit = base::Texture3D::SETUP_UNIT + 1 + samplerOffset; const std::string& uniformName = self.uniformName( role ); base::ShaderUniform< int >( uniformName, unit ).upload(); } /* Invoke shader. */ sliceMesh.render(); } // ---------------------------------------------------------------------------------- // RayMarchingStage // ---------------------------------------------------------------------------------- RayMarchingStage::RayMarchingStage( unsigned int geometryType ) : base::GeometryStage< base::Renderable::DepthOrder< base::Renderable::ORDER_BACK_TO_FRONT > > ::GeometryStage( geometryType ) , pimpl( new Details() ) { } RayMarchingStage::~RayMarchingStage() { activateGLContext(); if( vr.get() != nullptr ) { /* Release main shader. */ base::ShaderManager::instance().releaseShader( vr->shader ); /* Release texture samplers. */ for( auto samplerItr = vr->samplers.begin(); samplerItr != vr->samplers.end(); ++samplerItr ) { delete samplerItr->second; } } } void RayMarchingStage::render( base::GLContext& glc, const base::Renderable& renderable ) { using base::math::Matrix4f; using base::math::Vector4f; /* Hereinafter the term 'model' is identified with 'segment'. */ const Matrix4f& modelView = renderable.modelViewTransform(); /* Compute the directional vector from eye to segment center. * This vector needs to be renormalized since 'viewModel' may contain scalings. */ const Matrix4f viewModel = modelView.inverse(); const Vector4f viewDirectionInModelSpace = ( viewModel * Vector4f( 0, 0, -1, 0 ) ).normalized(); /* Construct billboard at segment center, i.e. plane that always faces the camera. */ const float s = std::sqrt( 2.f ) / 2; const Vector4f modelNormal = s * -viewDirectionInModelSpace; const Vector4f modelTangent = s * ( viewModel * Vector4f( 1, 0, 0, 0 ) ).normalized(); const Vector4f modelBitangent = s * ( viewModel * Vector4f( 0, 1, 0, 0 ) ).normalized(); const Matrix4f tangentModel = base::math::basis4f( modelTangent, modelBitangent, modelNormal ); /* NOTE: This can be optimized using geometry shader, by sending only the central * slice to the GPU and constructing the others in the shader. */ for( unsigned int sampleIdx = 0; sampleIdx < pimpl->mySampleRate; ++sampleIdx ) { const float progress = static_cast< float >( sampleIdx ) / ( pimpl->mySampleRate - 1 ); const float offset = std::sqrt( 3.f ) * ( 0.5f - progress ); /* Construct transformation from tangent to model space for specific slice. */ const Matrix4f sliceOffset = base::math::translation4f( viewDirectionInModelSpace * offset ); const Matrix4f sliceTangentModel = sliceOffset * tangentModel; vr->renderSlice( *this, renderable, sliceTangentModel, modelView ); } } void RayMarchingStage::loadVideoResources() { const base::ShaderProgram& shader = loadShader(); vr.reset( new VideoResources( shader ) ); createSamplers( [&]( unsigned int role, base::Sampler* sampler ) { CARNA_ASSERT( vr->samplers.find( role ) == vr->samplers.end() ); vr->samplers[ role ] = sampler; } ); } void RayMarchingStage::renderPass ( const base::math::Matrix4f& vt , base::RenderTask& rt , const base::Viewport& vp ) { if( vr.get() == nullptr ) { loadVideoResources(); } rt.renderer.glContext().setShader( vr->shader ); configureShader( rt.renderer.glContext() ); pimpl->renderTask = &rt; pimpl->viewPort = &vp; /* Configure proper OpenGL state. */ base::RenderState rs( rt.renderer.glContext() ); rs.setDepthWrite( false ); /* Do the rendering. */ base::GeometryStage< base::Renderable::DepthOrder< base::Renderable::ORDER_BACK_TO_FRONT > >::renderPass( vt, rt, vp ); /* There is no guarantee that 'renderTask' will be valid later. */ pimpl->renderTask = nullptr; } void RayMarchingStage::setSampleRate( unsigned int sampleRate ) { CARNA_ASSERT( sampleRate >= 2 ); pimpl->mySampleRate = sampleRate; } unsigned int RayMarchingStage::sampleRate() const { return pimpl->mySampleRate; } } // namespace Carna :: presets } // namespace Carna <|endoftext|>
<commit_before>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #include "./storage_profiler.h" #if MXNET_USE_NVML #include <nvml.h> #endif // MXNET_USE_NVML #include <fstream> #include <map> #include <regex> #include <unordered_map> #include <vector> #include "./profiler.h" #include "../common/utils.h" #include "../common/cuda/utils.h" namespace mxnet { namespace profiler { #if MXNET_USE_CUDA GpuDeviceStorageProfiler* GpuDeviceStorageProfiler::Get() { static std::mutex mtx; static std::shared_ptr<GpuDeviceStorageProfiler> gpu_dev_storage_profiler = nullptr; std::unique_lock<std::mutex> lk(mtx); if (!gpu_dev_storage_profiler) { gpu_dev_storage_profiler = std::make_shared<GpuDeviceStorageProfiler>(); } return gpu_dev_storage_profiler.get(); } void GpuDeviceStorageProfiler::DumpProfile() const { size_t current_pid = common::current_process_id(); std::ofstream fout((filename_prefix_ + "-pid_" + std::to_string(current_pid) + ".csv").c_str()); if (!fout.is_open()) { return; } struct AllocEntryDumpFmt { size_t requested_size; int dev_id; size_t actual_size; bool reuse; }; // order the GPU memory allocation entries by their attribute name std::multimap<std::string, AllocEntryDumpFmt> gpu_mem_ordered_alloc_entries; // map the GPU device ID to the total amount of allocations std::unordered_map<int, size_t> gpu_dev_id_total_alloc_map; std::regex gluon_param_regex( "([0-9a-fA-F]{8})_([0-9a-fA-F]{4})_" "([0-9a-fA-F]{4})_([0-9a-fA-F]{4})_" "([0-9a-fA-F]{12})_([^ ]*)"); for (const std::pair<void* const, AllocEntry>& alloc_entry : gpu_mem_alloc_entries_) { std::string alloc_entry_name = std::regex_replace(alloc_entry.second.name, gluon_param_regex, "$6"); if (alloc_entry_name == "") { // If the entry name becomes none after the regex replacement, we revert // back to the original. alloc_entry_name = alloc_entry.second.name; } gpu_mem_ordered_alloc_entries.emplace(alloc_entry.second.profiler_scope + alloc_entry_name, AllocEntryDumpFmt{alloc_entry.second.requested_size, alloc_entry.second.dev_id, alloc_entry.second.actual_size, alloc_entry.second.reuse}); gpu_dev_id_total_alloc_map[alloc_entry.second.dev_id] = 0; } fout << "\"Attribute Name\",\"Requested Size\"," "\"Device\",\"Actual Size\",\"Reuse?\"" << std::endl; for (const std::pair<const std::string, AllocEntryDumpFmt>& alloc_entry : gpu_mem_ordered_alloc_entries) { fout << "\"" << alloc_entry.first << "\"," << "\"" << alloc_entry.second.requested_size << "\"," << "\"" << alloc_entry.second.dev_id << "\"," << "\"" << alloc_entry.second.actual_size << "\"," << "\"" << alloc_entry.second.reuse << "\"" << std::endl; gpu_dev_id_total_alloc_map[alloc_entry.second.dev_id] += alloc_entry.second.actual_size; } #if MXNET_USE_NVML // If NVML has been enabled, add amend term to the GPU memory profile. nvmlDevice_t nvml_device; NVML_CALL(nvmlInit()); for (std::pair<const int, size_t>& dev_id_total_alloc_pair : gpu_dev_id_total_alloc_map) { unsigned info_count = 0; std::vector<nvmlProcessInfo_t> infos(info_count); NVML_CALL(nvmlDeviceGetHandleByIndex(dev_id_total_alloc_pair.first, &nvml_device)); // The first call to `nvmlDeviceGetComputeRunningProcesses` is to set the // size of info. Since `NVML_ERROR_INSUFFICIENT_SIZE` will always be // returned, we do not wrap the function call with `NVML_CALL`. nvmlDeviceGetComputeRunningProcesses(nvml_device, &info_count, infos.data()); infos = std::vector<nvmlProcessInfo_t>(info_count); NVML_CALL(nvmlDeviceGetComputeRunningProcesses(nvml_device, &info_count, infos.data())); bool amend_made = false; for (unsigned i = 0; i < info_count; ++i) { if (current_pid == infos[i].pid) { amend_made = true; fout << "\"" << "nvml_amend" << "\"," << "\"" << infos[i].usedGpuMemory - dev_id_total_alloc_pair.second << "\"," << "\"" << dev_id_total_alloc_pair.first << "\"," << "\"" << infos[i].usedGpuMemory - dev_id_total_alloc_pair.second << "\"," << "\"0\"" << std::endl; break; } } if (!amend_made) { LOG(INFO) << "NVML is unable to make amendment to the GPU memory profile " "since it is unable to locate the current process ID. " "Are you working in Docker without setting --pid=host?"; } } // for (dev_id_total_alloc_pair : gpu_dev_id_total_alloc_map) #endif // MXNET_USE_NVML } #endif // MXNET_USE_CUDA } // namespace profiler } // namespace mxnet <commit_msg>ensure type consistent with legacy nvml api (#20499)<commit_after>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #include "./storage_profiler.h" #if MXNET_USE_NVML #include <nvml.h> #endif // MXNET_USE_NVML #include <fstream> #include <map> #include <regex> #include <unordered_map> #include <vector> #include "./profiler.h" #include "../common/utils.h" #include "../common/cuda/utils.h" namespace mxnet { namespace profiler { #if MXNET_USE_CUDA GpuDeviceStorageProfiler* GpuDeviceStorageProfiler::Get() { static std::mutex mtx; static std::shared_ptr<GpuDeviceStorageProfiler> gpu_dev_storage_profiler = nullptr; std::unique_lock<std::mutex> lk(mtx); if (!gpu_dev_storage_profiler) { gpu_dev_storage_profiler = std::make_shared<GpuDeviceStorageProfiler>(); } return gpu_dev_storage_profiler.get(); } void GpuDeviceStorageProfiler::DumpProfile() const { size_t current_pid = common::current_process_id(); std::ofstream fout((filename_prefix_ + "-pid_" + std::to_string(current_pid) + ".csv").c_str()); if (!fout.is_open()) { return; } struct AllocEntryDumpFmt { size_t requested_size; int dev_id; size_t actual_size; bool reuse; }; // order the GPU memory allocation entries by their attribute name std::multimap<std::string, AllocEntryDumpFmt> gpu_mem_ordered_alloc_entries; // map the GPU device ID to the total amount of allocations std::unordered_map<int, size_t> gpu_dev_id_total_alloc_map; std::regex gluon_param_regex( "([0-9a-fA-F]{8})_([0-9a-fA-F]{4})_" "([0-9a-fA-F]{4})_([0-9a-fA-F]{4})_" "([0-9a-fA-F]{12})_([^ ]*)"); for (const std::pair<void* const, AllocEntry>& alloc_entry : gpu_mem_alloc_entries_) { std::string alloc_entry_name = std::regex_replace(alloc_entry.second.name, gluon_param_regex, "$6"); if (alloc_entry_name == "") { // If the entry name becomes none after the regex replacement, we revert // back to the original. alloc_entry_name = alloc_entry.second.name; } gpu_mem_ordered_alloc_entries.emplace(alloc_entry.second.profiler_scope + alloc_entry_name, AllocEntryDumpFmt{alloc_entry.second.requested_size, alloc_entry.second.dev_id, alloc_entry.second.actual_size, alloc_entry.second.reuse}); gpu_dev_id_total_alloc_map[alloc_entry.second.dev_id] = 0; } fout << "\"Attribute Name\",\"Requested Size\"," "\"Device\",\"Actual Size\",\"Reuse?\"" << std::endl; for (const std::pair<const std::string, AllocEntryDumpFmt>& alloc_entry : gpu_mem_ordered_alloc_entries) { fout << "\"" << alloc_entry.first << "\"," << "\"" << alloc_entry.second.requested_size << "\"," << "\"" << alloc_entry.second.dev_id << "\"," << "\"" << alloc_entry.second.actual_size << "\"," << "\"" << alloc_entry.second.reuse << "\"" << std::endl; gpu_dev_id_total_alloc_map[alloc_entry.second.dev_id] += alloc_entry.second.actual_size; } #if MXNET_USE_NVML // If NVML has been enabled, add amend term to the GPU memory profile. nvmlDevice_t nvml_device; #if NVML_API_VERSION < 11 typedef std::vector<nvmlProcessInfo_t> ProcessInfoVector; #else typedef std::vector<nvmlProcessInfo_v1_t> ProcessInfoVector; #endif NVML_CALL(nvmlInit()); for (std::pair<const int, size_t>& dev_id_total_alloc_pair : gpu_dev_id_total_alloc_map) { unsigned info_count = 0; ProcessInfoVector infos(info_count); NVML_CALL(nvmlDeviceGetHandleByIndex(dev_id_total_alloc_pair.first, &nvml_device)); // The first call to `nvmlDeviceGetComputeRunningProcesses` is to set the // size of info. Since `NVML_ERROR_INSUFFICIENT_SIZE` will always be // returned, we do not wrap the function call with `NVML_CALL`. nvmlDeviceGetComputeRunningProcesses(nvml_device, &info_count, infos.data()); infos = ProcessInfoVector(info_count); NVML_CALL(nvmlDeviceGetComputeRunningProcesses(nvml_device, &info_count, infos.data())); bool amend_made = false; for (unsigned i = 0; i < info_count; ++i) { if (current_pid == infos[i].pid) { amend_made = true; fout << "\"" << "nvml_amend" << "\"," << "\"" << infos[i].usedGpuMemory - dev_id_total_alloc_pair.second << "\"," << "\"" << dev_id_total_alloc_pair.first << "\"," << "\"" << infos[i].usedGpuMemory - dev_id_total_alloc_pair.second << "\"," << "\"0\"" << std::endl; break; } } if (!amend_made) { LOG(INFO) << "NVML is unable to make amendment to the GPU memory profile " "since it is unable to locate the current process ID. " "Are you working in Docker without setting --pid=host?"; } } // for (dev_id_total_alloc_pair : gpu_dev_id_total_alloc_map) #endif // MXNET_USE_NVML } #endif // MXNET_USE_CUDA } // namespace profiler } // namespace mxnet <|endoftext|>
<commit_before>/* Copyright 2010 Antonie Jovanoski * * 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. * * Contact e-mail: Antonie Jovanoski <minimoog77_at_gmail.com> */ #include <QtDebug> #include <QNetworkRequest> #include <QNetworkReply> #include "qtweetdirectmessagessent.h" #include "qtweetdmstatus.h" #include "qtweetconvert.h" #include "json/qjsondocument.h" #include "json/qjsonarray.h" /** * Constructor */ QTweetDirectMessagesSent::QTweetDirectMessagesSent(QObject *parent) : QTweetNetBase(parent) { } /** * Constructor * @param oauthTwitter OAuthTwitter object * @param parent parent QObject */ QTweetDirectMessagesSent::QTweetDirectMessagesSent(OAuthTwitter *oauthTwitter, QObject *parent) : QTweetNetBase(oauthTwitter, parent) { } /** * Starts fetching direct messages * @param sinceid returns results with an ID greater than (that is, more recent than) the specified ID. * @param maxid returns results with an ID less than (that is, older than) or equal to the specified ID. * @param count specifies the number of records to retrieve. Must be less than or equal to 200. * @param page specifies the page of results to retrieve. * @param includeEntities When set to true, each tweet will include a node called "entities,". * @remarks Setting parameters to default value will not be put in the query */ void QTweetDirectMessagesSent::fetch(qint64 sinceid, qint64 maxid, int count, int page, bool includeEntities) { if (!isAuthenticationEnabled()) { qCritical("Needs authentication to be enabled"); return; } QUrl url("http://api.twitter.com/1/direct_messages/sent.json"); if (sinceid) url.addQueryItem("since_id", QString::number(sinceid)); if (maxid) url.addQueryItem("max_id", QString::number(maxid)); if (count) url.addQueryItem("count", QString::number(count)); if (page) url.addQueryItem("page", QString::number(page)); if (includeEntities) url.addQueryItem("include_entities", "true"); QNetworkRequest req(url); QByteArray oauthHeader = oauthTwitter()->generateAuthorizationHeader(url, OAuth::GET); req.setRawHeader(AUTH_HEADER, oauthHeader); QNetworkReply *reply = oauthTwitter()->networkAccessManager()->get(req); connect(reply, SIGNAL(finished()), this, SLOT(reply())); } void QTweetDirectMessagesSent::parseJsonFinished(const QJsonDocument &jsonDoc) { if (jsonDoc.isArray()) { QList<QTweetDMStatus> directMessages = QTweetConvert::jsonArrayToDirectMessagesList(jsonDoc.array()); emit parsedDirectMessages(directMessages); } } <commit_msg>Updated QTweetDirectMessagesSent to 1.1 API<commit_after>/* Copyright 2010 Antonie Jovanoski * * 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. * * Contact e-mail: Antonie Jovanoski <minimoog77_at_gmail.com> */ #include <QtDebug> #include <QNetworkRequest> #include <QNetworkReply> #include "qtweetdirectmessagessent.h" #include "qtweetdmstatus.h" #include "qtweetconvert.h" #include "json/qjsondocument.h" #include "json/qjsonarray.h" /** * Constructor */ QTweetDirectMessagesSent::QTweetDirectMessagesSent(QObject *parent) : QTweetNetBase(parent) { } /** * Constructor * @param oauthTwitter OAuthTwitter object * @param parent parent QObject */ QTweetDirectMessagesSent::QTweetDirectMessagesSent(OAuthTwitter *oauthTwitter, QObject *parent) : QTweetNetBase(oauthTwitter, parent) { } /** * Starts fetching direct messages * @param sinceid returns results with an ID greater than (that is, more recent than) the specified ID. * @param maxid returns results with an ID less than (that is, older than) or equal to the specified ID. * @param count specifies the number of records to retrieve. Must be less than or equal to 200. * @param page specifies the page of results to retrieve. * @param includeEntities When set to true, each tweet will include a node called "entities,". * @remarks Setting parameters to default value will not be put in the query */ void QTweetDirectMessagesSent::fetch(qint64 sinceid, qint64 maxid, int count, int page, bool includeEntities) { if (!isAuthenticationEnabled()) { qCritical("Needs authentication to be enabled"); return; } QUrl url("https://api.twitter.com/1.1/direct_messages/sent.json"); if (sinceid) url.addQueryItem("since_id", QString::number(sinceid)); if (maxid) url.addQueryItem("max_id", QString::number(maxid)); if (count) url.addQueryItem("count", QString::number(count)); if (page) url.addQueryItem("page", QString::number(page)); if (includeEntities) url.addQueryItem("include_entities", "true"); QNetworkRequest req(url); QByteArray oauthHeader = oauthTwitter()->generateAuthorizationHeader(url, OAuth::GET); req.setRawHeader(AUTH_HEADER, oauthHeader); QNetworkReply *reply = oauthTwitter()->networkAccessManager()->get(req); connect(reply, SIGNAL(finished()), this, SLOT(reply())); } void QTweetDirectMessagesSent::parseJsonFinished(const QJsonDocument &jsonDoc) { if (jsonDoc.isArray()) { QList<QTweetDMStatus> directMessages = QTweetConvert::jsonArrayToDirectMessagesList(jsonDoc.array()); emit parsedDirectMessages(directMessages); } } <|endoftext|>
<commit_before>#include "calculatorfactory.h" #include "calculators/integrals.h" #include "calculators/marcusrates.h" #include "calculators/readxml.h" #include "calculators/writexml.h" #include "calculators/contkmc.h" #include "calculators/estatics.h" #include "calculators/histintegrals.h" #include "calculators/shufflenrg.h" #include "calculators/generate_nrgs.h" #include "calculators/energycorr.h" #include "calculators/polymerrates.h" #include "calculators/pairdump.h" #include "calculators/CurrentDensity.h" void CalculatorFactory::RegisterAll(void) { Calculators().Register<CalcIntegrals>("integrals"); Calculators().Register<WriteXML>("writexml"); Calculators().Register<ReadXML>("readxml"); Calculators().Register<ContKmc>("kmc"); Calculators().Register<CalcEstatics>("estat"); Calculators().Register<MarcusRates>("marcusrates"); Calculators().Register<CalcHistIntegrals>("histintegrals"); Calculators().Register<ShuffleNrg>("shufflenrg"); Calculators().Register<GenerateNrgs>("generatenrgs"); Calculators().Register<EnergyCorr>("energycorr"); Calculators().Register<PolymerRates>("polymerrates"); Calculators().Register<PairDump>("pairdump"); Calculators().Register<CurrentDensity>("currden"); } <commit_msg>new calculator for marcus rates and jortnerrates<commit_after>#include "calculatorfactory.h" #include "calculators/integrals.h" #include "calculators/marcusrates.h" #include "calculators/readxml.h" #include "calculators/writexml.h" #include "calculators/contkmc.h" #include "calculators/estatics.h" #include "calculators/histintegrals.h" #include "calculators/shufflenrg.h" #include "calculators/generate_nrgs.h" #include "calculators/energycorr.h" #include "calculators/polymerrates.h" #include "calculators/pairdump.h" #include "calculators/CurrentDensity.h" #include "calculators/jortnerrates.h" #include "calculators/marcusrateslambdaouter.h" void CalculatorFactory::RegisterAll(void) { Calculators().Register<CalcIntegrals>("integrals"); Calculators().Register<WriteXML>("writexml"); Calculators().Register<ReadXML>("readxml"); Calculators().Register<ContKmc>("kmc"); Calculators().Register<CalcEstatics>("estat"); Calculators().Register<MarcusRates>("marcusrates"); Calculators().Register<CalcHistIntegrals>("histintegrals"); Calculators().Register<ShuffleNrg>("shufflenrg"); Calculators().Register<GenerateNrgs>("generatenrgs"); Calculators().Register<EnergyCorr>("energycorr"); Calculators().Register<PolymerRates>("polymerrates"); Calculators().Register<PairDump>("pairdump"); Calculators().Register<CurrentDensity>("currden"); Calculators().Register<JortnerRates>("jortnerrates"); Calculators().Register<MarcusRatesLambdaOuter>("marcusrateslambdaouter"); } <|endoftext|>
<commit_before>/* RawSpeed - RAW file decoder. Copyright (C) 2009-2014 Klaus Post Copyright (C) 2017 Roman Lebedev 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "io/FileReader.h" #include "common/Common.h" // for make_unique #include "io/Buffer.h" // for Buffer #include "io/FileIOException.h" // for FileIOException (ptr only), ThrowFIE #include <algorithm> // for move #include <cstdio> // for fclose, fseek, fopen, fread, ftell #include <fcntl.h> // for SEEK_END, SEEK_SET #include <limits> // for numeric_limits #include <memory> // for unique_ptr #if defined(__unix__) || defined(__APPLE__) #include <type_traits> // for make_unsigned #else #include <io.h> #include <tchar.h> #include <windows.h> #endif namespace rawspeed { std::unique_ptr<Buffer> FileReader::readFile() { size_t fileSize = 0; #if defined(__unix__) || defined(__APPLE__) using file_ptr = std::unique_ptr<FILE, decltype(&fclose)>; file_ptr file(fopen(fileName, "rb"), &fclose); if (file == nullptr) ThrowFIE("Could not open file \"%s\".", fileName); fseek(file.get(), 0, SEEK_END); const auto size = ftell(file.get()); if (size <= 0) ThrowFIE("File is 0 bytes."); fileSize = static_cast<std::make_unsigned<decltype(size)>::type>(size); if (fileSize > std::numeric_limits<Buffer::size_type>::max()) ThrowFIE("File is too big (%zu bytes).", fileSize); fseek(file.get(), 0, SEEK_SET); auto dest = Buffer::Create(fileSize); auto bytes_read = fread(dest.get(), 1, fileSize, file.get()); if (fileSize != bytes_read) { ThrowFIE("Could not read file, %s.", feof(file.get()) ? "reached end-of-file" : (ferror(file.get()) ? "file reading error" : "unknown problem")); } #else // __unix__ using file_ptr = std::unique_ptr<HANDLE, decltype(&CloseHandle)>; file_ptr file(CreateFile(fileName, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, nullptr), &CloseHandle); if (file == INVALID_HANDLE_VALUE) ThrowFIE("Could not open file \"%s\".", fileName); LARGE_INTEGER size; GetFileSizeEx(file.get(), &size); static_assert( std::numeric_limits<Buffer::size_type>::max() == std::numeric_limits<decltype(size.LowPart)>::max(), "once Buffer migrates to 64-bit index, this needs to be updated."); if (size.HighPart > 0) ThrowFIE("File is too big."); if (size.LowPart <= 0) ThrowFIE("File is 0 bytes."); auto dest = Buffer::Create(size.LowPart); DWORD bytes_read; if (!ReadFile(file.get(), dest.get(), size.LowPart, &bytes_read, nullptr)) ThrowFIE("Could not read file."); if (size.LowPart != bytes_read) ThrowFIE("Could not read file."); fileSize = size.LowPart; #endif // __unix__ return make_unique<Buffer>(move(dest), fileSize); } } // namespace rawspeed <commit_msg>FileReader::readFile(): windows: and how about with remove_pointer?<commit_after>/* RawSpeed - RAW file decoder. Copyright (C) 2009-2014 Klaus Post Copyright (C) 2017 Roman Lebedev 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "io/FileReader.h" #include "common/Common.h" // for make_unique #include "io/Buffer.h" // for Buffer #include "io/FileIOException.h" // for FileIOException (ptr only), ThrowFIE #include <algorithm> // for move #include <cstdio> // for fclose, fseek, fopen, fread, ftell #include <fcntl.h> // for SEEK_END, SEEK_SET #include <limits> // for numeric_limits #include <memory> // for unique_ptr #include <type_traits> // for make_unsigned #if !(defined(__unix__) || defined(__APPLE__)) #include <io.h> #include <tchar.h> #include <windows.h> #endif namespace rawspeed { std::unique_ptr<Buffer> FileReader::readFile() { size_t fileSize = 0; #if defined(__unix__) || defined(__APPLE__) using file_ptr = std::unique_ptr<FILE, decltype(&fclose)>; file_ptr file(fopen(fileName, "rb"), &fclose); if (file == nullptr) ThrowFIE("Could not open file \"%s\".", fileName); fseek(file.get(), 0, SEEK_END); const auto size = ftell(file.get()); if (size <= 0) ThrowFIE("File is 0 bytes."); fileSize = static_cast<std::make_unsigned<decltype(size)>::type>(size); if (fileSize > std::numeric_limits<Buffer::size_type>::max()) ThrowFIE("File is too big (%zu bytes).", fileSize); fseek(file.get(), 0, SEEK_SET); auto dest = Buffer::Create(fileSize); auto bytes_read = fread(dest.get(), 1, fileSize, file.get()); if (fileSize != bytes_read) { ThrowFIE("Could not read file, %s.", feof(file.get()) ? "reached end-of-file" : (ferror(file.get()) ? "file reading error" : "unknown problem")); } #else // __unix__ using file_ptr = std::unique_ptr<std::remove_pointer<HANDLE>::type, decltype(&CloseHandle)>; file_ptr file(CreateFile(fileName, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, nullptr), &CloseHandle); if (file == INVALID_HANDLE_VALUE) ThrowFIE("Could not open file \"%s\".", fileName); LARGE_INTEGER size; GetFileSizeEx(file.get(), &size); static_assert( std::numeric_limits<Buffer::size_type>::max() == std::numeric_limits<decltype(size.LowPart)>::max(), "once Buffer migrates to 64-bit index, this needs to be updated."); if (size.HighPart > 0) ThrowFIE("File is too big."); if (size.LowPart <= 0) ThrowFIE("File is 0 bytes."); auto dest = Buffer::Create(size.LowPart); DWORD bytes_read; if (!ReadFile(file.get(), dest.get(), size.LowPart, &bytes_read, nullptr)) ThrowFIE("Could not read file."); if (size.LowPart != bytes_read) ThrowFIE("Could not read file."); fileSize = size.LowPart; #endif // __unix__ return make_unique<Buffer>(move(dest), fileSize); } } // namespace rawspeed <|endoftext|>
<commit_before>#include "runtime_internal.h" extern "C" { void *dlopen(const char *, int); void *dlsym(void *, const char *); int dlclose(void *); #define RTLD_LAZY 0x1 #define RTLD_LOCAL 0x4 WEAK void *halide_get_symbol(const char *name) { return dlsym(NULL, name); } WEAK void *halide_load_library(const char *name) { return dlopen(name, RTLD_LAZY | RTLD_LOCAL); } WEAK void *halide_get_library_symbol(void *lib, const char *name) { return dlsym(lib, name); } WEAK void halide_free_library(void *lib) { dlclose(lib); } } <commit_msg>Fixed broken dlopen on linux.<commit_after>#include "runtime_internal.h" extern "C" { void *dlopen(const char *, int); void *dlsym(void *, const char *); int dlclose(void *); #define RTLD_LAZY 0x1 WEAK void *halide_get_symbol(const char *name) { return dlsym(NULL, name); } WEAK void *halide_load_library(const char *name) { return dlopen(name, RTLD_LAZY); } WEAK void *halide_get_library_symbol(void *lib, const char *name) { return dlsym(lib, name); } WEAK void halide_free_library(void *lib) { dlclose(lib); } } <|endoftext|>
<commit_before>// illarionserver - server for the game Illarion // Copyright 2011 Illarion e.V. // // This file is part of illarionserver. // // illarionserver 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 3 of the License, or // (at your option) any later version. // // illarionserver 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 illarionserver. If not, see <http://www.gnu.org/licenses/>. #ifndef __CONFIG_HPP__ #define __CONFIG_HPP__ #include <string> #include <map> #include <iostream> class ConfigEntryBase { public: ConfigEntryBase(const std::string &config_name); friend std::istream &operator>>(std::istream &is, ConfigEntryBase &); virtual void read(std::istream &is) = 0; virtual void write(std::ostream &os) const= 0; virtual ~ConfigEntryBase() { } bool isInitialized() const { return _initialized; } protected: std::string _config_name; bool _initialized = { false }; }; std::istream &operator>>(std::istream &is, ConfigEntryBase &config_entry); std::ostream &operator<<(std::ostream &os, ConfigEntryBase &config_entry); template<typename T> class ConfigEntry : public ConfigEntryBase { public: ConfigEntry(const std::string &config_name, const T &default_value = {}) : ConfigEntryBase { config_name }, _item { default_value } {} operator T() const { return _item; } T operator()() const { return _item; } virtual void read(std::istream &is) { is >> _item; _initialized = true; } virtual void write(std::ostream &os) const { os << _item; } private: T _item; }; class Config { public: static bool load(const std::string &config_file); static void register_entry(const std::string &config_name, ConfigEntryBase *entry); static Config &instance() { if (_instance == nullptr) { _instance = new Config(); } return *_instance; } ConfigEntry<std::string> coutdir = { "coutdir", "./log/" }; ConfigEntry<std::string> datadir = { "datadir", "./data/" }; ConfigEntry<std::string> scriptdir = { "scriptdir", "./script/" }; ConfigEntry<std::string> monsteridc = { "monsteridc", "./monster/monstercount.bin" }; ConfigEntry<uint16_t> port = { "port", 3012 }; ConfigEntry<std::string> postgres_db = { "postgres_db", "illarion" }; ConfigEntry<std::string> postgres_user = { "postgres_user", "illarion" }; ConfigEntry<std::string> postgres_pwd = { "postgres_pwd", "illarion" }; ConfigEntry<std::string> postgres_host = { "postgres_host", "/var/run/postgresql" }; ConfigEntry<uint16_t> postgres_port = { "postgres_port", 5432 }; ConfigEntry<std::string> postgres_schema_server = { "postgres_schema_server", "server" }; ConfigEntry<std::string> postgres_schema_account = { "postgres_schema_account", "accounts" }; ConfigEntry<uint16_t> clientversion = { "clientversion", 122 }; ConfigEntry<int16_t> playerstart_x = { "playerstart_x", 0 }; ConfigEntry<int16_t> playerstart_y = { "playerstart_y", 0 }; ConfigEntry<int16_t> playerstart_z = { "playerstart_z", 0 }; private: static Config *_instance; }; #endif <commit_msg>Remove obsolete config entry<commit_after>// illarionserver - server for the game Illarion // Copyright 2011 Illarion e.V. // // This file is part of illarionserver. // // illarionserver 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 3 of the License, or // (at your option) any later version. // // illarionserver 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 illarionserver. If not, see <http://www.gnu.org/licenses/>. #ifndef __CONFIG_HPP__ #define __CONFIG_HPP__ #include <string> #include <map> #include <iostream> class ConfigEntryBase { public: ConfigEntryBase(const std::string &config_name); friend std::istream &operator>>(std::istream &is, ConfigEntryBase &); virtual void read(std::istream &is) = 0; virtual void write(std::ostream &os) const= 0; virtual ~ConfigEntryBase() { } bool isInitialized() const { return _initialized; } protected: std::string _config_name; bool _initialized = { false }; }; std::istream &operator>>(std::istream &is, ConfigEntryBase &config_entry); std::ostream &operator<<(std::ostream &os, ConfigEntryBase &config_entry); template<typename T> class ConfigEntry : public ConfigEntryBase { public: ConfigEntry(const std::string &config_name, const T &default_value = {}) : ConfigEntryBase { config_name }, _item { default_value } {} operator T() const { return _item; } T operator()() const { return _item; } virtual void read(std::istream &is) { is >> _item; _initialized = true; } virtual void write(std::ostream &os) const { os << _item; } private: T _item; }; class Config { public: static bool load(const std::string &config_file); static void register_entry(const std::string &config_name, ConfigEntryBase *entry); static Config &instance() { if (_instance == nullptr) { _instance = new Config(); } return *_instance; } ConfigEntry<std::string> coutdir = { "coutdir", "./log/" }; ConfigEntry<std::string> datadir = { "datadir", "./data/" }; ConfigEntry<std::string> scriptdir = { "scriptdir", "./script/" }; ConfigEntry<uint16_t> port = { "port", 3012 }; ConfigEntry<std::string> postgres_db = { "postgres_db", "illarion" }; ConfigEntry<std::string> postgres_user = { "postgres_user", "illarion" }; ConfigEntry<std::string> postgres_pwd = { "postgres_pwd", "illarion" }; ConfigEntry<std::string> postgres_host = { "postgres_host", "/var/run/postgresql" }; ConfigEntry<uint16_t> postgres_port = { "postgres_port", 5432 }; ConfigEntry<std::string> postgres_schema_server = { "postgres_schema_server", "server" }; ConfigEntry<std::string> postgres_schema_account = { "postgres_schema_account", "accounts" }; ConfigEntry<uint16_t> clientversion = { "clientversion", 122 }; ConfigEntry<int16_t> playerstart_x = { "playerstart_x", 0 }; ConfigEntry<int16_t> playerstart_y = { "playerstart_y", 0 }; ConfigEntry<int16_t> playerstart_z = { "playerstart_z", 0 }; private: static Config *_instance; }; #endif <|endoftext|>
<commit_before>#include "Central.h" Central::Central(uint32_t tSede1, uint32_t tSede2) { tel1 = tSede1; tel2 = tSede2; } Central::~Central() { } Address Central::llamar(uint32_t llamante, Time duracion) { ns3::UniformRandomVariable rnd; // Se escoge aleatoriamente un nmero al que llamar int llamado = rnd.GetValue(0, tel1+tel2); // Si el nmero no se encuentra en la lista, es que est libre if (llamadas.find(llamado)==llamadas.end()) { llamadas.insert(std::pair<uint32_t, uint32_t>(llamante, llamado)); Simulator::Schedule(duracion, this, Central::colgar, llamante); return telefonos[llamado]; } else // Si se encontr, est ocupado y no se produce la llamada { return Address(); // Devolver direccin invlida } } void Central::colgar(uint32_t llamante) { llamadas.erase(llamante); } uint32_t Central::registrar(Address llamante) { uint32_t indice = telefonos.count; telefonos.insert(std::pair<uint32_t, Address>(telefonos.count, llamante)); return indice; } <commit_msg>repair<commit_after>#include "Central.h" Central::Central(uint32_t tSede1, uint32_t tSede2) { tel1 = tSede1; tel2 = tSede2; } Central::~Central() { } Address Central::llamar(uint32_t llamante, Time duracion) { ns3::UniformRandomVariable rnd; // Se escoge aleatoriamente un nmero al que llamar uint32_t llamado = rnd.GetValue(0, tel1+tel2); // Si el nmero no se encuentra en la lista, es que est libre if (llamadas.find(llamado)==llamadas.end()) { llamadas.insert(std::pair<uint32_t, uint32_t>(llamante, llamado)); Simulator::Schedule(duracion, this, colgar, llamante); return telefonos[llamado]; } else // Si se encontr, est ocupado y no se produce la llamada { return Address(); // Devolver direccin invlida } } void Central::colgar(uint32_t llamante) { llamadas.erase(llamante); } uint32_t Central::registrar(Address llamante) { uint32_t indice = (uint32_t) telefonos.count; telefonos.insert(std::pair<uint32_t, Address>(telefonos.count, llamante)); return indice; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: mempool.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: hr $ $Date: 2007-06-27 22:15:56 $ * * 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 * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_tools.hxx" #include <tools/mempool.hxx> #ifndef _RTL_ALLOC_H_ #include "rtl/alloc.h" #endif #ifndef INCLUDED_STDIO_H #include <stdio.h> #endif /************************************************************************* |* |* FixedMemPool::FixedMemPool() |* *************************************************************************/ FixedMemPool::FixedMemPool ( USHORT _nTypeSize, USHORT, USHORT) { char name[RTL_CACHE_NAME_LENGTH + 1]; snprintf (name, sizeof(name), "FixedMemPool_%d", (int)_nTypeSize); m_pImpl = (FixedMemPool_Impl*)rtl_cache_create (name, _nTypeSize, 0, NULL, NULL, NULL, 0, NULL, 0); } /************************************************************************* |* |* FixedMemPool::~FixedMemPool() |* *************************************************************************/ FixedMemPool::~FixedMemPool() { rtl_cache_destroy ((rtl_cache_type*)(m_pImpl)); } /************************************************************************* |* |* FixedMemPool::Alloc() |* *************************************************************************/ void* FixedMemPool::Alloc() { return rtl_cache_alloc ((rtl_cache_type*)(m_pImpl)); } /************************************************************************* |* |* FixedMemPool::Free() |* *************************************************************************/ void FixedMemPool::Free( void* pFree ) { rtl_cache_free ((rtl_cache_type*)(m_pImpl), pFree); } <commit_msg>INTEGRATION: CWS changefileheader (1.8.84); FILE MERGED 2008/04/01 16:01:32 thb 1.8.84.2: #i85898# Stripping all external header guards 2008/03/28 15:41:22 rt 1.8.84.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: mempool.cxx,v $ * $Revision: 1.9 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_tools.hxx" #include <tools/mempool.hxx> #include "rtl/alloc.h" #ifndef INCLUDED_STDIO_H #include <stdio.h> #endif /************************************************************************* |* |* FixedMemPool::FixedMemPool() |* *************************************************************************/ FixedMemPool::FixedMemPool ( USHORT _nTypeSize, USHORT, USHORT) { char name[RTL_CACHE_NAME_LENGTH + 1]; snprintf (name, sizeof(name), "FixedMemPool_%d", (int)_nTypeSize); m_pImpl = (FixedMemPool_Impl*)rtl_cache_create (name, _nTypeSize, 0, NULL, NULL, NULL, 0, NULL, 0); } /************************************************************************* |* |* FixedMemPool::~FixedMemPool() |* *************************************************************************/ FixedMemPool::~FixedMemPool() { rtl_cache_destroy ((rtl_cache_type*)(m_pImpl)); } /************************************************************************* |* |* FixedMemPool::Alloc() |* *************************************************************************/ void* FixedMemPool::Alloc() { return rtl_cache_alloc ((rtl_cache_type*)(m_pImpl)); } /************************************************************************* |* |* FixedMemPool::Free() |* *************************************************************************/ void FixedMemPool::Free( void* pFree ) { rtl_cache_free ((rtl_cache_type*)(m_pImpl), pFree); } <|endoftext|>
<commit_before>#include "Line.hpp" #include "Point.hpp" #include "Circle.hpp" using namespace Geometry2d; bool Line::intersects(const Line &other, Point *intr) const { // From Mathworld: // http://mathworld.wolfram.com/Line-LineIntersection.html float x1 = pt[0].x; float y1 = pt[0].y; float x2 = pt[1].x; float y2 = pt[1].y; float x3 = other.pt[0].x; float y3 = other.pt[0].y; float x4 = other.pt[1].x; float y4 = other.pt[1].y; float denom = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4); if (denom == 0) return false; if (intr) { float deta = x1 * y2 - y1 * x2; float detb = x3 * y4 - y3 * x4; intr->x = (deta * (x3 - x4) - (x1 - x2) * detb) / denom; intr->y = (deta * (y3 - y4) - (y1 - y2) * detb) / denom; } return true; } float Line::distTo(const Point &other) const { Point delta = pt[1] - pt[0]; float top = delta.x * (pt[0].y - other.y) - (pt[0].x - other.x) * delta.y; return fabs(top) / delta.mag(); } Point Line::nearestPoint(Point p) const { Point v_hat = delta().normalized(); return pt[0] + v_hat * v_hat.dot(p - pt[0]); } bool Line::intersects(const Circle& circle, Point* p1, Point* p2) const { //http://mathworld.wolfram.com/Circle-LineIntersection.html const float dx = pt[1].x - pt[0].x; const float dy = pt[1].y - pt[0].y; const float dr2 = dx*dx + dy*dy; const float r = circle.radius(); float det = pt[0].x * pt[1].y - pt[1].x * pt[0].y; float descr = r * r * dr2 - det*det; if (descr < 0) { return false; } float common = sqrt(descr); float x1 = det * dy; float x2 = sign(dy) * dx * common; float y1 = -det * dx; float y2 = fabs(dy) * common; if (p1) { float x = x1 + x2; float y = y1 + y2; *p1 = Point(x/dr2, y/dr2); } if (p2) { float x = x1 - x2; float y = y1 - y2; *p2 = Point(x/dr2, y/dr2); } return true; } <commit_msg>fixed line intersection special case<commit_after>#include "Line.hpp" #include "Point.hpp" #include "Circle.hpp" using namespace Geometry2d; bool Line::intersects(const Line &other, Point *intr) const { // From Mathworld: // http://mathworld.wolfram.com/Line-LineIntersection.html float x1 = pt[0].x; float y1 = pt[0].y; float x2 = pt[1].x; float y2 = pt[1].y; float x3 = other.pt[0].x; float y3 = other.pt[0].y; float x4 = other.pt[1].x; float y4 = other.pt[1].y; float denom = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4); if (denom == 0) return false; if (intr) { float deta = x1 * y2 - y1 * x2; float detb = x3 * y4 - y3 * x4; intr->x = (deta * (x3 - x4) - (x1 - x2) * detb) / denom; intr->y = (deta * (y3 - y4) - (y1 - y2) * detb) / denom; } return true; } float Line::distTo(const Point &other) const { Point delta = pt[1] - pt[0]; float top = delta.x * (pt[0].y - other.y) - (pt[0].x - other.x) * delta.y; return fabs(top) / delta.mag(); } Point Line::nearestPoint(Point p) const { Point v_hat = delta().normalized(); return pt[0] + v_hat * v_hat.dot(p - pt[0]); } bool Line::intersects(const Circle& circle, Point* p1, Point* p2) const { //http://mathworld.wolfram.com/Circle-LineIntersection.html const float dx = pt[1].x - pt[0].x; const float dy = pt[1].y - pt[0].y; const float dr2 = dx*dx + dy*dy; const float r = circle.radius(); if (dx == 0 && dy == 0) return false; float det = pt[0].x * pt[1].y - pt[1].x * pt[0].y; float descr = r * r * dr2 - det*det; if (descr < 0) { return false; } float common = sqrt(descr); float x1 = det * dy; float x2 = sign(dy) * dx * common; float y1 = -det * dx; float y2 = fabs(dy) * common; if (p1) { float x = x1 + x2; float y = y1 + y2; *p1 = Point(x/dr2, y/dr2); } if (p2) { float x = x1 - x2; float y = y1 - y2; *p2 = Point(x/dr2, y/dr2); } return true; } <|endoftext|>
<commit_before>#include <GLXW/glxw.h> #include <iostream> #include <vector> #include <defer.h> #include "../assimp/include/assimp/Importer.hpp" #include "../assimp/include/assimp/postprocess.h" #include "../assimp/include/assimp/scene.h" #include "utils/models.h" GLfloat* importedModelCreate(const char* fname, unsigned int meshNumber, size_t* outVerticesBufferSize, unsigned int* outVerticesNumber) { *outVerticesBufferSize = 0; *outVerticesNumber = 0; Assimp::Importer importer; const aiScene* scene = importer.ReadFile(fname, aiProcess_CalcTangentSpace | aiProcess_Triangulate | aiProcess_JoinIdenticalVertices | aiProcess_SortByPType); if(scene == nullptr) { std::cerr << "Failed to load model " << fname << std::endl; return nullptr; } if(scene->mNumMeshes <= meshNumber) { std::cerr << "There is no mesh #" << meshNumber << " in model (" << scene->mNumMeshes << " only)" << fname << std::endl; return nullptr; } aiMesh* mesh = scene->mMeshes[meshNumber]; unsigned int facesNum = mesh->mNumFaces; // unsigned int verticesNum = mesh->mNumVertices; *outVerticesNumber = facesNum*3; if(mesh->mTextureCoords[0] == nullptr) { std::cerr << "mesh->mTextureCoords[0] == nullptr, fname = " << fname << std::endl; return nullptr; } *outVerticesBufferSize = facesNum*sizeof(GLfloat)* 5 /* coordinates per vertex */ * 3 /* 3 vertices per face */; GLfloat* verticesBuffer = (GLfloat*)malloc(*outVerticesBufferSize); unsigned int verticesBufferIndex = 0; for(unsigned int i = 0; i < facesNum; ++i) { const aiFace& face = mesh->mFaces[i]; if(face.mNumIndices != 3) { std::cerr << "face.numIndices = " << face.mNumIndices << " (3 expected), i = " << i << ", fname = " << fname << std::endl; free(verticesBuffer); return nullptr; } for(unsigned int j = 0; j < face.mNumIndices; ++j) { unsigned int index = face.mIndices[j]; aiVector3D pos = mesh->mVertices[index]; aiVector3D uv = mesh->mTextureCoords[0][index]; // aiVector3D normal = mesh->mNormals[index]; verticesBuffer[verticesBufferIndex++] = pos.x; verticesBuffer[verticesBufferIndex++] = pos.y; verticesBuffer[verticesBufferIndex++] = pos.z; verticesBuffer[verticesBufferIndex++] = uv.x; verticesBuffer[verticesBufferIndex++] = 1.0f - uv.y; } } return verticesBuffer; } bool importedModelSave(const char* fname, GLfloat* verticesBuffer, unsigned int verticesNumber) { std::vector<GLfloat> vertices; std::vector<unsigned int> indices; unsigned int usedIndices = 0; unsigned const int floatsPerVertex = 5; // 3 coordinates + UV const GLfloat eps = 0.00001f; for(unsigned int vtx = 0; vtx < verticesNumber; ++vtx) { GLfloat currentX = verticesBuffer[vtx* floatsPerVertex +0]; GLfloat currentY = verticesBuffer[vtx* floatsPerVertex +1]; GLfloat currentZ = verticesBuffer[vtx* floatsPerVertex +2]; GLfloat currentU = verticesBuffer[vtx* floatsPerVertex +3]; GLfloat currentV = verticesBuffer[vtx* floatsPerVertex +4]; unsigned int foundIndex = 0; bool indexFound = false; for(unsigned int idx = 0; !indexFound && idx < usedIndices; ++idx) { GLfloat idxX = vertices[idx * floatsPerVertex + 0]; GLfloat idxY = vertices[idx * floatsPerVertex + 1]; GLfloat idxZ = vertices[idx * floatsPerVertex + 2]; GLfloat idxU = vertices[idx * floatsPerVertex + 3]; GLfloat idxV = vertices[idx * floatsPerVertex + 4]; if((fabs(currentX - idxX) < eps) && (fabs(currentY - idxY) < eps) && (fabs(currentZ - idxZ) < eps) && (fabs(currentU - idxU) < eps) && (fabs(currentV - idxV) < eps)) { foundIndex = idx; indexFound = true; } } if(!indexFound) { vertices.push_back(currentX); vertices.push_back(currentY); vertices.push_back(currentZ); vertices.push_back(currentU); vertices.push_back(currentV); foundIndex = usedIndices; usedIndices++; } indices.push_back(foundIndex); } return modelSave(fname, vertices.data(), usedIndices* floatsPerVertex *sizeof(GLfloat), indices.data(), verticesNumber); } void importedModelFree(GLfloat* model) { free(model); } int main(int argc, char* argv[]) { if(argc < 2) { std::cout << "Usage: emdconv <input file> <output file>" << std::endl; return 1; } char* infile = argv[1]; char* outfile = argv[2]; std::cout << "Infile: " << infile << std::endl; std::cout << "Outfile: " << outfile << std::endl; unsigned int modelVerticesNumber; size_t modelVerticesBufferSize; GLfloat * modelVerticesBuffer = importedModelCreate(infile, 0, &modelVerticesBufferSize, &modelVerticesNumber); if(modelVerticesBuffer == nullptr) { std::cerr << "importedModelCreate returned null" << std::endl; return 2; } defer(importedModelFree(modelVerticesBuffer)); if(!importedModelSave(outfile, modelVerticesBuffer, modelVerticesNumber)) { std::cerr << "importedModelSave failed" << std::endl; return 3; } std::cout << "Done!" << std::endl; return 0; }<commit_msg>Print indexed model compression ratio<commit_after>#include <GLXW/glxw.h> #include <iostream> #include <vector> #include <defer.h> #include "../assimp/include/assimp/Importer.hpp" #include "../assimp/include/assimp/postprocess.h" #include "../assimp/include/assimp/scene.h" #include "utils/models.h" GLfloat* importedModelCreate(const char* fname, unsigned int meshNumber, size_t* outVerticesBufferSize, unsigned int* outVerticesNumber) { *outVerticesBufferSize = 0; *outVerticesNumber = 0; Assimp::Importer importer; const aiScene* scene = importer.ReadFile(fname, aiProcess_CalcTangentSpace | aiProcess_Triangulate | aiProcess_JoinIdenticalVertices | aiProcess_SortByPType); if(scene == nullptr) { std::cerr << "Failed to load model " << fname << std::endl; return nullptr; } if(scene->mNumMeshes <= meshNumber) { std::cerr << "There is no mesh #" << meshNumber << " in model (" << scene->mNumMeshes << " only)" << fname << std::endl; return nullptr; } aiMesh* mesh = scene->mMeshes[meshNumber]; unsigned int facesNum = mesh->mNumFaces; // unsigned int verticesNum = mesh->mNumVertices; *outVerticesNumber = facesNum*3; if(mesh->mTextureCoords[0] == nullptr) { std::cerr << "mesh->mTextureCoords[0] == nullptr, fname = " << fname << std::endl; return nullptr; } *outVerticesBufferSize = facesNum*sizeof(GLfloat)* 5 /* coordinates per vertex */ * 3 /* 3 vertices per face */; GLfloat* verticesBuffer = (GLfloat*)malloc(*outVerticesBufferSize); unsigned int verticesBufferIndex = 0; for(unsigned int i = 0; i < facesNum; ++i) { const aiFace& face = mesh->mFaces[i]; if(face.mNumIndices != 3) { std::cerr << "face.numIndices = " << face.mNumIndices << " (3 expected), i = " << i << ", fname = " << fname << std::endl; free(verticesBuffer); return nullptr; } for(unsigned int j = 0; j < face.mNumIndices; ++j) { unsigned int index = face.mIndices[j]; aiVector3D pos = mesh->mVertices[index]; aiVector3D uv = mesh->mTextureCoords[0][index]; // aiVector3D normal = mesh->mNormals[index]; verticesBuffer[verticesBufferIndex++] = pos.x; verticesBuffer[verticesBufferIndex++] = pos.y; verticesBuffer[verticesBufferIndex++] = pos.z; verticesBuffer[verticesBufferIndex++] = uv.x; verticesBuffer[verticesBufferIndex++] = 1.0f - uv.y; } } return verticesBuffer; } bool importedModelSave(const char* fname, GLfloat* verticesBuffer, unsigned int verticesNumber) { std::vector<GLfloat> vertices; std::vector<unsigned int> indices; unsigned int usedIndices = 0; unsigned const int floatsPerVertex = 5; // 3 coordinates + UV const GLfloat eps = 0.00001f; for(unsigned int vtx = 0; vtx < verticesNumber; ++vtx) { GLfloat currentX = verticesBuffer[vtx* floatsPerVertex +0]; GLfloat currentY = verticesBuffer[vtx* floatsPerVertex +1]; GLfloat currentZ = verticesBuffer[vtx* floatsPerVertex +2]; GLfloat currentU = verticesBuffer[vtx* floatsPerVertex +3]; GLfloat currentV = verticesBuffer[vtx* floatsPerVertex +4]; unsigned int foundIndex = 0; bool indexFound = false; for(unsigned int idx = 0; !indexFound && idx < usedIndices; ++idx) { GLfloat idxX = vertices[idx * floatsPerVertex + 0]; GLfloat idxY = vertices[idx * floatsPerVertex + 1]; GLfloat idxZ = vertices[idx * floatsPerVertex + 2]; GLfloat idxU = vertices[idx * floatsPerVertex + 3]; GLfloat idxV = vertices[idx * floatsPerVertex + 4]; if((fabs(currentX - idxX) < eps) && (fabs(currentY - idxY) < eps) && (fabs(currentZ - idxZ) < eps) && (fabs(currentU - idxU) < eps) && (fabs(currentV - idxV) < eps)) { foundIndex = idx; indexFound = true; } } if(!indexFound) { vertices.push_back(currentX); vertices.push_back(currentY); vertices.push_back(currentZ); vertices.push_back(currentU); vertices.push_back(currentV); foundIndex = usedIndices; usedIndices++; } indices.push_back(foundIndex); } unsigned char indexSize = 1; if(verticesNumber > 255) indexSize *= 2; if(verticesNumber > 65535) indexSize *= 2; unsigned int modelSize = (unsigned int) (verticesNumber*floatsPerVertex*sizeof(GLfloat)); unsigned int indexedModelSize = (unsigned int) (usedIndices*floatsPerVertex*sizeof(GLfloat) + verticesNumber*indexSize); float ratio = (float)indexedModelSize*100.0f / (float)modelSize; std::cout << "importedModelSave - fname = " << fname << ", verticesNumber = " << verticesNumber << ", usedIndices = " << usedIndices << std::endl; std::cout << "importedModelSave - modelSize = " << modelSize << ", indexedModelSize = " << indexedModelSize << ", ratio = " << ratio << " %" << std::endl; return modelSave(fname, vertices.data(), usedIndices* floatsPerVertex *sizeof(GLfloat), indices.data(), verticesNumber); } void importedModelFree(GLfloat* model) { free(model); } int main(int argc, char* argv[]) { if(argc < 2) { std::cout << "Usage: emdconv <input file> <output file>" << std::endl; return 1; } char* infile = argv[1]; char* outfile = argv[2]; std::cout << "Infile: " << infile << std::endl; std::cout << "Outfile: " << outfile << std::endl; unsigned int modelVerticesNumber; size_t modelVerticesBufferSize; GLfloat * modelVerticesBuffer = importedModelCreate(infile, 0, &modelVerticesBufferSize, &modelVerticesNumber); if(modelVerticesBuffer == nullptr) { std::cerr << "importedModelCreate returned null" << std::endl; return 2; } defer(importedModelFree(modelVerticesBuffer)); if(!importedModelSave(outfile, modelVerticesBuffer, modelVerticesNumber)) { std::cerr << "importedModelSave failed" << std::endl; return 3; } std::cout << "Done!" << std::endl; return 0; }<|endoftext|>
<commit_before>// WatchdogLog - logs program address to EEPROM before watchdog timeout MCU reset https://github.com/per1234/WatchdogLog #include "WatchdogLog.h" //determine the size of the program counter based on flash size #ifdef FLASHEND #if FLASHEND > 65535 const byte programCounterSize = 3; //bytes #else //FLASHEND > 65535 const byte programCounterSize = 2; //bytes #endif //FLASHEND > 65535 #else //FLASHEND const byte programCounterSize = 2; //bytes #endif //FLASHEND /* Function called when the watchdog interrupt fires. The function is naked so that we don't get program stated pushed onto the stack. Consequently the top programCounterSize values on the stack will be the program counter when the interrupt fired. We're going to save that in the EEPROM then let the second watchdog event reset the MCU. We never return from this function. */ ISR(WDT_vect, ISR_NAKED) { register uint8_t *programCounter; //Setup a pointer to the program counter. It goes in a register so we don't mess up the stack. programCounter = (uint8_t*)SP; /* The stack pointer on the AVR micro points to the next available location so we want to go back one location to get the first byte of the address pushed onto the stack when the interrupt was triggered. There will be programCounterSize bytes there. */ programCounter += programCounterSize; WatchdogLog.writeLog(programCounter); } WatchdogLogClass::WatchdogLogClass() { } boolean WatchdogLogClass::begin(unsigned int EEPROMbaseAddressInput) { if (EEPROMbaseAddressInput > E2END - sizeof(unsigned int) + 1) { //base address sanity check return false; //invalid base address } EEPROMbaseAddress = EEPROMbaseAddressInput; //set the base EEPROM address for logging the program address WDTCSR |= _BV(WDIE); //set the watchdog timer to trigger an interrupt(WDT_vect) before resetting the micro return true; } void WatchdogLogClass::writeLog(uint8_t *programCounter) { wdt_disable(); //disable the watchdog until the log is written uint8_t programAddressArray[sizeof(unsigned long)]; //the stack has the bytes of the address in reverse order for (byte counter = 0; counter < programCounterSize; counter++) { programAddressArray[counter] = *programCounter; programCounter--; } //convert the array into unsigned long unsigned long programAddress; memcpy(&programAddress, programAddressArray, sizeof(unsigned long)); programAddress = programAddress * 2; //convert from word to byte eeprom_update_dword((unsigned long*)EEPROMbaseAddress, programAddress); //write the program address to the EEPROM //reset the MCU wdt_enable(WDTO_15MS); while (true) {}; } WatchdogLogClass WatchdogLog; <commit_msg>Use correct type in begin() sanity check<commit_after>// WatchdogLog - logs program address to EEPROM before watchdog timeout MCU reset https://github.com/per1234/WatchdogLog #include "WatchdogLog.h" //determine the size of the program counter based on flash size #ifdef FLASHEND #if FLASHEND > 65535 const byte programCounterSize = 3; //bytes #else //FLASHEND > 65535 const byte programCounterSize = 2; //bytes #endif //FLASHEND > 65535 #else //FLASHEND const byte programCounterSize = 2; //bytes #endif //FLASHEND /* Function called when the watchdog interrupt fires. The function is naked so that we don't get program stated pushed onto the stack. Consequently the top programCounterSize values on the stack will be the program counter when the interrupt fired. We're going to save that in the EEPROM then let the second watchdog event reset the MCU. We never return from this function. */ ISR(WDT_vect, ISR_NAKED) { register uint8_t *programCounter; //Setup a pointer to the program counter. It goes in a register so we don't mess up the stack. programCounter = (uint8_t*)SP; /* The stack pointer on the AVR micro points to the next available location so we want to go back one location to get the first byte of the address pushed onto the stack when the interrupt was triggered. There will be programCounterSize bytes there. */ programCounter += programCounterSize; WatchdogLog.writeLog(programCounter); } WatchdogLogClass::WatchdogLogClass() { } boolean WatchdogLogClass::begin(unsigned int EEPROMbaseAddressInput) { if (EEPROMbaseAddressInput > E2END - sizeof(unsigned long) + 1) { //base address sanity check return false; //invalid base address } EEPROMbaseAddress = EEPROMbaseAddressInput; //set the base EEPROM address for logging the program address WDTCSR |= _BV(WDIE); //set the watchdog timer to trigger an interrupt(WDT_vect) before resetting the micro return true; } void WatchdogLogClass::writeLog(uint8_t *programCounter) { wdt_disable(); //disable the watchdog until the log is written uint8_t programAddressArray[sizeof(unsigned long)]; //the stack has the bytes of the address in reverse order for (byte counter = 0; counter < programCounterSize; counter++) { programAddressArray[counter] = *programCounter; programCounter--; } //convert the array into unsigned long unsigned long programAddress; memcpy(&programAddress, programAddressArray, sizeof(unsigned long)); programAddress = programAddress * 2; //convert from word to byte eeprom_update_dword((unsigned long*)EEPROMbaseAddress, programAddress); //write the program address to the EEPROM //reset the MCU wdt_enable(WDTO_15MS); while (true) {}; } WatchdogLogClass WatchdogLog; <|endoftext|>
<commit_before>#include <iostream> #include "lcm/lcm-cpp.hpp" #include "Automatic.h" #include "common/CallbackHandler.hpp" #include "poll.h" #include "Command/TakeOff.hpp" using namespace common; int main(int argc, char** argv){ lcm::LCM handler, handler2, handler3; if (!handler.good() && !handler2.good() && !handler3.good()) return 1; CallbackHandler call; Automatic autom; Lander lander; lcm::Subscription *sub = handler.subscribe("vision_position_estimate", &CallbackHandler::visionEstimateCallback, &call); lcm::Subscription *sub2 = handler2.subscribe("platform/pose", &CallbackHandler::positionSetpointCallback, &call); lcm::Subscription *sub3 = handler3.subscribe("actual_task", &CallbackHandler::actualTaskCallback, &call); sub ->setQueueCapacity(1); sub2->setQueueCapacity(1); sub3->setQueueCapacity(1); struct pollfd fds[2]; fds[0].fd = handler3.getFileno(); // Actual task fds[0].events = POLLIN; fds[1].fd = handler2.getFileno(); // Square pose fds[1].events = POLLIN; bool waiting = true; MavState platform; while(0==handler.handle()){ autom.setState(call._vision_pos); lander.setState(call._vision_pos); int ret = poll(fds,2,0); if(fds[0].revents & POLLIN){ handler3.handle(); autom.setTask(call._task); std::cout<< "New task arrived with action: " << printAction(autom._actualTask.action) << std::endl; waiting = false; autom.handleCommands(); } if(fds[1].revents & POLLIN){ handler2.handle(); platform = call._position_sp; autom.setPlatformState(platform); } if(!waiting) { //Call commands autom.executeCommand(); //Prepare LCM stuff geometry::pose command = call.mavState2LcmPose(autom._comm); geometry::pose platRobPos; platRobPos.position[0] = platform.getX(); platRobPos.position[1] = platform.getY(); platRobPos.position[2] = platform.getZ(); platRobPos.velocity[0] = platform.getVx(); platRobPos.velocity[1] = platform.getVy(); platRobPos.velocity[2] = platform.getVz(); handler.publish("local_position_sp", &command); //For gazebo visualization with the marker plugin handler.publish("Marker/pose_cmd", &command); handler3.publish("platRob", &platRobPos); } } return 0; } <commit_msg>clean<commit_after>#include <iostream> #include "lcm/lcm-cpp.hpp" #include "Automatic.h" #include "common/CallbackHandler.hpp" #include "poll.h" using namespace common; int main(int argc, char** argv){ lcm::LCM handler, handler2, handler3; if (!handler.good() && !handler2.good() && !handler3.good()) return 1; CallbackHandler call; Automatic autom; Lander lander; lcm::Subscription *sub = handler.subscribe("vision_position_estimate", &CallbackHandler::visionEstimateCallback, &call); lcm::Subscription *sub2 = handler2.subscribe("platform/pose", &CallbackHandler::positionSetpointCallback, &call); lcm::Subscription *sub3 = handler3.subscribe("actual_task", &CallbackHandler::actualTaskCallback, &call); sub ->setQueueCapacity(1); sub2->setQueueCapacity(1); sub3->setQueueCapacity(1); struct pollfd fds[2]; fds[0].fd = handler3.getFileno(); // Actual task fds[0].events = POLLIN; fds[1].fd = handler2.getFileno(); // Square pose fds[1].events = POLLIN; bool waiting = true; MavState platform; while(0==handler.handle()){ autom.setState(call._vision_pos); lander.setState(call._vision_pos); int ret = poll(fds,2,0); if(fds[0].revents & POLLIN){ handler3.handle(); autom.setTask(call._task); std::cout<< "New task arrived with action: " << printAction(autom._actualTask.action) << std::endl; waiting = false; autom.handleCommands(); } if(fds[1].revents & POLLIN){ handler2.handle(); platform = call._position_sp; autom.setPlatformState(platform); } if(!waiting) { //Call commands autom.executeCommand(); //Prepare LCM stuff geometry::pose command = call.mavState2LcmPose(autom._comm); geometry::pose platRobPos; platRobPos.position[0] = platform.getX(); platRobPos.position[1] = platform.getY(); platRobPos.position[2] = platform.getZ(); platRobPos.velocity[0] = platform.getVx(); platRobPos.velocity[1] = platform.getVy(); platRobPos.velocity[2] = platform.getVz(); handler.publish("local_position_sp", &command); //For gazebo visualization with the marker plugin handler.publish("Marker/pose_cmd", &command); handler3.publish("platRob", &platRobPos); } } return 0; } <|endoftext|>
<commit_before>#include "HttpClient.hpp" #include "Timer.hpp" #include <iostream> #include <sstream> #include <string> #include <stdexcept> using namespace Kite; class Kite::HttpClientPrivate { public: HttpClientPrivate() { state = 0; responseCode = 999; } void setUrl(const std::string &url, const std::string &verb) { d_path = "/"; d_host.clear(); d_verb = verb; p_buf.clear(); std::istringstream ss(url); std::string token; int at = 0; while (std::getline(ss, token, '/')) { if (at == 0) { if (token == "https:") { d_is_https = true; } else if (token == "http:") { d_is_https = false; } else { throw std::invalid_argument("unsupported url schema " + token); } } else if (at == 2) { std::istringstream s2(token); std::getline(s2, d_host, ':'); std::getline(s2, token, ':'); try { d_port = std::stoi(token); } catch (std::invalid_argument&) { d_port = d_is_https ? 443 : 80; } } else if (at > 2) { d_path += "/" + token; } ++at; } } void d_write(const char *buf, int len) { if (p_buf.length() + len > 4048) throw std::runtime_error("overflow"); p_buf.reserve(p_buf.length() + len); for (int i = 0; i < len; i++) { p_buf += buf[i]; if (state < HttpClient::HeaderCompleted) { if (buf[i] == '\n') { onLine(p_buf); p_buf.clear(); } } else { } } } void onLine(const std::string &line) { if (state == Kite::HttpClient::Connected) { std::istringstream ss(line); std::string httpd; ss >> httpd; ss >> responseCode; state = Kite::HttpClient::StatusCompleted; } else { if (line == "\r\n") { state = HttpClient::HeaderCompleted; } } } std::map<std::string,std::string> headers; int responseCode; HttpClient::Status status; int state; std::string d_verb; bool d_is_https; std::string d_host; int d_port; std::string d_path; std::string d_post_body; friend class HttpClient; std::string p_buf; HttpClient *p; }; /////////////////////////////////////////////////////////////////////////////// HttpClient::HttpClient(std::weak_ptr<Kite::EventLoop> ev) : Kite::SecureSocket(ev) , p(new HttpClientPrivate) { p->p = this; } HttpClient::~HttpClient() { delete p; } void HttpClient::get(const std::string &url) { p->setUrl(url, "GET"); p->status = Kite::HttpClient::Connecting; connect(p->d_host, p->d_port, 5000, p->d_is_https); } void HttpClient::post(const std::string &url, const std::string &body) { p->setUrl(url, "POST"); p->status = Kite::HttpClient::Connecting; p->d_post_body = body; connect(p->d_host, p->d_port, 5000, p->d_is_https); } void HttpClient::onActivated(int) { char buf [102]; int r = read(buf, 100); buf[r] = 0; p->d_write(buf, r); if (r == 0) { disconnect(); return; } } void HttpClient::onDisconnected(SocketState state) { onFinished(p->status, p->responseCode, p->p_buf); } void HttpClient::onConnected() { p->state = Kite::HttpClient::Connected; std::stringstream ss; ss << p->d_verb << " " << p->d_path << " HTTP/1.1\r\n"; ss << "Host: " << p->d_host << "\r\n"; for (auto it = p->headers.begin(); it != p->headers.end(); ++it) { ss << it->first << ": " << it->second << "\r\n"; } if (p->d_verb == "POST") { ss << "Content-Length: " << p->d_post_body.length() << "\r\n"; } else { ss << "Connection: close\r\n"; } ss << "\r\n"; ss << p->d_post_body; write(ss.str().c_str(), ss.str().length()); } void HttpClient::setHeaders(std::map<std::string,std::string> headers) { p->headers = headers; } <commit_msg>close connection in post too<commit_after>#include "HttpClient.hpp" #include "Timer.hpp" #include <iostream> #include <sstream> #include <string> #include <stdexcept> using namespace Kite; class Kite::HttpClientPrivate { public: HttpClientPrivate() { state = 0; responseCode = 999; } void setUrl(const std::string &url, const std::string &verb) { d_path = "/"; d_host.clear(); d_verb = verb; p_buf.clear(); std::istringstream ss(url); std::string token; int at = 0; while (std::getline(ss, token, '/')) { if (at == 0) { if (token == "https:") { d_is_https = true; } else if (token == "http:") { d_is_https = false; } else { throw std::invalid_argument("unsupported url schema " + token); } } else if (at == 2) { std::istringstream s2(token); std::getline(s2, d_host, ':'); std::getline(s2, token, ':'); try { d_port = std::stoi(token); } catch (std::invalid_argument&) { d_port = d_is_https ? 443 : 80; } } else if (at > 2) { d_path += "/" + token; } ++at; } } void d_write(const char *buf, int len) { if (p_buf.length() + len > 4048) throw std::runtime_error("overflow"); p_buf.reserve(p_buf.length() + len); for (int i = 0; i < len; i++) { p_buf += buf[i]; if (state < HttpClient::HeaderCompleted) { if (buf[i] == '\n') { onLine(p_buf); p_buf.clear(); } } else { } } } void onLine(const std::string &line) { if (state == Kite::HttpClient::Connected) { std::istringstream ss(line); std::string httpd; ss >> httpd; ss >> responseCode; state = Kite::HttpClient::StatusCompleted; } else { if (line == "\r\n") { state = HttpClient::HeaderCompleted; } } } std::map<std::string,std::string> headers; int responseCode; HttpClient::Status status; int state; std::string d_verb; bool d_is_https; std::string d_host; int d_port; std::string d_path; std::string d_post_body; friend class HttpClient; std::string p_buf; HttpClient *p; }; /////////////////////////////////////////////////////////////////////////////// HttpClient::HttpClient(std::weak_ptr<Kite::EventLoop> ev) : Kite::SecureSocket(ev) , p(new HttpClientPrivate) { p->p = this; } HttpClient::~HttpClient() { delete p; } void HttpClient::get(const std::string &url) { p->setUrl(url, "GET"); p->status = Kite::HttpClient::Connecting; connect(p->d_host, p->d_port, 5000, p->d_is_https); } void HttpClient::post(const std::string &url, const std::string &body) { p->setUrl(url, "POST"); p->status = Kite::HttpClient::Connecting; p->d_post_body = body; connect(p->d_host, p->d_port, 5000, p->d_is_https); } void HttpClient::onActivated(int) { char buf [102]; int r = read(buf, 100); buf[r] = 0; p->d_write(buf, r); if (r == 0) { disconnect(); return; } } void HttpClient::onDisconnected(SocketState state) { onFinished(p->status, p->responseCode, p->p_buf); } void HttpClient::onConnected() { p->state = Kite::HttpClient::Connected; std::stringstream ss; ss << p->d_verb << " " << p->d_path << " HTTP/1.1\r\n"; ss << "Host: " << p->d_host << "\r\n"; for (auto it = p->headers.begin(); it != p->headers.end(); ++it) { ss << it->first << ": " << it->second << "\r\n"; } if (p->d_verb == "POST") { ss << "Content-Length: " << p->d_post_body.length() << "\r\n"; } ss << "Connection: close\r\n"; ss << "\r\n"; ss << p->d_post_body; write(ss.str().c_str(), ss.str().length()); } void HttpClient::setHeaders(std::map<std::string,std::string> headers) { p->headers = headers; } <|endoftext|>
<commit_before>/* * Copyright 2013 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // This is heavily inspired by the signal handler from google-glog #include "folly/experimental/symbolizer/SignalHandler.h" #include <sys/types.h> #include <atomic> #include <ctime> #include <mutex> #include <pthread.h> #include <signal.h> #include <unistd.h> #include <vector> #include <glog/logging.h> #include "folly/Conv.h" #include "folly/FileUtil.h" #include "folly/Portability.h" #include "folly/ScopeGuard.h" #include "folly/experimental/symbolizer/Symbolizer.h" namespace folly { namespace symbolizer { namespace { /** * Fatal signal handler registry. */ class FatalSignalCallbackRegistry { public: FatalSignalCallbackRegistry(); void add(SignalCallback func); void markInstalled(); void run(); private: std::atomic<bool> installed_; std::mutex mutex_; std::vector<SignalCallback> handlers_; }; FatalSignalCallbackRegistry::FatalSignalCallbackRegistry() : installed_(false) { } void FatalSignalCallbackRegistry::add(SignalCallback func) { std::lock_guard<std::mutex> lock(mutex_); CHECK(!installed_) << "FatalSignalCallbackRegistry::add may not be used " "after installing the signal handlers."; handlers_.push_back(func); } void FatalSignalCallbackRegistry::markInstalled() { std::lock_guard<std::mutex> lock(mutex_); CHECK(!installed_.exchange(true)) << "FatalSignalCallbackRegistry::markInstalled must be called " << "at most once"; } void FatalSignalCallbackRegistry::run() { if (!installed_) { return; } for (auto& fn : handlers_) { fn(); } } // Leak it so we don't have to worry about destruction order FatalSignalCallbackRegistry* gFatalSignalCallbackRegistry = new FatalSignalCallbackRegistry; struct { int number; const char* name; struct sigaction oldAction; } kFatalSignals[] = { { SIGSEGV, "SIGSEGV" }, { SIGILL, "SIGILL" }, { SIGFPE, "SIGFPE" }, { SIGABRT, "SIGABRT" }, { SIGBUS, "SIGBUS" }, { SIGTERM, "SIGTERM" }, { 0, nullptr } }; void callPreviousSignalHandler(int signum) { // Restore disposition to old disposition, then kill ourselves with the same // signal. The signal will be blocked until we return from our handler, // then it will invoke the default handler and abort. for (auto p = kFatalSignals; p->name; ++p) { if (p->number == signum) { sigaction(signum, &p->oldAction, nullptr); return; } } // Not one of the signals we know about. Oh well. Reset to default. struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_handler = SIG_DFL; sigaction(signum, &sa, nullptr); raise(signum); } void printDec(uint64_t val) { char buf[20]; uint32_t n = uint64ToBufferUnsafe(val, buf); writeFull(STDERR_FILENO, buf, n); } const char kHexChars[] = "0123456789abcdef"; void printHex(uint64_t val) { // TODO(tudorb): Add this to folly/Conv.h char buf[2 + 2 * sizeof(uint64_t)]; // "0x" prefix, 2 digits for each byte char* end = buf + sizeof(buf); char* p = end; do { *--p = kHexChars[val & 0x0f]; val >>= 4; } while (val != 0); *--p = 'x'; *--p = '0'; writeFull(STDERR_FILENO, p, end - p); } void print(StringPiece sp) { writeFull(STDERR_FILENO, sp.data(), sp.size()); } void dumpTimeInfo() { SCOPE_EXIT { fsyncNoInt(STDERR_FILENO); }; time_t now = time(nullptr); print("*** Aborted at "); printDec(now); print(" (Unix time, try 'date -d @"); printDec(now); print("') ***\n"); } void dumpSignalInfo(int signum, siginfo_t* siginfo) { SCOPE_EXIT { fsyncNoInt(STDERR_FILENO); }; // Get the signal name, if possible. const char* name = nullptr; for (auto p = kFatalSignals; p->name; ++p) { if (p->number == signum) { name = p->name; break; } } print("*** Signal "); printDec(signum); if (name) { print(" ("); print(name); print(")"); } print(" ("); printHex(reinterpret_cast<uint64_t>(siginfo->si_addr)); print(") received by PID "); printDec(getpid()); print(" (TID "); printHex((uint64_t)pthread_self()); print("), stack trace: ***\n"); } void dumpStackTrace() { SCOPE_EXIT { fsyncNoInt(STDERR_FILENO); }; // Get and symbolize stack trace constexpr size_t kMaxStackTraceDepth = 100; FrameArray<kMaxStackTraceDepth> addresses; // Skip the getStackTrace frame if (!getStackTrace(addresses)) { print("(error retrieving stack trace)\n"); } else { Symbolizer symbolizer; symbolizer.symbolize(addresses); FDSymbolizePrinter printer(STDERR_FILENO); printer.println(addresses); } } std::atomic<pthread_t*> gSignalThread; // Here be dragons. void innerSignalHandler(int signum, siginfo_t* info, void* uctx) { // First, let's only let one thread in here at a time. pthread_t myId = pthread_self(); pthread_t* prevSignalThread = nullptr; while (!gSignalThread.compare_exchange_strong(prevSignalThread, &myId)) { if (pthread_equal(*prevSignalThread, myId)) { print("Entered fatal signal handler recursively. We're in trouble.\n"); return; } // Wait a while, try again. timespec ts; ts.tv_sec = 0; ts.tv_nsec = 100L * 1000 * 1000; // 100ms nanosleep(&ts, nullptr); prevSignalThread = nullptr; } dumpTimeInfo(); dumpSignalInfo(signum, info); dumpStackTrace(); // Run user callbacks gFatalSignalCallbackRegistry->run(); } void signalHandler(int signum, siginfo_t* info, void* uctx) { SCOPE_EXIT { fsyncNoInt(STDERR_FILENO); }; innerSignalHandler(signum, info, uctx); gSignalThread = nullptr; // Kill ourselves with the previous handler. callPreviousSignalHandler(signum); } } // namespace void addFatalSignalCallback(SignalCallback cb) { gFatalSignalCallbackRegistry->add(cb); } void installFatalSignalCallbacks() { gFatalSignalCallbackRegistry->markInstalled(); } namespace { std::atomic<bool> gAlreadyInstalled; } // namespace void installFatalSignalHandler() { if (gAlreadyInstalled.exchange(true)) { // Already done. return; } struct sigaction sa; memset(&sa, 0, sizeof(sa)); sigemptyset(&sa.sa_mask); sa.sa_flags |= SA_SIGINFO; sa.sa_sigaction = &signalHandler; for (auto p = kFatalSignals; p->name; ++p) { CHECK_ERR(sigaction(p->number, &sa, &p->oldAction)); } } }} // namespaces <commit_msg>fix callPreviousSignalHandler()<commit_after>/* * Copyright 2013 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // This is heavily inspired by the signal handler from google-glog #include "folly/experimental/symbolizer/SignalHandler.h" #include <sys/types.h> #include <atomic> #include <ctime> #include <mutex> #include <pthread.h> #include <signal.h> #include <unistd.h> #include <vector> #include <glog/logging.h> #include "folly/Conv.h" #include "folly/FileUtil.h" #include "folly/Portability.h" #include "folly/ScopeGuard.h" #include "folly/experimental/symbolizer/Symbolizer.h" namespace folly { namespace symbolizer { namespace { /** * Fatal signal handler registry. */ class FatalSignalCallbackRegistry { public: FatalSignalCallbackRegistry(); void add(SignalCallback func); void markInstalled(); void run(); private: std::atomic<bool> installed_; std::mutex mutex_; std::vector<SignalCallback> handlers_; }; FatalSignalCallbackRegistry::FatalSignalCallbackRegistry() : installed_(false) { } void FatalSignalCallbackRegistry::add(SignalCallback func) { std::lock_guard<std::mutex> lock(mutex_); CHECK(!installed_) << "FatalSignalCallbackRegistry::add may not be used " "after installing the signal handlers."; handlers_.push_back(func); } void FatalSignalCallbackRegistry::markInstalled() { std::lock_guard<std::mutex> lock(mutex_); CHECK(!installed_.exchange(true)) << "FatalSignalCallbackRegistry::markInstalled must be called " << "at most once"; } void FatalSignalCallbackRegistry::run() { if (!installed_) { return; } for (auto& fn : handlers_) { fn(); } } // Leak it so we don't have to worry about destruction order FatalSignalCallbackRegistry* gFatalSignalCallbackRegistry = new FatalSignalCallbackRegistry; struct { int number; const char* name; struct sigaction oldAction; } kFatalSignals[] = { { SIGSEGV, "SIGSEGV" }, { SIGILL, "SIGILL" }, { SIGFPE, "SIGFPE" }, { SIGABRT, "SIGABRT" }, { SIGBUS, "SIGBUS" }, { SIGTERM, "SIGTERM" }, { 0, nullptr } }; void callPreviousSignalHandler(int signum) { // Restore disposition to old disposition, then kill ourselves with the same // signal. The signal will be blocked until we return from our handler, // then it will invoke the default handler and abort. for (auto p = kFatalSignals; p->name; ++p) { if (p->number == signum) { sigaction(signum, &p->oldAction, nullptr); raise(signum); return; } } // Not one of the signals we know about. Oh well. Reset to default. struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_handler = SIG_DFL; sigaction(signum, &sa, nullptr); raise(signum); } void printDec(uint64_t val) { char buf[20]; uint32_t n = uint64ToBufferUnsafe(val, buf); writeFull(STDERR_FILENO, buf, n); } const char kHexChars[] = "0123456789abcdef"; void printHex(uint64_t val) { // TODO(tudorb): Add this to folly/Conv.h char buf[2 + 2 * sizeof(uint64_t)]; // "0x" prefix, 2 digits for each byte char* end = buf + sizeof(buf); char* p = end; do { *--p = kHexChars[val & 0x0f]; val >>= 4; } while (val != 0); *--p = 'x'; *--p = '0'; writeFull(STDERR_FILENO, p, end - p); } void print(StringPiece sp) { writeFull(STDERR_FILENO, sp.data(), sp.size()); } void dumpTimeInfo() { SCOPE_EXIT { fsyncNoInt(STDERR_FILENO); }; time_t now = time(nullptr); print("*** Aborted at "); printDec(now); print(" (Unix time, try 'date -d @"); printDec(now); print("') ***\n"); } void dumpSignalInfo(int signum, siginfo_t* siginfo) { SCOPE_EXIT { fsyncNoInt(STDERR_FILENO); }; // Get the signal name, if possible. const char* name = nullptr; for (auto p = kFatalSignals; p->name; ++p) { if (p->number == signum) { name = p->name; break; } } print("*** Signal "); printDec(signum); if (name) { print(" ("); print(name); print(")"); } print(" ("); printHex(reinterpret_cast<uint64_t>(siginfo->si_addr)); print(") received by PID "); printDec(getpid()); print(" (TID "); printHex((uint64_t)pthread_self()); print("), stack trace: ***\n"); } void dumpStackTrace() { SCOPE_EXIT { fsyncNoInt(STDERR_FILENO); }; // Get and symbolize stack trace constexpr size_t kMaxStackTraceDepth = 100; FrameArray<kMaxStackTraceDepth> addresses; // Skip the getStackTrace frame if (!getStackTrace(addresses)) { print("(error retrieving stack trace)\n"); } else { Symbolizer symbolizer; symbolizer.symbolize(addresses); FDSymbolizePrinter printer(STDERR_FILENO); printer.println(addresses); } } std::atomic<pthread_t*> gSignalThread; // Here be dragons. void innerSignalHandler(int signum, siginfo_t* info, void* uctx) { // First, let's only let one thread in here at a time. pthread_t myId = pthread_self(); pthread_t* prevSignalThread = nullptr; while (!gSignalThread.compare_exchange_strong(prevSignalThread, &myId)) { if (pthread_equal(*prevSignalThread, myId)) { print("Entered fatal signal handler recursively. We're in trouble.\n"); return; } // Wait a while, try again. timespec ts; ts.tv_sec = 0; ts.tv_nsec = 100L * 1000 * 1000; // 100ms nanosleep(&ts, nullptr); prevSignalThread = nullptr; } dumpTimeInfo(); dumpSignalInfo(signum, info); dumpStackTrace(); // Run user callbacks gFatalSignalCallbackRegistry->run(); } void signalHandler(int signum, siginfo_t* info, void* uctx) { SCOPE_EXIT { fsyncNoInt(STDERR_FILENO); }; innerSignalHandler(signum, info, uctx); gSignalThread = nullptr; // Kill ourselves with the previous handler. callPreviousSignalHandler(signum); } } // namespace void addFatalSignalCallback(SignalCallback cb) { gFatalSignalCallbackRegistry->add(cb); } void installFatalSignalCallbacks() { gFatalSignalCallbackRegistry->markInstalled(); } namespace { std::atomic<bool> gAlreadyInstalled; } // namespace void installFatalSignalHandler() { if (gAlreadyInstalled.exchange(true)) { // Already done. return; } struct sigaction sa; memset(&sa, 0, sizeof(sa)); sigemptyset(&sa.sa_mask); sa.sa_flags |= SA_SIGINFO; sa.sa_sigaction = &signalHandler; for (auto p = kFatalSignals; p->name; ++p) { CHECK_ERR(sigaction(p->number, &sa, &p->oldAction)); } } }} // namespaces <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2010-2013, Image Engine Design 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 Image Engine Design nor the names of any // other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "UT/UT_StringMMPattern.h" #include "IECore/CompoundData.h" #include "IECore/CompoundParameter.h" #include "IECore/MessageHandler.h" #include "IECoreHoudini/Convert.h" #include "IECoreHoudini/ToHoudiniAttribConverter.h" #include "IECoreHoudini/ToHoudiniGeometryConverter.h" #include "IECoreHoudini/ToHoudiniStringAttribConverter.h" using namespace IECore; using namespace IECoreHoudini; IE_CORE_DEFINERUNTIMETYPED( ToHoudiniGeometryConverter ); ToHoudiniGeometryConverter::ToHoudiniGeometryConverter( const IECore::Object *object, const std::string &description ) : ToHoudiniConverter( description, ObjectTypeId ) { srcParameter()->setValue( const_cast<Object*>( object ) ); // safe because the object is const in doConversion m_nameParameter = new StringParameter( "name", "The name given to the converted primitive(s). If empty, primitives will be unnamed", "" ); m_attributeFilterParameter = new StringParameter( "attributeFilter", "A list of attribute names to convert, if they exist. Uses Houdini matching syntax.", "*" ); m_convertStandardAttributesParameter = new BoolParameter( "convertStandardAttributes", "Performs automated conversion of standard PrimitiveVariables to Houdini Attributes (i.e. Pref->rest ; Cs->Cd ; s,t->uv)", true ); parameters()->addParameter( m_nameParameter ); parameters()->addParameter( m_attributeFilterParameter ); parameters()->addParameter( m_convertStandardAttributesParameter ); } ToHoudiniGeometryConverter::~ToHoudiniGeometryConverter() { } BoolParameter *ToHoudiniGeometryConverter::convertStandardAttributesParameter() { return m_convertStandardAttributesParameter; } const BoolParameter *ToHoudiniGeometryConverter::convertStandardAttributesParameter() const { return m_convertStandardAttributesParameter; } StringParameter *ToHoudiniGeometryConverter::nameParameter() { return m_nameParameter; } const StringParameter *ToHoudiniGeometryConverter::nameParameter() const { return m_nameParameter; } StringParameter *ToHoudiniGeometryConverter::attributeFilterParameter() { return m_attributeFilterParameter; } const StringParameter *ToHoudiniGeometryConverter::attributeFilterParameter() const { return m_attributeFilterParameter; } bool ToHoudiniGeometryConverter::convert( GU_DetailHandle handle ) const { ConstCompoundObjectPtr operands = parameters()->getTypedValidatedValue<CompoundObject>(); GU_DetailHandleAutoWriteLock writeHandle( handle ); GU_Detail *geo = writeHandle.getGdp(); if ( !geo ) { return false; } return doConversion( srcParameter()->getValidatedValue(), geo ); } GA_Range ToHoudiniGeometryConverter::appendPoints( GA_Detail *geo, size_t numPoints ) const { if ( !numPoints ) { return GA_Range(); } GA_OffsetList offsets; offsets.reserve( numPoints ); for ( size_t i=0; i < numPoints; ++i ) { offsets.append( geo->appendPoint() ); } return GA_Range( geo->getPointMap(), offsets ); } PrimitiveVariable ToHoudiniGeometryConverter::processPrimitiveVariable( const IECore::Primitive *primitive, const PrimitiveVariable &primVar ) const { return primVar; } void ToHoudiniGeometryConverter::transferAttribs( GU_Detail *geo, const GA_Range &points, const GA_Range &prims ) const { const Primitive *primitive = IECore::runTimeCast<const Primitive>( srcParameter()->getValidatedValue() ); if ( primitive ) { transferAttribValues( primitive, geo, points, prims ); } setName( geo, prims ); } void ToHoudiniGeometryConverter::setName( GU_Detail *geo, const GA_Range &prims ) const { // add the name attribute based on the parameter const std::string &name = nameParameter()->getTypedValue(); if ( name != "" && prims.isValid() ) { ToHoudiniStringVectorAttribConverter::convertString( "name", name, geo, prims ); } } void ToHoudiniGeometryConverter::transferAttribValues( const Primitive *primitive, GU_Detail *geo, const GA_Range &points, const GA_Range &prims, PrimitiveVariable::Interpolation vertexInterpolation, PrimitiveVariable::Interpolation primitiveInterpolation, PrimitiveVariable::Interpolation pointInterpolation, PrimitiveVariable::Interpolation detailInterpolation ) const { GA_OffsetList offsets; if ( prims.isValid() ) { const GA_PrimitiveList &primitives = geo->getPrimitiveList(); for ( GA_Iterator it=prims.begin(); !it.atEnd(); ++it ) { const GA_Primitive *prim = primitives.get( it.getOffset() ); size_t numPrimVerts = prim->getVertexCount(); for ( size_t v=0; v < numPrimVerts; v++ ) { if ( prim->getTypeId() == GEO_PRIMPOLY ) { offsets.append( prim->getVertexOffset( numPrimVerts - 1 - v ) ); } else { offsets.append( prim->getVertexOffset( v ) ); } } } } GA_Range vertRange( geo->getVertexMap(), offsets ); UT_String filter( attributeFilterParameter()->getTypedValue() ); // match all the string variables to each associated indices variable /// \todo: replace all this logic with IECore::IndexedData once it exists... PrimitiveVariableMap stringsToIndices; for ( PrimitiveVariableMap::const_iterator it=primitive->variables.begin() ; it != primitive->variables.end(); it++ ) { if ( !primitive->isPrimitiveVariableValid( it->second ) ) { IECore::msg( IECore::MessageHandler::Warning, "ToHoudiniGeometryConverter", "PrimitiveVariable " + it->first + " is invalid. Ignoring." ); filter += UT_String( " ^" + it->first ); continue; } ToHoudiniAttribConverterPtr converter = ToHoudiniAttribConverter::create( it->second.data ); if ( !converter ) { continue; } if ( it->second.data->isInstanceOf( StringVectorDataTypeId ) ) { std::string indicesVariableName = it->first + "Indices"; PrimitiveVariableMap::const_iterator indices = primitive->variables.find( indicesVariableName ); if ( indices != primitive->variables.end() && indices->second.data->isInstanceOf( IntVectorDataTypeId ) && primitive->isPrimitiveVariableValid( indices->second ) ) { stringsToIndices[it->first] = indices->second; filter += UT_String( " ^" + indicesVariableName ); } } } bool convertStandardAttributes = m_convertStandardAttributesParameter->getTypedValue(); if ( convertStandardAttributes && UT_String( "s" ).multiMatch( filter ) && UT_String( "t" ).multiMatch( filter ) ) { // convert s and t to uv PrimitiveVariableMap::const_iterator sPrimVar = primitive->variables.find( "s" ); PrimitiveVariableMap::const_iterator tPrimVar = primitive->variables.find( "t" ); if ( sPrimVar != primitive->variables.end() && tPrimVar != primitive->variables.end() ) { if ( sPrimVar->second.interpolation == tPrimVar->second.interpolation ) { const FloatVectorData *sData = runTimeCast<const FloatVectorData>( sPrimVar->second.data ); const FloatVectorData *tData = runTimeCast<const FloatVectorData>( tPrimVar->second.data ); if ( sData && tData ) { const std::vector<float> &s = sData->readable(); const std::vector<float> &t = tData->readable(); std::vector<Imath::V3f> uvw; uvw.reserve( s.size() ); for ( size_t i=0; i < s.size(); ++i ) { uvw.push_back( Imath::V3f( s[i], 1 - t[i], 0 ) ); } GA_Range range = vertRange; if ( sPrimVar->second.interpolation == pointInterpolation ) { range = points; } ToHoudiniAttribConverterPtr converter = ToHoudiniAttribConverter::create( new V3fVectorData( uvw ) ); converter->convert( "uv", geo, range ); filter += " ^s ^t"; } } } } UT_StringMMPattern attribFilter; attribFilter.compile( filter ); // add the primitive variables to the various GEO_AttribDicts based on interpolation type for ( PrimitiveVariableMap::const_iterator it=primitive->variables.begin() ; it != primitive->variables.end(); it++ ) { UT_String varName( it->first ); if ( !varName.multiMatch( attribFilter ) ) { continue; } PrimitiveVariable primVar = processPrimitiveVariable( primitive, it->second ); ToHoudiniAttribConverterPtr converter = ToHoudiniAttribConverter::create( primVar.data ); if ( !converter ) { continue; } PrimitiveVariable::Interpolation interpolation = primVar.interpolation; if ( converter->isInstanceOf( (IECore::TypeId)ToHoudiniStringVectorAttribConverterTypeId ) ) { PrimitiveVariableMap::const_iterator indices = stringsToIndices.find( it->first ); if ( indices != stringsToIndices.end() ) { ToHoudiniStringVectorAttribConverter *stringVectorConverter = IECore::runTimeCast<ToHoudiniStringVectorAttribConverter>( converter ); PrimitiveVariable indicesPrimVar = processPrimitiveVariable( primitive, indices->second ); stringVectorConverter->indicesParameter()->setValidatedValue( indicesPrimVar.data ); interpolation = indices->second.interpolation; } } const std::string name = ( convertStandardAttributes ) ? processPrimitiveVariableName( it->first ) : it->first; if ( interpolation == detailInterpolation ) { // add detail attribs converter->convert( name, geo ); } else if ( interpolation == pointInterpolation ) { // add point attribs if ( name == "P" ) { // special case for P transferP( runTimeCast<const V3fVectorData>( primVar.data ), geo, points ); } else { converter->convert( name, geo, points ); } } else if ( interpolation == primitiveInterpolation ) { // add primitive attribs converter->convert( name, geo, prims ); } else if ( interpolation == vertexInterpolation ) { // add vertex attribs converter->convert( name, geo, vertRange ); } } // backwards compatibility with older data const StringData *nameData = primitive->blindData()->member<StringData>( "name" ); if ( nameData && prims.isValid() ) { ToHoudiniStringVectorAttribConverter::convertString( "name", nameData->readable(), geo, prims ); } } void ToHoudiniGeometryConverter::transferP( const IECore::V3fVectorData *positions, GU_Detail *geo, const GA_Range &points ) const { if ( !positions ) { return; } const std::vector<Imath::V3f> &pos = positions->readable(); size_t i = 0; for ( GA_Iterator it=points.begin(); !it.atEnd(); ++it, ++i ) { geo->setPos3( it.getOffset(), IECore::convert<UT_Vector3>( pos[i] ) ); } } const std::string ToHoudiniGeometryConverter::processPrimitiveVariableName( const std::string &name ) const { /// \todo: This should probably be some formal static map. Make sure to update FromHoudiniGeometryConverter as well. if ( name == "Cs" ) { return "Cd"; } else if ( name == "Os" ) { return "Alpha"; } else if ( name == "Pref" ) { return "rest"; } else if ( name == "width" ) { return "pscale"; } return name; } ///////////////////////////////////////////////////////////////////////////////// // Factory ///////////////////////////////////////////////////////////////////////////////// ToHoudiniGeometryConverterPtr ToHoudiniGeometryConverter::create( const Object *object ) { const TypesToFnsMap *m = typesToFns(); TypesToFnsMap::const_iterator it = m->find( Types( object->typeId() ) ); if( it!=m->end() ) { return it->second( object ); } // no exact match, so check for base class matches for ( TypesToFnsMap::const_iterator it = m->begin(); it != m->end(); ++it ) { if ( object->isInstanceOf( it->first.fromType ) ) { return it->second( object ); } } return 0; } void ToHoudiniGeometryConverter::registerConverter( IECore::TypeId fromType, CreatorFn creator ) { TypesToFnsMap *m = typesToFns(); m->insert( TypesToFnsMap::value_type( Types( fromType ), creator ) ); } ToHoudiniGeometryConverter::TypesToFnsMap *ToHoudiniGeometryConverter::typesToFns() { static TypesToFnsMap *m = new TypesToFnsMap; return m; } void ToHoudiniGeometryConverter::supportedTypes( std::set<IECore::TypeId> &types ) { types.clear(); const TypesToFnsMap *m = typesToFns(); for ( TypesToFnsMap::const_iterator it=m->begin(); it != m->end(); it ++ ) { types.insert( it->first.fromType ); } } ///////////////////////////////////////////////////////////////////////////////// // Implementation of nested Types class ///////////////////////////////////////////////////////////////////////////////// ToHoudiniGeometryConverter::Types::Types( IECore::TypeId from ) : fromType( from ) { } bool ToHoudiniGeometryConverter::Types::operator < ( const Types &other ) const { return fromType < other.fromType; } <commit_msg>ToHoudiniGeometryConverter now increments meta cache count.<commit_after>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2010-2013, Image Engine Design 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 Image Engine Design nor the names of any // other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "UT/UT_StringMMPattern.h" #include "IECore/CompoundData.h" #include "IECore/CompoundParameter.h" #include "IECore/MessageHandler.h" #include "IECoreHoudini/Convert.h" #include "IECoreHoudini/ToHoudiniAttribConverter.h" #include "IECoreHoudini/ToHoudiniGeometryConverter.h" #include "IECoreHoudini/ToHoudiniStringAttribConverter.h" using namespace IECore; using namespace IECoreHoudini; IE_CORE_DEFINERUNTIMETYPED( ToHoudiniGeometryConverter ); ToHoudiniGeometryConverter::ToHoudiniGeometryConverter( const IECore::Object *object, const std::string &description ) : ToHoudiniConverter( description, ObjectTypeId ) { srcParameter()->setValue( const_cast<Object*>( object ) ); // safe because the object is const in doConversion m_nameParameter = new StringParameter( "name", "The name given to the converted primitive(s). If empty, primitives will be unnamed", "" ); m_attributeFilterParameter = new StringParameter( "attributeFilter", "A list of attribute names to convert, if they exist. Uses Houdini matching syntax.", "*" ); m_convertStandardAttributesParameter = new BoolParameter( "convertStandardAttributes", "Performs automated conversion of standard PrimitiveVariables to Houdini Attributes (i.e. Pref->rest ; Cs->Cd ; s,t->uv)", true ); parameters()->addParameter( m_nameParameter ); parameters()->addParameter( m_attributeFilterParameter ); parameters()->addParameter( m_convertStandardAttributesParameter ); } ToHoudiniGeometryConverter::~ToHoudiniGeometryConverter() { } BoolParameter *ToHoudiniGeometryConverter::convertStandardAttributesParameter() { return m_convertStandardAttributesParameter; } const BoolParameter *ToHoudiniGeometryConverter::convertStandardAttributesParameter() const { return m_convertStandardAttributesParameter; } StringParameter *ToHoudiniGeometryConverter::nameParameter() { return m_nameParameter; } const StringParameter *ToHoudiniGeometryConverter::nameParameter() const { return m_nameParameter; } StringParameter *ToHoudiniGeometryConverter::attributeFilterParameter() { return m_attributeFilterParameter; } const StringParameter *ToHoudiniGeometryConverter::attributeFilterParameter() const { return m_attributeFilterParameter; } bool ToHoudiniGeometryConverter::convert( GU_DetailHandle handle ) const { ConstCompoundObjectPtr operands = parameters()->getTypedValidatedValue<CompoundObject>(); GU_DetailHandleAutoWriteLock writeHandle( handle ); GU_Detail *geo = writeHandle.getGdp(); if ( !geo ) { return false; } bool result = doConversion( srcParameter()->getValidatedValue(), geo ); if ( result ) { geo->incrementMetaCacheCount(); } return result; } GA_Range ToHoudiniGeometryConverter::appendPoints( GA_Detail *geo, size_t numPoints ) const { if ( !numPoints ) { return GA_Range(); } GA_OffsetList offsets; offsets.reserve( numPoints ); for ( size_t i=0; i < numPoints; ++i ) { offsets.append( geo->appendPoint() ); } return GA_Range( geo->getPointMap(), offsets ); } PrimitiveVariable ToHoudiniGeometryConverter::processPrimitiveVariable( const IECore::Primitive *primitive, const PrimitiveVariable &primVar ) const { return primVar; } void ToHoudiniGeometryConverter::transferAttribs( GU_Detail *geo, const GA_Range &points, const GA_Range &prims ) const { const Primitive *primitive = IECore::runTimeCast<const Primitive>( srcParameter()->getValidatedValue() ); if ( primitive ) { transferAttribValues( primitive, geo, points, prims ); } setName( geo, prims ); } void ToHoudiniGeometryConverter::setName( GU_Detail *geo, const GA_Range &prims ) const { // add the name attribute based on the parameter const std::string &name = nameParameter()->getTypedValue(); if ( name != "" && prims.isValid() ) { ToHoudiniStringVectorAttribConverter::convertString( "name", name, geo, prims ); } } void ToHoudiniGeometryConverter::transferAttribValues( const Primitive *primitive, GU_Detail *geo, const GA_Range &points, const GA_Range &prims, PrimitiveVariable::Interpolation vertexInterpolation, PrimitiveVariable::Interpolation primitiveInterpolation, PrimitiveVariable::Interpolation pointInterpolation, PrimitiveVariable::Interpolation detailInterpolation ) const { GA_OffsetList offsets; if ( prims.isValid() ) { const GA_PrimitiveList &primitives = geo->getPrimitiveList(); for ( GA_Iterator it=prims.begin(); !it.atEnd(); ++it ) { const GA_Primitive *prim = primitives.get( it.getOffset() ); size_t numPrimVerts = prim->getVertexCount(); for ( size_t v=0; v < numPrimVerts; v++ ) { if ( prim->getTypeId() == GEO_PRIMPOLY ) { offsets.append( prim->getVertexOffset( numPrimVerts - 1 - v ) ); } else { offsets.append( prim->getVertexOffset( v ) ); } } } } GA_Range vertRange( geo->getVertexMap(), offsets ); UT_String filter( attributeFilterParameter()->getTypedValue() ); // match all the string variables to each associated indices variable /// \todo: replace all this logic with IECore::IndexedData once it exists... PrimitiveVariableMap stringsToIndices; for ( PrimitiveVariableMap::const_iterator it=primitive->variables.begin() ; it != primitive->variables.end(); it++ ) { if ( !primitive->isPrimitiveVariableValid( it->second ) ) { IECore::msg( IECore::MessageHandler::Warning, "ToHoudiniGeometryConverter", "PrimitiveVariable " + it->first + " is invalid. Ignoring." ); filter += UT_String( " ^" + it->first ); continue; } ToHoudiniAttribConverterPtr converter = ToHoudiniAttribConverter::create( it->second.data ); if ( !converter ) { continue; } if ( it->second.data->isInstanceOf( StringVectorDataTypeId ) ) { std::string indicesVariableName = it->first + "Indices"; PrimitiveVariableMap::const_iterator indices = primitive->variables.find( indicesVariableName ); if ( indices != primitive->variables.end() && indices->second.data->isInstanceOf( IntVectorDataTypeId ) && primitive->isPrimitiveVariableValid( indices->second ) ) { stringsToIndices[it->first] = indices->second; filter += UT_String( " ^" + indicesVariableName ); } } } bool convertStandardAttributes = m_convertStandardAttributesParameter->getTypedValue(); if ( convertStandardAttributes && UT_String( "s" ).multiMatch( filter ) && UT_String( "t" ).multiMatch( filter ) ) { // convert s and t to uv PrimitiveVariableMap::const_iterator sPrimVar = primitive->variables.find( "s" ); PrimitiveVariableMap::const_iterator tPrimVar = primitive->variables.find( "t" ); if ( sPrimVar != primitive->variables.end() && tPrimVar != primitive->variables.end() ) { if ( sPrimVar->second.interpolation == tPrimVar->second.interpolation ) { const FloatVectorData *sData = runTimeCast<const FloatVectorData>( sPrimVar->second.data ); const FloatVectorData *tData = runTimeCast<const FloatVectorData>( tPrimVar->second.data ); if ( sData && tData ) { const std::vector<float> &s = sData->readable(); const std::vector<float> &t = tData->readable(); std::vector<Imath::V3f> uvw; uvw.reserve( s.size() ); for ( size_t i=0; i < s.size(); ++i ) { uvw.push_back( Imath::V3f( s[i], 1 - t[i], 0 ) ); } GA_Range range = vertRange; if ( sPrimVar->second.interpolation == pointInterpolation ) { range = points; } ToHoudiniAttribConverterPtr converter = ToHoudiniAttribConverter::create( new V3fVectorData( uvw ) ); converter->convert( "uv", geo, range ); filter += " ^s ^t"; } } } } UT_StringMMPattern attribFilter; attribFilter.compile( filter ); // add the primitive variables to the various GEO_AttribDicts based on interpolation type for ( PrimitiveVariableMap::const_iterator it=primitive->variables.begin() ; it != primitive->variables.end(); it++ ) { UT_String varName( it->first ); if ( !varName.multiMatch( attribFilter ) ) { continue; } PrimitiveVariable primVar = processPrimitiveVariable( primitive, it->second ); ToHoudiniAttribConverterPtr converter = ToHoudiniAttribConverter::create( primVar.data ); if ( !converter ) { continue; } PrimitiveVariable::Interpolation interpolation = primVar.interpolation; if ( converter->isInstanceOf( (IECore::TypeId)ToHoudiniStringVectorAttribConverterTypeId ) ) { PrimitiveVariableMap::const_iterator indices = stringsToIndices.find( it->first ); if ( indices != stringsToIndices.end() ) { ToHoudiniStringVectorAttribConverter *stringVectorConverter = IECore::runTimeCast<ToHoudiniStringVectorAttribConverter>( converter ); PrimitiveVariable indicesPrimVar = processPrimitiveVariable( primitive, indices->second ); stringVectorConverter->indicesParameter()->setValidatedValue( indicesPrimVar.data ); interpolation = indices->second.interpolation; } } const std::string name = ( convertStandardAttributes ) ? processPrimitiveVariableName( it->first ) : it->first; if ( interpolation == detailInterpolation ) { // add detail attribs converter->convert( name, geo ); } else if ( interpolation == pointInterpolation ) { // add point attribs if ( name == "P" ) { // special case for P transferP( runTimeCast<const V3fVectorData>( primVar.data ), geo, points ); } else { converter->convert( name, geo, points ); } } else if ( interpolation == primitiveInterpolation ) { // add primitive attribs converter->convert( name, geo, prims ); } else if ( interpolation == vertexInterpolation ) { // add vertex attribs converter->convert( name, geo, vertRange ); } } // backwards compatibility with older data const StringData *nameData = primitive->blindData()->member<StringData>( "name" ); if ( nameData && prims.isValid() ) { ToHoudiniStringVectorAttribConverter::convertString( "name", nameData->readable(), geo, prims ); } } void ToHoudiniGeometryConverter::transferP( const IECore::V3fVectorData *positions, GU_Detail *geo, const GA_Range &points ) const { if ( !positions ) { return; } const std::vector<Imath::V3f> &pos = positions->readable(); size_t i = 0; for ( GA_Iterator it=points.begin(); !it.atEnd(); ++it, ++i ) { geo->setPos3( it.getOffset(), IECore::convert<UT_Vector3>( pos[i] ) ); } } const std::string ToHoudiniGeometryConverter::processPrimitiveVariableName( const std::string &name ) const { /// \todo: This should probably be some formal static map. Make sure to update FromHoudiniGeometryConverter as well. if ( name == "Cs" ) { return "Cd"; } else if ( name == "Os" ) { return "Alpha"; } else if ( name == "Pref" ) { return "rest"; } else if ( name == "width" ) { return "pscale"; } return name; } ///////////////////////////////////////////////////////////////////////////////// // Factory ///////////////////////////////////////////////////////////////////////////////// ToHoudiniGeometryConverterPtr ToHoudiniGeometryConverter::create( const Object *object ) { const TypesToFnsMap *m = typesToFns(); TypesToFnsMap::const_iterator it = m->find( Types( object->typeId() ) ); if( it!=m->end() ) { return it->second( object ); } // no exact match, so check for base class matches for ( TypesToFnsMap::const_iterator it = m->begin(); it != m->end(); ++it ) { if ( object->isInstanceOf( it->first.fromType ) ) { return it->second( object ); } } return 0; } void ToHoudiniGeometryConverter::registerConverter( IECore::TypeId fromType, CreatorFn creator ) { TypesToFnsMap *m = typesToFns(); m->insert( TypesToFnsMap::value_type( Types( fromType ), creator ) ); } ToHoudiniGeometryConverter::TypesToFnsMap *ToHoudiniGeometryConverter::typesToFns() { static TypesToFnsMap *m = new TypesToFnsMap; return m; } void ToHoudiniGeometryConverter::supportedTypes( std::set<IECore::TypeId> &types ) { types.clear(); const TypesToFnsMap *m = typesToFns(); for ( TypesToFnsMap::const_iterator it=m->begin(); it != m->end(); it ++ ) { types.insert( it->first.fromType ); } } ///////////////////////////////////////////////////////////////////////////////// // Implementation of nested Types class ///////////////////////////////////////////////////////////////////////////////// ToHoudiniGeometryConverter::Types::Types( IECore::TypeId from ) : fromType( from ) { } bool ToHoudiniGeometryConverter::Types::operator < ( const Types &other ) const { return fromType < other.fromType; } <|endoftext|>
<commit_before>#if defined(__APPLE__) #include "net_rubygrapefruit_platform_internal_jni_OsxFileEventFunctions.h" #include "generic.h" #include <CoreServices/CoreServices.h> #include <pthread.h> class Server; static void handleEventsCallback( ConstFSEventStreamRef streamRef, void *clientCallBackInfo, size_t numEvents, void *eventPaths, const FSEventStreamEventFlags eventFlags[], const FSEventStreamEventId eventIds[]); static void *EventProcessingThread(void *data); class Server { public: Server(JavaVM *jvm, JNIEnv *env, jobject watcherCallback, CFMutableArrayRef rootsToWatch, long latencyInMillis); ~Server(); private: void run(); friend void *EventProcessingThread(void *data); void handleEvents( size_t numEvents, char **eventPaths, const FSEventStreamEventFlags eventFlags[], const FSEventStreamEventId eventIds[]); friend void handleEventsCallback( ConstFSEventStreamRef streamRef, void *clientCallBackInfo, size_t numEvents, void *eventPaths, const FSEventStreamEventFlags eventFlags[], const FSEventStreamEventId eventIds[]); void handleEvent(JNIEnv *env, char* path, FSEventStreamEventFlags flags); // TODO: Move this to somewhere else JNIEnv* getThreadEnv(); JavaVM *jvm; jobject watcherCallback; CFMutableArrayRef rootsToWatch; FSEventStreamRef watcherStream; pthread_t watcherThread; CFRunLoopRef threadLoop; bool invalidStateDetected; }; Server::Server(JavaVM *jvm, JNIEnv *env, jobject watcherCallback, CFMutableArrayRef rootsToWatch, long latencyInMillis) { this->jvm = jvm; this->watcherCallback = env->NewGlobalRef(watcherCallback); this->rootsToWatch = rootsToWatch; this->invalidStateDetected = false; FSEventStreamContext context = { 0, // version, must be 0 (void*) this, // info NULL, // retain NULL, // release NULL // copyDescription }; FSEventStreamRef watcherStream = FSEventStreamCreate ( NULL, &handleEventsCallback, &context, rootsToWatch, kFSEventStreamEventIdSinceNow, latencyInMillis / 1000.0, kFSEventStreamCreateFlagNoDefer | kFSEventStreamCreateFlagFileEvents | kFSEventStreamCreateFlagWatchRoot); if (watcherStream == NULL) { log_severe(env, "Could not create FSEventStreamCreate to track changes", NULL); // TODO Error handling return; } this->watcherStream = watcherStream; if (pthread_create(&(watcherThread), NULL, EventProcessingThread, this) != 0) { log_severe(env, "Could not create file watcher thread.", NULL); // TODO Error handling return; } } Server::~Server() { JNIEnv *env = getThreadEnv(); if (invalidStateDetected) { // report and reset flag, but try to clean up state as much as possible log_severe(env, "Watcher is in invalid state, reported changes may be incorrect", NULL); } if (threadLoop != NULL) { CFRunLoopStop(threadLoop); } if (watcherThread != NULL) { pthread_join(watcherThread, NULL); } if (rootsToWatch != NULL) { for (int i = 0; i < CFArrayGetCount(rootsToWatch); i++) { const void *value = CFArrayGetValueAtIndex(rootsToWatch, i); CFRelease(value); } // TODO Can we release these earlier? CFRelease(rootsToWatch); } if (watcherStream != NULL) { FSEventStreamStop(watcherStream); FSEventStreamInvalidate(watcherStream); FSEventStreamRelease(watcherStream); // TODO: consider using FSEventStreamFlushSync to flush all pending events. } if (watcherCallback != NULL) { env->DeleteGlobalRef(watcherCallback); } } static void *EventProcessingThread(void *data) { Server *server = (Server*) data; server->run(); return NULL; } void Server::run() { JNIEnv* env = attach_jni(jvm, true); log_fine(env, "Starting thread", NULL); CFRunLoopRef threadLoop = CFRunLoopGetCurrent(); FSEventStreamScheduleWithRunLoop(watcherStream, threadLoop, kCFRunLoopDefaultMode); FSEventStreamStart(watcherStream); this->threadLoop = threadLoop; // TODO We should wait for all this to finish in the caller thread otherwise stopWatching() might crash // This triggers run loop for this thread, causing it to run until we explicitly stop it. CFRunLoopRun(); log_fine(env, "Stopping thread", NULL); detach_jni(jvm); } static void handleEventsCallback( ConstFSEventStreamRef streamRef, void *clientCallBackInfo, size_t numEvents, void *eventPaths, const FSEventStreamEventFlags eventFlags[], const FSEventStreamEventId eventIds[] ) { Server *server = (Server*) clientCallBackInfo; server->handleEvents(numEvents, (char **) eventPaths, eventFlags, eventIds); } void Server::handleEvents( size_t numEvents, char **eventPaths, const FSEventStreamEventFlags eventFlags[], const FSEventStreamEventId eventIds[] ) { if (invalidStateDetected) { // TODO Handle this better return; } JNIEnv* env = getThreadEnv(); for (int i = 0; i < numEvents; i++) { handleEvent(env, eventPaths[i], eventFlags[i]); } } void Server::handleEvent(JNIEnv *env, char* path, FSEventStreamEventFlags flags) { log_fine(env, "Event flags: 0x%x for %s", flags, path); jint type; if (IS_SET(flags, kFSEventStreamEventFlagHistoryDone)) { return; } else if (IS_ANY_SET(flags, kFSEventStreamEventFlagRootChanged | kFSEventStreamEventFlagMount | kFSEventStreamEventFlagUnmount | kFSEventStreamEventFlagMustScanSubDirs)) { type = FILE_EVENT_INVALIDATE; } else if (IS_SET(flags, kFSEventStreamEventFlagItemRenamed)) { if (IS_SET(flags, kFSEventStreamEventFlagItemCreated)) { type = FILE_EVENT_REMOVED; } else { type = FILE_EVENT_CREATED; } } else if (IS_SET(flags, kFSEventStreamEventFlagItemModified)) { type = FILE_EVENT_MODIFIED; } else if (IS_SET(flags, kFSEventStreamEventFlagItemRemoved)) { type = FILE_EVENT_REMOVED; } else if (IS_ANY_SET(flags, kFSEventStreamEventFlagItemInodeMetaMod // file locked | kFSEventStreamEventFlagItemFinderInfoMod | kFSEventStreamEventFlagItemChangeOwner | kFSEventStreamEventFlagItemXattrMod)) { type = FILE_EVENT_MODIFIED; } else if (IS_SET(flags, kFSEventStreamEventFlagItemCreated)) { type = FILE_EVENT_CREATED; } else { log_warning(env, "Unknown event 0x%x for %s", flags, path); type = FILE_EVENT_UNKNOWN; } // TODO What does this do? size_t len = 0; if (path != NULL) { len = strlen(path); for (char *p = path; *p != '\0'; p++) { if (*p == '\n') { *p = '\0'; } } } log_info(env, "Changed: %s %d", path, type); jclass callback_class = env->GetObjectClass(watcherCallback); jmethodID methodCallback = env->GetMethodID(callback_class, "pathChanged", "(ILjava/lang/String;)V"); env->CallVoidMethod(watcherCallback, methodCallback, type, env->NewStringUTF(path)); } static JNIEnv* lookupThreadEnv(JavaVM *jvm) { JNIEnv* env; // TODO Verify that JNI 1.6 is the right version jint ret = jvm->GetEnv((void **) &(env), JNI_VERSION_1_6); if (ret != JNI_OK) { fprintf(stderr, "Failed to get JNI env for current thread: %d\n", ret); return NULL; } return env; } JNIEnv* Server::getThreadEnv() { return lookupThreadEnv(jvm); } JNIEXPORT jobject JNICALL Java_net_rubygrapefruit_platform_internal_jni_OsxFileEventFunctions_startWatching(JNIEnv *env, jclass target, jobjectArray paths, long latencyInMillis, jobject javaCallback, jobject result) { log_fine(env, "Configuring...", NULL); JavaVM* jvm; int jvmStatus = env->GetJavaVM(&jvm); if (jvmStatus < 0) { log_severe(env, "Could not store jvm instance", NULL); return NULL; } int count = env->GetArrayLength(paths); if (count == 0) { log_severe(env, "No paths given to watch", NULL); // TODO Error handling return NULL; } CFMutableArrayRef rootsToWatch = CFArrayCreateMutable(NULL, 0, NULL); if (rootsToWatch == NULL) { log_severe(env, "Could not allocate array to store roots to watch", NULL); // TODO Error handling return NULL; } for (int i = 0; i < count; i++) { jstring path = (jstring) env->GetObjectArrayElement(paths, i); char* watchedPath = java_to_char(env, path, result); log_info(env, "Watching %s", watchedPath); if (watchedPath == NULL) { log_severe(env, "Could not allocate string to store root to watch.", NULL); // TODO Free resources return NULL; } CFStringRef stringPath = CFStringCreateWithCString(NULL, watchedPath, kCFStringEncodingUTF8); free(watchedPath); if (stringPath == NULL) { log_severe(env, "Could not create CFStringRef", NULL); // TODO Free resources return NULL; } CFArrayAppendValue(rootsToWatch, stringPath); } Server* server = new Server(jvm, env, javaCallback, rootsToWatch, latencyInMillis); jclass clsWatcher = env->FindClass("net/rubygrapefruit/platform/internal/jni/OsxFileEventFunctions$WatcherImpl"); jmethodID constructor = env->GetMethodID(clsWatcher, "<init>", "(Ljava/lang/Object;)V"); return env->NewObject(clsWatcher, constructor, env->NewDirectByteBuffer(server, sizeof(server))); } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_OsxFileEventFunctions_stopWatching(JNIEnv *env, jclass target, jobject detailsObj, jobject result) { Server *server = (Server*) env->GetDirectBufferAddress(detailsObj); delete server; } #endif <commit_msg>Update src/main/cpp/apple_fsnotifier.cpp<commit_after>#if defined(__APPLE__) #include "net_rubygrapefruit_platform_internal_jni_OsxFileEventFunctions.h" #include "generic.h" #include <CoreServices/CoreServices.h> #include <pthread.h> class Server; static void handleEventsCallback( ConstFSEventStreamRef streamRef, void *clientCallBackInfo, size_t numEvents, void *eventPaths, const FSEventStreamEventFlags eventFlags[], const FSEventStreamEventId eventIds[]); static void *EventProcessingThread(void *data); class Server { public: Server(JavaVM *jvm, JNIEnv *env, jobject watcherCallback, CFMutableArrayRef rootsToWatch, long latencyInMillis); ~Server(); private: void run(); friend void *EventProcessingThread(void *data); void handleEvents( size_t numEvents, char **eventPaths, const FSEventStreamEventFlags eventFlags[], const FSEventStreamEventId eventIds[]); friend void handleEventsCallback( ConstFSEventStreamRef streamRef, void *clientCallBackInfo, size_t numEvents, void *eventPaths, const FSEventStreamEventFlags eventFlags[], const FSEventStreamEventId eventIds[]); void handleEvent(JNIEnv *env, char* path, FSEventStreamEventFlags flags); // TODO: Move this to somewhere else JNIEnv* getThreadEnv(); JavaVM *jvm; jobject watcherCallback; CFMutableArrayRef rootsToWatch; FSEventStreamRef watcherStream; pthread_t watcherThread; CFRunLoopRef threadLoop; bool invalidStateDetected; }; Server::Server(JavaVM *jvm, JNIEnv *env, jobject watcherCallback, CFMutableArrayRef rootsToWatch, long latencyInMillis) { this->jvm = jvm; this->watcherCallback = env->NewGlobalRef(watcherCallback); this->rootsToWatch = rootsToWatch; this->invalidStateDetected = false; FSEventStreamContext context = { 0, // version, must be 0 (void*) this, // info NULL, // retain NULL, // release NULL // copyDescription }; FSEventStreamRef watcherStream = FSEventStreamCreate( NULL, &handleEventsCallback, &context, rootsToWatch, kFSEventStreamEventIdSinceNow, latencyInMillis / 1000.0, kFSEventStreamCreateFlagNoDefer | kFSEventStreamCreateFlagFileEvents | kFSEventStreamCreateFlagWatchRoot); if (watcherStream == NULL) { log_severe(env, "Could not create FSEventStreamCreate to track changes", NULL); // TODO Error handling return; } this->watcherStream = watcherStream; if (pthread_create(&(watcherThread), NULL, EventProcessingThread, this) != 0) { log_severe(env, "Could not create file watcher thread.", NULL); // TODO Error handling return; } } Server::~Server() { JNIEnv *env = getThreadEnv(); if (invalidStateDetected) { // report and reset flag, but try to clean up state as much as possible log_severe(env, "Watcher is in invalid state, reported changes may be incorrect", NULL); } if (threadLoop != NULL) { CFRunLoopStop(threadLoop); } if (watcherThread != NULL) { pthread_join(watcherThread, NULL); } if (rootsToWatch != NULL) { for (int i = 0; i < CFArrayGetCount(rootsToWatch); i++) { const void *value = CFArrayGetValueAtIndex(rootsToWatch, i); CFRelease(value); } // TODO Can we release these earlier? CFRelease(rootsToWatch); } if (watcherStream != NULL) { FSEventStreamStop(watcherStream); FSEventStreamInvalidate(watcherStream); FSEventStreamRelease(watcherStream); // TODO: consider using FSEventStreamFlushSync to flush all pending events. } if (watcherCallback != NULL) { env->DeleteGlobalRef(watcherCallback); } } static void *EventProcessingThread(void *data) { Server *server = (Server*) data; server->run(); return NULL; } void Server::run() { JNIEnv* env = attach_jni(jvm, true); log_fine(env, "Starting thread", NULL); CFRunLoopRef threadLoop = CFRunLoopGetCurrent(); FSEventStreamScheduleWithRunLoop(watcherStream, threadLoop, kCFRunLoopDefaultMode); FSEventStreamStart(watcherStream); this->threadLoop = threadLoop; // TODO We should wait for all this to finish in the caller thread otherwise stopWatching() might crash // This triggers run loop for this thread, causing it to run until we explicitly stop it. CFRunLoopRun(); log_fine(env, "Stopping thread", NULL); detach_jni(jvm); } static void handleEventsCallback( ConstFSEventStreamRef streamRef, void *clientCallBackInfo, size_t numEvents, void *eventPaths, const FSEventStreamEventFlags eventFlags[], const FSEventStreamEventId eventIds[] ) { Server *server = (Server*) clientCallBackInfo; server->handleEvents(numEvents, (char **) eventPaths, eventFlags, eventIds); } void Server::handleEvents( size_t numEvents, char **eventPaths, const FSEventStreamEventFlags eventFlags[], const FSEventStreamEventId eventIds[] ) { if (invalidStateDetected) { // TODO Handle this better return; } JNIEnv* env = getThreadEnv(); for (int i = 0; i < numEvents; i++) { handleEvent(env, eventPaths[i], eventFlags[i]); } } void Server::handleEvent(JNIEnv *env, char* path, FSEventStreamEventFlags flags) { log_fine(env, "Event flags: 0x%x for %s", flags, path); jint type; if (IS_SET(flags, kFSEventStreamEventFlagHistoryDone)) { return; } else if (IS_ANY_SET(flags, kFSEventStreamEventFlagRootChanged | kFSEventStreamEventFlagMount | kFSEventStreamEventFlagUnmount | kFSEventStreamEventFlagMustScanSubDirs)) { type = FILE_EVENT_INVALIDATE; } else if (IS_SET(flags, kFSEventStreamEventFlagItemRenamed)) { if (IS_SET(flags, kFSEventStreamEventFlagItemCreated)) { type = FILE_EVENT_REMOVED; } else { type = FILE_EVENT_CREATED; } } else if (IS_SET(flags, kFSEventStreamEventFlagItemModified)) { type = FILE_EVENT_MODIFIED; } else if (IS_SET(flags, kFSEventStreamEventFlagItemRemoved)) { type = FILE_EVENT_REMOVED; } else if (IS_ANY_SET(flags, kFSEventStreamEventFlagItemInodeMetaMod // file locked | kFSEventStreamEventFlagItemFinderInfoMod | kFSEventStreamEventFlagItemChangeOwner | kFSEventStreamEventFlagItemXattrMod)) { type = FILE_EVENT_MODIFIED; } else if (IS_SET(flags, kFSEventStreamEventFlagItemCreated)) { type = FILE_EVENT_CREATED; } else { log_warning(env, "Unknown event 0x%x for %s", flags, path); type = FILE_EVENT_UNKNOWN; } // TODO What does this do? size_t len = 0; if (path != NULL) { len = strlen(path); for (char *p = path; *p != '\0'; p++) { if (*p == '\n') { *p = '\0'; } } } log_info(env, "Changed: %s %d", path, type); jclass callback_class = env->GetObjectClass(watcherCallback); jmethodID methodCallback = env->GetMethodID(callback_class, "pathChanged", "(ILjava/lang/String;)V"); env->CallVoidMethod(watcherCallback, methodCallback, type, env->NewStringUTF(path)); } static JNIEnv* lookupThreadEnv(JavaVM *jvm) { JNIEnv* env; // TODO Verify that JNI 1.6 is the right version jint ret = jvm->GetEnv((void **) &(env), JNI_VERSION_1_6); if (ret != JNI_OK) { fprintf(stderr, "Failed to get JNI env for current thread: %d\n", ret); return NULL; } return env; } JNIEnv* Server::getThreadEnv() { return lookupThreadEnv(jvm); } JNIEXPORT jobject JNICALL Java_net_rubygrapefruit_platform_internal_jni_OsxFileEventFunctions_startWatching(JNIEnv *env, jclass target, jobjectArray paths, long latencyInMillis, jobject javaCallback, jobject result) { log_fine(env, "Configuring...", NULL); JavaVM* jvm; int jvmStatus = env->GetJavaVM(&jvm); if (jvmStatus < 0) { log_severe(env, "Could not store jvm instance", NULL); return NULL; } int count = env->GetArrayLength(paths); if (count == 0) { log_severe(env, "No paths given to watch", NULL); // TODO Error handling return NULL; } CFMutableArrayRef rootsToWatch = CFArrayCreateMutable(NULL, 0, NULL); if (rootsToWatch == NULL) { log_severe(env, "Could not allocate array to store roots to watch", NULL); // TODO Error handling return NULL; } for (int i = 0; i < count; i++) { jstring path = (jstring) env->GetObjectArrayElement(paths, i); char* watchedPath = java_to_char(env, path, result); log_info(env, "Watching %s", watchedPath); if (watchedPath == NULL) { log_severe(env, "Could not allocate string to store root to watch.", NULL); // TODO Free resources return NULL; } CFStringRef stringPath = CFStringCreateWithCString(NULL, watchedPath, kCFStringEncodingUTF8); free(watchedPath); if (stringPath == NULL) { log_severe(env, "Could not create CFStringRef", NULL); // TODO Free resources return NULL; } CFArrayAppendValue(rootsToWatch, stringPath); } Server* server = new Server(jvm, env, javaCallback, rootsToWatch, latencyInMillis); jclass clsWatcher = env->FindClass("net/rubygrapefruit/platform/internal/jni/OsxFileEventFunctions$WatcherImpl"); jmethodID constructor = env->GetMethodID(clsWatcher, "<init>", "(Ljava/lang/Object;)V"); return env->NewObject(clsWatcher, constructor, env->NewDirectByteBuffer(server, sizeof(server))); } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_OsxFileEventFunctions_stopWatching(JNIEnv *env, jclass target, jobject detailsObj, jobject result) { Server *server = (Server*) env->GetDirectBufferAddress(detailsObj); delete server; } #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: depapp.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: obo $ $Date: 2006-04-20 15:15:01 $ * * 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 * ************************************************************************/ // ----------------------------------------------------------------------- #include "depapp.hxx" void MyApp::Main() { pDebugFile = fopen( "fprintf.out", "w" ); pMyApp = GetpApp(); MyWin aMainWin( NULL, WB_APP | WB_STDWORK ); pAppWindow = &aMainWin; // pToolBarFrame = new FloatingWindow( aMainWin, WB_STDWORK ); //pToolBox = new ToolBox(pToolBarFrame,DtSodResId(TID_SOLDEP_MAIN)); pSolDep = new SolDep( &aMainWin ); pSolDep->Init(); aMainWin.SetText( String::CreateFromAscii( SOLDEPL_NAME )); aMainWin.Show(); Help aHelp; SetHelp(&aHelp); aHelp.EnableContextHelp(); aHelp.EnableQuickHelp(); Execute(); delete pResMgr; delete pSolDep; } // ----------------------------------------------------------------------- MyWin::MyWin( Window* pParent, WinBits nWinStyle ) : WorkWindow( pParent, nWinStyle )//,aToolBox( this, DtSodResId(TID_SOLDEP_MAIN)), // depper aTaskBarFrame(this, 0) { //depper aTaskBarFrame.EnableAlwaysOnTop(); //depper aMenuBar.InsertItem( 1, XubString( RTL_CONSTASCII_USTRINGPARAM( "~Source" ) ) ); //depper aMenuBar.InsertItem( 2, XubString( RTL_CONSTASCII_USTRINGPARAM( "~Exit" ) ) ); //depper SetMenuBar( &aMenuBar ); //depper aToolBox.SetPosSizePixel( Point( 0,0 ), Size( 1100,35 )); // aToolBox.Show(); } // ----------------------------------------------------------------------- void MyWin::MouseMove( const MouseEvent& rMEvt ) { WorkWindow::MouseMove( rMEvt ); } // ----------------------------------------------------------------------- void MyWin::MouseButtonDown( const MouseEvent& rMEvt ) { WorkWindow::MouseButtonDown( rMEvt ); } // ----------------------------------------------------------------------- void MyWin::MouseButtonUp( const MouseEvent& rMEvt ) { WorkWindow::MouseButtonUp( rMEvt ); } // ----------------------------------------------------------------------- void MyWin::KeyInput( const KeyEvent& rKEvt ) { WorkWindow::KeyInput( rKEvt ); } // ----------------------------------------------------------------------- void MyWin::KeyUp( const KeyEvent& rKEvt ) { WorkWindow::KeyUp( rKEvt ); } // ----------------------------------------------------------------------- void MyWin::Paint( const Rectangle& rRect ) { WorkWindow::Paint( rRect ); } // ----------------------------------------------------------------------- void MyWin::Resize() { ((MyApp*)GetpApp())->GetSolDep()->Resize(); WorkWindow::Resize(); } SAL_IMPLEMENT_MAIN() { Reference< XMultiServiceFactory > xMS; // for this to work make sure an <appname>.ini file is available, you can just copy soffice.ini Reference< XComponentContext > xComponentContext = ::cppu::defaultBootstrap_InitialComponentContext(); xMS = cppu::createRegistryServiceFactory( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "applicat.rdb" ) ), sal_True ); InitVCL( xMS ); aMyApp.Main(); DeInitVCL(); return 0; } <commit_msg>::comphelper::setProcessServiceFactory needed<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: depapp.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: obo $ $Date: 2006-10-23 11:36:37 $ * * 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 * ************************************************************************/ // ----------------------------------------------------------------------- #include "depapp.hxx" void MyApp::Main() { pDebugFile = fopen( "fprintf.out", "w" ); pMyApp = GetpApp(); MyWin aMainWin( NULL, WB_APP | WB_STDWORK ); pAppWindow = &aMainWin; // pToolBarFrame = new FloatingWindow( aMainWin, WB_STDWORK ); //pToolBox = new ToolBox(pToolBarFrame,DtSodResId(TID_SOLDEP_MAIN)); pSolDep = new SolDep( &aMainWin ); pSolDep->Init(); aMainWin.SetText( String::CreateFromAscii( SOLDEPL_NAME )); aMainWin.Show(); Help aHelp; SetHelp(&aHelp); aHelp.EnableContextHelp(); aHelp.EnableQuickHelp(); Execute(); delete pResMgr; delete pSolDep; } // ----------------------------------------------------------------------- MyWin::MyWin( Window* pParent, WinBits nWinStyle ) : WorkWindow( pParent, nWinStyle )//,aToolBox( this, DtSodResId(TID_SOLDEP_MAIN)), // depper aTaskBarFrame(this, 0) { //depper aTaskBarFrame.EnableAlwaysOnTop(); //depper aMenuBar.InsertItem( 1, XubString( RTL_CONSTASCII_USTRINGPARAM( "~Source" ) ) ); //depper aMenuBar.InsertItem( 2, XubString( RTL_CONSTASCII_USTRINGPARAM( "~Exit" ) ) ); //depper SetMenuBar( &aMenuBar ); //depper aToolBox.SetPosSizePixel( Point( 0,0 ), Size( 1100,35 )); // aToolBox.Show(); } // ----------------------------------------------------------------------- void MyWin::MouseMove( const MouseEvent& rMEvt ) { WorkWindow::MouseMove( rMEvt ); } // ----------------------------------------------------------------------- void MyWin::MouseButtonDown( const MouseEvent& rMEvt ) { WorkWindow::MouseButtonDown( rMEvt ); } // ----------------------------------------------------------------------- void MyWin::MouseButtonUp( const MouseEvent& rMEvt ) { WorkWindow::MouseButtonUp( rMEvt ); } // ----------------------------------------------------------------------- void MyWin::KeyInput( const KeyEvent& rKEvt ) { WorkWindow::KeyInput( rKEvt ); } // ----------------------------------------------------------------------- void MyWin::KeyUp( const KeyEvent& rKEvt ) { WorkWindow::KeyUp( rKEvt ); } // ----------------------------------------------------------------------- void MyWin::Paint( const Rectangle& rRect ) { WorkWindow::Paint( rRect ); } // ----------------------------------------------------------------------- void MyWin::Resize() { ((MyApp*)GetpApp())->GetSolDep()->Resize(); WorkWindow::Resize(); } SAL_IMPLEMENT_MAIN() { Reference< XMultiServiceFactory > xMS; // for this to work make sure an <appname>.ini file is available, you can just copy soffice.ini Reference< XComponentContext > xComponentContext = ::cppu::defaultBootstrap_InitialComponentContext(); xMS = cppu::createRegistryServiceFactory( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "applicat.rdb" ) ), sal_True ); InitVCL( xMS ); ::comphelper::setProcessServiceFactory(xMS); aMyApp.Main(); DeInitVCL(); return 0; } <|endoftext|>
<commit_before>/* Initial version copied from https://raw.githubusercontent.com/JetBrains/intellij-community/master/native/fsNotifier/mac/. */ // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. /* * Apple specific functions. */ #if defined(__APPLE__) #include "native.h" #include "generic.h" #include <CoreServices/CoreServices.h> #include <thread> #include <stdio.h> #include <pthread.h> #include <strings.h> #include <sys/mount.h> CFMutableArrayRef rootsToWatch; FSEventStreamRef watcherStream; pthread_t watcherThread; // store the callback object, as we need to invoke it once file change is detected. jobject watcherCallback; JavaVM* jvm; CFRunLoopRef threadLoop; static void reportEvent(const char *event, char *path) { size_t len = 0; if (path != NULL) { len = strlen(path); for (char *p = path; *p != '\0'; p++) { if (*p == '\n') { *p = '\0'; } } } JNIEnv* env; int getEnvStat = jvm->GetEnv((void **)&env, JNI_VERSION_1_6); if (getEnvStat == JNI_EDETACHED) { if (jvm->AttachCurrentThread((void **) &env, NULL) != 0) { } } else if (getEnvStat == JNI_OK) { // } else if (getEnvStat == JNI_EVERSION) { printf("GetEnv: version not supported"); } jclass callback_class = env->GetObjectClass(watcherCallback); jmethodID methodCallback = env->GetMethodID(callback_class, "pathChanged", "(Ljava/lang/String;)V"); env->CallVoidMethod(watcherCallback, methodCallback, env->NewStringUTF(path)); } static void callback(ConstFSEventStreamRef streamRef, void *clientCallBackInfo, size_t numEvents, void *eventPaths, const FSEventStreamEventFlags eventFlags[], const FSEventStreamEventId eventIds[]) { char **paths = (char**) eventPaths; for (int i = 0; i < numEvents; i++) { // TODO[max] Lion has much more detailed flags we need accurately process. For now just reduce to SL events range. FSEventStreamEventFlags flags = eventFlags[i] & 0xFF; if ((flags & kFSEventStreamEventFlagMustScanSubDirs) != 0) { reportEvent("RECDIRTY", paths[i]); } else if (flags != kFSEventStreamEventFlagNone) { reportEvent("RESET", NULL); } else { reportEvent("DIRTY", paths[i]); } } } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_OsxFileEventFunctions_createWatch(JNIEnv *env, jclass target, jstring path, jobject result) { if (rootsToWatch == NULL) { rootsToWatch = CFArrayCreateMutable(NULL, 0, NULL); } CFStringRef stringPath = CFStringCreateWithCString(NULL, java_to_char(env, path, result), kCFStringEncodingUTF8); CFArrayAppendValue(rootsToWatch, stringPath); } static void *EventProcessingThread(void *data) { FSEventStreamRef stream = (FSEventStreamRef) data; threadLoop = CFRunLoopGetCurrent(); FSEventStreamScheduleWithRunLoop(stream, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode); FSEventStreamStart(stream); CFRunLoopRun(); return NULL; } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_OsxFileEventFunctions_startWatch(JNIEnv *env, jclass target, jobject javaCallback, jobject result) { if (rootsToWatch == NULL) { // nothing to watch, just return return; } CFAbsoluteTime latency = 0.3; // Latency in seconds watcherCallback = env->NewGlobalRef(javaCallback); watcherStream = FSEventStreamCreate ( NULL, &callback, NULL, rootsToWatch, kFSEventStreamEventIdSinceNow, latency, kFSEventStreamCreateFlagNoDefer); if (watcherStream == NULL) { printf("GIVEUP\n"); } if (pthread_create(&watcherThread, NULL, EventProcessingThread, watcherStream) != 0) { printf("GIVEUP\n"); } env->GetJavaVM(&jvm); } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_OsxFileEventFunctions_stopWatch(JNIEnv *env, jclass target, jobject result) { // if there were no roots to watch, there are no resources to release if (rootsToWatch == NULL) return; for (int i = 0; i < CFArrayGetCount(rootsToWatch); i++) { void *value = (char *)CFArrayGetValueAtIndex(rootsToWatch, i); free(value); } CFRelease(rootsToWatch); rootsToWatch = NULL; FSEventStreamStop(watcherStream); watcherStream = NULL; CFRunLoopStop(threadLoop); threadLoop = NULL; env->DeleteGlobalRef(watcherCallback); watcherCallback = NULL; pthread_join(watcherThread, NULL); watcherThread = NULL; } #endif<commit_msg>Free memory using CFRelease<commit_after>/* Initial version copied from https://raw.githubusercontent.com/JetBrains/intellij-community/master/native/fsNotifier/mac/. */ // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. /* * Apple specific functions. */ #if defined(__APPLE__) #include "native.h" #include "generic.h" #include <CoreServices/CoreServices.h> #include <thread> #include <stdio.h> #include <pthread.h> #include <strings.h> #include <sys/mount.h> CFMutableArrayRef rootsToWatch; FSEventStreamRef watcherStream; pthread_t watcherThread; // store the callback object, as we need to invoke it once file change is detected. jobject watcherCallback; JavaVM* jvm; CFRunLoopRef threadLoop; static void reportEvent(const char *event, char *path) { size_t len = 0; if (path != NULL) { len = strlen(path); for (char *p = path; *p != '\0'; p++) { if (*p == '\n') { *p = '\0'; } } } JNIEnv* env; int getEnvStat = jvm->GetEnv((void **)&env, JNI_VERSION_1_6); if (getEnvStat == JNI_EDETACHED) { if (jvm->AttachCurrentThread((void **) &env, NULL) != 0) { } } else if (getEnvStat == JNI_OK) { // } else if (getEnvStat == JNI_EVERSION) { printf("GetEnv: version not supported"); } jclass callback_class = env->GetObjectClass(watcherCallback); jmethodID methodCallback = env->GetMethodID(callback_class, "pathChanged", "(Ljava/lang/String;)V"); env->CallVoidMethod(watcherCallback, methodCallback, env->NewStringUTF(path)); } static void callback(ConstFSEventStreamRef streamRef, void *clientCallBackInfo, size_t numEvents, void *eventPaths, const FSEventStreamEventFlags eventFlags[], const FSEventStreamEventId eventIds[]) { char **paths = (char**) eventPaths; for (int i = 0; i < numEvents; i++) { // TODO[max] Lion has much more detailed flags we need accurately process. For now just reduce to SL events range. FSEventStreamEventFlags flags = eventFlags[i] & 0xFF; if ((flags & kFSEventStreamEventFlagMustScanSubDirs) != 0) { reportEvent("RECDIRTY", paths[i]); } else if (flags != kFSEventStreamEventFlagNone) { reportEvent("RESET", NULL); } else { reportEvent("DIRTY", paths[i]); } } } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_OsxFileEventFunctions_createWatch(JNIEnv *env, jclass target, jstring path, jobject result) { if (rootsToWatch == NULL) { rootsToWatch = CFArrayCreateMutable(NULL, 0, NULL); } CFStringRef stringPath = CFStringCreateWithCString(NULL, java_to_char(env, path, result), kCFStringEncodingUTF8); CFArrayAppendValue(rootsToWatch, stringPath); } static void *EventProcessingThread(void *data) { FSEventStreamRef stream = (FSEventStreamRef) data; threadLoop = CFRunLoopGetCurrent(); FSEventStreamScheduleWithRunLoop(stream, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode); FSEventStreamStart(stream); CFRunLoopRun(); return NULL; } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_OsxFileEventFunctions_startWatch(JNIEnv *env, jclass target, jobject javaCallback, jobject result) { if (rootsToWatch == NULL) { // nothing to watch, just return return; } CFAbsoluteTime latency = 0.3; // Latency in seconds watcherCallback = env->NewGlobalRef(javaCallback); watcherStream = FSEventStreamCreate ( NULL, &callback, NULL, rootsToWatch, kFSEventStreamEventIdSinceNow, latency, kFSEventStreamCreateFlagNoDefer); if (watcherStream == NULL) { printf("GIVEUP\n"); } if (pthread_create(&watcherThread, NULL, EventProcessingThread, watcherStream) != 0) { printf("GIVEUP\n"); } env->GetJavaVM(&jvm); } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_OsxFileEventFunctions_stopWatch(JNIEnv *env, jclass target, jobject result) { // if there were no roots to watch, there are no resources to release if (rootsToWatch == NULL) return; for (int i = 0; i < CFArrayGetCount(rootsToWatch); i++) { void *value = (char *)CFArrayGetValueAtIndex(rootsToWatch, i); CFRelease(value); } CFRelease(rootsToWatch); rootsToWatch = NULL; FSEventStreamStop(watcherStream); watcherStream = NULL; CFRunLoopStop(threadLoop); threadLoop = NULL; env->DeleteGlobalRef(watcherCallback); watcherCallback = NULL; pthread_join(watcherThread, NULL); watcherThread = NULL; } #endif<|endoftext|>
<commit_before>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_PRODUCTS_BASE_HH #define DUNE_GDT_PRODUCTS_BASE_HH #include <dune/stuff/grid/walker.hh> #include <dune/gdt/assembler/tmp-storage.hh> #include <dune/gdt/assembler/local/codim0.hh> #include "interfaces.hh" namespace Dune { namespace GDT { namespace Products { /** * \todo Derive from SystemAssembler, \see Operators::EllipticG */ template <class Traits> class LocalizableBase : public LocalizableProductInterface<Traits>, public Stuff::Grid::Functor::Codim0<typename Traits::GridViewType> { typedef LocalizableProductInterface<Traits> InterfaceType; public: typedef typename Traits::GridViewType GridViewType; typedef typename Traits::RangeType RangeType; typedef typename Traits::SourceType SourceType; typedef typename Traits::FieldType FieldType; private: typedef typename Traits::LocalOperatorType LocalOperatorType; typedef TmpStorageProvider::Matrices<FieldType> TmpMatricesProviderType; public: using typename InterfaceType::EntityType; public: LocalizableBase(const GridViewType& grd_vw, const RangeType& rng, const SourceType& src) : grid_view_(grd_vw) , range_(rng) , source_(src) , tmp_storage_(nullptr) , prepared_(false) , finalized_(false) , result_(0) { } LocalizableBase(const GridViewType& grd_vw, const RangeType& rng) : grid_view_(grd_vw) , range_(rng) , source_(range_) , tmp_storage_(nullptr) , prepared_(false) , finalized_(false) , result_(0) { } virtual ~LocalizableBase() { } const GridViewType& grid_view() const { return grid_view_; } const RangeType& range() const { return range_; } const SourceType& source() const { return source_; } private: virtual const LocalOperatorType& local_operator() const = 0; public: virtual void prepare() DS_OVERRIDE { if (!prepared_) { tmp_storage_ = std::unique_ptr<TmpMatricesProviderType>( new TmpMatricesProviderType({1, local_operator().numTmpObjectsRequired()}, 1, 1)); result_ *= 0.0; prepared_ = true; } } // ... prepare() FieldType compute_locally(const EntityType& entity) { assert(prepared_); assert(tmp_storage_); auto& tmp_storage = tmp_storage_->matrices(); assert(tmp_storage.size() >= 2); assert(tmp_storage[0].size() >= 1); auto& local_operator_result = tmp_storage[0][0]; auto& tmp_matrices = tmp_storage[1]; // get the local functions const auto local_source_ptr = this->source().local_function(entity); const auto local_range_ptr = this->range().local_function(entity); // apply local operator local_operator().apply(*local_range_ptr, *local_source_ptr, local_operator_result, tmp_matrices); assert(local_operator_result.rows() == 1); assert(local_operator_result.cols() == 1); return local_operator_result[0][0]; } // ... compute_locally(...) virtual void apply_local(const EntityType& entity) DS_OVERRIDE { result_ += compute_locally(entity); } virtual void finalize() DS_OVERRIDE { if (!finalized_) { result_ = grid_view_.comm().sum(result_); finalized_ = true; } } FieldType apply2() { if (!finalized_) { Stuff::Grid::Walker<GridViewType> grid_walker(grid_view_); grid_walker.add(*this); grid_walker.walk(); } return result_; } private: const GridViewType& grid_view_; const RangeType& range_; const SourceType& source_; std::unique_ptr<TmpMatricesProviderType> tmp_storage_; bool prepared_; bool finalized_; FieldType result_; }; // class LocalizableBase /** * \todo Derive from SystemAssembler, \see Operators::EllipticG */ template <class Traits> class AssemblableBase : public AssemblableProductInterface<Traits>, public Stuff::Grid::Functor::Codim0<typename Traits::GridViewType> { typedef AssemblableProductInterface<Traits> InterfaceType; public: typedef typename Traits::GridViewType GridViewType; typedef typename Traits::RangeSpaceType RangeSpaceType; typedef typename Traits::SourceSpaceType SourceSpaceType; typedef typename Traits::MatrixType MatrixType; typedef typename MatrixType::ScalarType FieldType; private: typedef TmpStorageProvider::Matrices<FieldType> TmpMatricesProviderType; typedef typename Traits::LocalOperatorType LocalOperatorType; typedef LocalAssembler::Codim0Matrix<LocalOperatorType> LocalAssemblerType; public: using typename InterfaceType::EntityType; using InterfaceType::pattern; AssemblableBase(MatrixType& mtrx, const RangeSpaceType& rng_spc, const GridViewType& grd_vw, const SourceSpaceType& src_spc) : matrix_(mtrx) , range_space_(rng_spc) , grid_view_(grd_vw) , source_space_(src_spc) , local_assembler_(nullptr) , tmp_storage_(nullptr) , prepared_(false) , assembled_(false) { } AssemblableBase(MatrixType& mtrx, const RangeSpaceType& rng_spc, const GridViewType& grd_vw) : matrix_(mtrx) , range_space_(rng_spc) , grid_view_(grd_vw) , source_space_(range_space_) , local_assembler_(nullptr) , tmp_storage_(nullptr) , prepared_(false) , assembled_(false) { } AssemblableBase(MatrixType& mtrx, const RangeSpaceType& rng_spc) : matrix_(mtrx) , range_space_(rng_spc) , grid_view_(*(range_space_->grid_view())) , source_space_(range_space_) , local_assembler_(nullptr) , tmp_storage_(nullptr) , prepared_(false) , assembled_(false) { } const GridViewType& grid_view() const { return grid_view_; } const RangeSpaceType& range_space() const { return range_space_; } const SourceSpaceType& source_space() const { return source_space_; } MatrixType& matrix() { return matrix_; } const MatrixType& matrix() const { return matrix_; } private: virtual const LocalOperatorType& local_operator() const = 0; public: virtual void prepare() DS_OVERRIDE { if (!assembled_ && !prepared_) { local_assembler_ = std::unique_ptr<LocalAssemblerType>(new LocalAssemblerType(local_operator())); tmp_storage_ = std::unique_ptr<TmpMatricesProviderType>( new TmpMatricesProviderType(local_assembler_->numTmpObjectsRequired(), range_space_.mapper().maxNumDofs(), source_space_.mapper().maxNumDofs())); prepared_ = true; } } // ... prepare() virtual void apply_local(const EntityType& entity) DS_OVERRIDE { assert(prepared_); assert(local_assembler_); assert(tmp_storage_); local_assembler_->assembleLocal( range_space_, source_space_, entity, matrix_, tmp_storage_->matrices(), tmp_storage_->indices()); } // ... apply_local(...) void assemble() { if (!assembled_) { Stuff::Grid::Walker<GridViewType> grid_walker(grid_view_); grid_walker.add(*this); grid_walker.walk(); assembled_ = true; } } // ... assemble() using InterfaceType::apply2; private: MatrixType& matrix_; const RangeSpaceType& range_space_; const GridViewType& grid_view_; const SourceSpaceType& source_space_; std::unique_ptr<LocalAssemblerType> local_assembler_; std::unique_ptr<TmpMatricesProviderType> tmp_storage_; bool prepared_; bool assembled_; }; // class AssemblableBase } // namespace Products } // namespace GDT } // namespace Dune #endif // DUNE_GDT_PRODUCTS_BASE_HH <commit_msg>[producsts.base] makes result variable atomic<commit_after>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_PRODUCTS_BASE_HH #define DUNE_GDT_PRODUCTS_BASE_HH #include <dune/stuff/grid/walker.hh> #include <dune/gdt/assembler/tmp-storage.hh> #include <dune/gdt/assembler/local/codim0.hh> #include "interfaces.hh" namespace Dune { namespace GDT { namespace Products { /** * \todo Derive from SystemAssembler, \see Operators::EllipticG */ template <class Traits> class LocalizableBase : public LocalizableProductInterface<Traits>, public Stuff::Grid::Functor::Codim0<typename Traits::GridViewType> { typedef LocalizableProductInterface<Traits> InterfaceType; public: typedef typename Traits::GridViewType GridViewType; typedef typename Traits::RangeType RangeType; typedef typename Traits::SourceType SourceType; typedef typename Traits::FieldType FieldType; private: typedef typename Traits::LocalOperatorType LocalOperatorType; typedef TmpStorageProvider::Matrices<FieldType> TmpMatricesProviderType; public: using typename InterfaceType::EntityType; public: LocalizableBase(const GridViewType& grd_vw, const RangeType& rng, const SourceType& src) : grid_view_(grd_vw) , range_(rng) , source_(src) , tmp_storage_(nullptr) , prepared_(false) , finalized_(false) , result_(0) { } LocalizableBase(const GridViewType& grd_vw, const RangeType& rng) : grid_view_(grd_vw) , range_(rng) , source_(range_) , tmp_storage_(nullptr) , prepared_(false) , finalized_(false) , result_(0) { } virtual ~LocalizableBase() { } const GridViewType& grid_view() const { return grid_view_; } const RangeType& range() const { return range_; } const SourceType& source() const { return source_; } private: virtual const LocalOperatorType& local_operator() const = 0; public: virtual void prepare() DS_OVERRIDE { if (!prepared_) { tmp_storage_ = std::unique_ptr<TmpMatricesProviderType>( new TmpMatricesProviderType({1, local_operator().numTmpObjectsRequired()}, 1, 1)); result_ = FieldType(0.0); prepared_ = true; } } // ... prepare() FieldType compute_locally(const EntityType& entity) { assert(prepared_); assert(tmp_storage_); auto& tmp_storage = tmp_storage_->matrices(); assert(tmp_storage.size() >= 2); assert(tmp_storage[0].size() >= 1); auto& local_operator_result = tmp_storage[0][0]; auto& tmp_matrices = tmp_storage[1]; // get the local functions const auto local_source_ptr = this->source().local_function(entity); const auto local_range_ptr = this->range().local_function(entity); // apply local operator local_operator().apply(*local_range_ptr, *local_source_ptr, local_operator_result, tmp_matrices); assert(local_operator_result.rows() == 1); assert(local_operator_result.cols() == 1); return local_operator_result[0][0]; } // ... compute_locally(...) virtual void apply_local(const EntityType& entity) DS_OVERRIDE { result_ = result_ + compute_locally(entity); } virtual void finalize() DS_OVERRIDE { if (!finalized_) { FieldType tmp = result_; result_ = grid_view_.comm().sum(tmp); finalized_ = true; } } FieldType apply2() { if (!finalized_) { Stuff::Grid::Walker<GridViewType> grid_walker(grid_view_); grid_walker.add(*this); grid_walker.walk(); } return result_; } private: const GridViewType& grid_view_; const RangeType& range_; const SourceType& source_; std::unique_ptr<TmpMatricesProviderType> tmp_storage_; bool prepared_; bool finalized_; std::atomic<FieldType> result_; }; // class LocalizableBase /** * \todo Derive from SystemAssembler, \see Operators::EllipticG */ template <class Traits> class AssemblableBase : public AssemblableProductInterface<Traits>, public Stuff::Grid::Functor::Codim0<typename Traits::GridViewType> { typedef AssemblableProductInterface<Traits> InterfaceType; public: typedef typename Traits::GridViewType GridViewType; typedef typename Traits::RangeSpaceType RangeSpaceType; typedef typename Traits::SourceSpaceType SourceSpaceType; typedef typename Traits::MatrixType MatrixType; typedef typename MatrixType::ScalarType FieldType; private: typedef TmpStorageProvider::Matrices<FieldType> TmpMatricesProviderType; typedef typename Traits::LocalOperatorType LocalOperatorType; typedef LocalAssembler::Codim0Matrix<LocalOperatorType> LocalAssemblerType; public: using typename InterfaceType::EntityType; using InterfaceType::pattern; AssemblableBase(MatrixType& mtrx, const RangeSpaceType& rng_spc, const GridViewType& grd_vw, const SourceSpaceType& src_spc) : matrix_(mtrx) , range_space_(rng_spc) , grid_view_(grd_vw) , source_space_(src_spc) , local_assembler_(nullptr) , tmp_storage_(nullptr) , prepared_(false) , assembled_(false) { } AssemblableBase(MatrixType& mtrx, const RangeSpaceType& rng_spc, const GridViewType& grd_vw) : matrix_(mtrx) , range_space_(rng_spc) , grid_view_(grd_vw) , source_space_(range_space_) , local_assembler_(nullptr) , tmp_storage_(nullptr) , prepared_(false) , assembled_(false) { } AssemblableBase(MatrixType& mtrx, const RangeSpaceType& rng_spc) : matrix_(mtrx) , range_space_(rng_spc) , grid_view_(*(range_space_->grid_view())) , source_space_(range_space_) , local_assembler_(nullptr) , tmp_storage_(nullptr) , prepared_(false) , assembled_(false) { } const GridViewType& grid_view() const { return grid_view_; } const RangeSpaceType& range_space() const { return range_space_; } const SourceSpaceType& source_space() const { return source_space_; } MatrixType& matrix() { return matrix_; } const MatrixType& matrix() const { return matrix_; } private: virtual const LocalOperatorType& local_operator() const = 0; public: virtual void prepare() DS_OVERRIDE { if (!assembled_ && !prepared_) { local_assembler_ = std::unique_ptr<LocalAssemblerType>(new LocalAssemblerType(local_operator())); tmp_storage_ = std::unique_ptr<TmpMatricesProviderType>( new TmpMatricesProviderType(local_assembler_->numTmpObjectsRequired(), range_space_.mapper().maxNumDofs(), source_space_.mapper().maxNumDofs())); prepared_ = true; } } // ... prepare() virtual void apply_local(const EntityType& entity) DS_OVERRIDE { assert(prepared_); assert(local_assembler_); assert(tmp_storage_); local_assembler_->assembleLocal( range_space_, source_space_, entity, matrix_, tmp_storage_->matrices(), tmp_storage_->indices()); } // ... apply_local(...) void assemble() { if (!assembled_) { Stuff::Grid::Walker<GridViewType> grid_walker(grid_view_); grid_walker.add(*this); grid_walker.walk(); assembled_ = true; } } // ... assemble() using InterfaceType::apply2; private: MatrixType& matrix_; const RangeSpaceType& range_space_; const GridViewType& grid_view_; const SourceSpaceType& source_space_; std::unique_ptr<LocalAssemblerType> local_assembler_; std::unique_ptr<TmpMatricesProviderType> tmp_storage_; bool prepared_; bool assembled_; }; // class AssemblableBase } // namespace Products } // namespace GDT } // namespace Dune #endif // DUNE_GDT_PRODUCTS_BASE_HH <|endoftext|>
<commit_before>/* * Initial version copied from https://github.com/JetBrains/intellij-community/blob/master/native/fsNotifier/mac/fsnotifier.c */ // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. /* * Apple specific functions. */ #if defined(__APPLE__) #include "native.h" #include "generic.h" #include <CoreServices/CoreServices.h> #include <pthread.h> #include <strings.h> JavaVM* jvm = NULL; bool invalidStateDetected = false; typedef struct watch_details { CFMutableArrayRef rootsToWatch; FSEventStreamRef watcherStream; pthread_t watcherThread; jobject watcherCallback; CFRunLoopRef threadLoop; } watch_details_t; static void reportEvent(jint type, char *path, jobject watcherCallback) { // TODO What does this do? size_t len = 0; if (path != NULL) { len = strlen(path); for (char *p = path; *p != '\0'; p++) { if (*p == '\n') { *p = '\0'; } } } // TODO Extract this logic to some global function JNIEnv* env; int getEnvStat = jvm->GetEnv((void **)&env, JNI_VERSION_1_6); if (getEnvStat == JNI_EDETACHED) { if (jvm->AttachCurrentThread((void **) &env, NULL) != JNI_OK) { invalidStateDetected = true; return; } } else if (getEnvStat == JNI_EVERSION) { invalidStateDetected = true; return; } printf("~~~~ Changed: %s %d\n", path, type); jclass callback_class = env->GetObjectClass(watcherCallback); jmethodID methodCallback = env->GetMethodID(callback_class, "pathChanged", "(ILjava/lang/String;)V"); env->CallVoidMethod(watcherCallback, methodCallback, type, env->NewStringUTF(path)); } static void callback(ConstFSEventStreamRef streamRef, void *clientCallBackInfo, size_t numEvents, void *eventPaths, const FSEventStreamEventFlags eventFlags[], const FSEventStreamEventId eventIds[]) { if (invalidStateDetected) return; char **paths = (char**) eventPaths; jobject watcherCallback = (jobject) clientCallBackInfo; for (int i = 0; i < numEvents; i++) { FSEventStreamEventFlags flags = eventFlags[i]; printf("~~~~ Event flags: 0x%x for %s\n", flags, paths[i]); jint type; if (IS_SET(flags, kFSEventStreamEventFlagMustScanSubDirs)) { type = FILE_EVENT_INVALIDATE; } else if (IS_SET(flags, kFSEventStreamEventFlagItemRenamed)) { if (IS_SET(flags, kFSEventStreamEventFlagItemCreated)) { type = FILE_EVENT_REMOVED; } else { type = FILE_EVENT_CREATED; } } else if (IS_SET(flags, kFSEventStreamEventFlagItemModified)) { type = FILE_EVENT_MODIFIED; } else if (IS_SET(flags, kFSEventStreamEventFlagItemRemoved)) { type = FILE_EVENT_REMOVED; } else if (IS_SET(flags, kFSEventStreamEventFlagItemCreated)) { type = FILE_EVENT_CREATED; } else { printf("~~~~ Unknown event 0x%x for %s\n", flags, paths[i]); type = FILE_EVENT_UNKNOWN; } reportEvent(type, paths[i], watcherCallback); } } static void *EventProcessingThread(void *data) { watch_details_t *details = (watch_details_t*) data; printf("~~~~ Starting thread\n"); CFRunLoopRef threadLoop = CFRunLoopGetCurrent(); FSEventStreamScheduleWithRunLoop(details->watcherStream, threadLoop, kCFRunLoopDefaultMode); FSEventStreamStart(details->watcherStream); details->threadLoop = threadLoop; // TODO We should wait for this in the caller thread otherwise stopWatching() might crash // This triggers run loop for this thread, causing it to run until we explicitly stop it. CFRunLoopRun(); printf("~~~~ Stopping thread\n"); return NULL; } void freeDetails(JNIEnv *env, watch_details_t *details) { CFMutableArrayRef rootsToWatch = details->rootsToWatch; FSEventStreamRef watcherStream = details->watcherStream; pthread_t watcherThread = details->watcherThread; jobject watcherCallback = details->watcherCallback; CFRunLoopRef threadLoop = details->threadLoop; free(details); if (threadLoop != NULL) { CFRunLoopStop(threadLoop); } if (watcherThread != NULL) { pthread_join(watcherThread, NULL); } if (rootsToWatch != NULL) { for (int i = 0; i < CFArrayGetCount(rootsToWatch); i++) { const void *value = CFArrayGetValueAtIndex(rootsToWatch, i); CFRelease(value); } // TODO Can we release these earlier? CFRelease(rootsToWatch); } if (watcherStream != NULL) { FSEventStreamStop(watcherStream); FSEventStreamInvalidate(watcherStream); FSEventStreamRelease(watcherStream); // TODO: consider using FSEventStreamFlushSync to flush all pending events. } if (watcherCallback != NULL) { env->DeleteGlobalRef(watcherCallback); } } JNIEXPORT jobject JNICALL Java_net_rubygrapefruit_platform_internal_jni_OsxFileEventFunctions_startWatching(JNIEnv *env, jclass target, jobjectArray paths, long latencyInMillis, jobject javaCallback, jobject result) { printf("\n~~~~ Configuring...\n"); invalidStateDetected = false; CFMutableArrayRef rootsToWatch = CFArrayCreateMutable(NULL, 0, NULL); if (rootsToWatch == NULL) { mark_failed_with_errno(env, "Could not allocate array to store roots to watch.", result); return NULL; } int count = env->GetArrayLength(paths); if (count == 0) { mark_failed_with_errno(env, "No paths given to watch.", result); return NULL; } watch_details_t* details = (watch_details_t*) malloc(sizeof(watch_details_t)); details->rootsToWatch = rootsToWatch; for (int i = 0; i < count; i++) { jstring path = (jstring) env->GetObjectArrayElement(paths, i); char* watchedPath = java_to_char(env, path, result); printf("~~~~ Watching %s\n", watchedPath); if (watchedPath == NULL) { mark_failed_with_errno(env, "Could not allocate string to store root to watch.", result); freeDetails(env, details); return NULL; } CFStringRef stringPath = CFStringCreateWithCString(NULL, watchedPath, kCFStringEncodingUTF8); free(watchedPath); if (stringPath == NULL) { mark_failed_with_errno(env, "Could not create CFStringRef.", result); freeDetails(env, details); return NULL; } CFArrayAppendValue(rootsToWatch, stringPath); } details->watcherCallback = env->NewGlobalRef(javaCallback); if (details->watcherCallback == NULL) { mark_failed_with_errno(env, "Could not create global reference for callback.", result); freeDetails(env, details); return NULL; } FSEventStreamContext context = {0, (void*) details->watcherCallback, NULL, NULL, NULL}; details->watcherStream = FSEventStreamCreate ( NULL, &callback, &context, rootsToWatch, kFSEventStreamEventIdSinceNow, latencyInMillis / 1000.0, kFSEventStreamCreateFlagNoDefer | kFSEventStreamCreateFlagFileEvents); if (details->watcherStream == NULL) { mark_failed_with_errno(env, "Could not create FSEventStreamCreate to track changes.", result); freeDetails(env, details); return NULL; } if (pthread_create(&(details->watcherThread), NULL, EventProcessingThread, details) != 0) { mark_failed_with_errno(env, "Could not create file watcher thread.", result); freeDetails(env, details); return NULL; } // TODO Should this be somewhere global? int jvmStatus = env->GetJavaVM(&jvm); if (jvmStatus < 0) { mark_failed_with_errno(env, "Could not store jvm instance.", result); freeDetails(env, details); return NULL; } jclass clsWatcher = env->FindClass("net/rubygrapefruit/platform/internal/jni/OsxFileEventFunctions$WatcherImpl"); jmethodID constructor = env->GetMethodID(clsWatcher, "<init>", "(Ljava/lang/Object;)V"); return env->NewObject(clsWatcher, constructor, env->NewDirectByteBuffer(details, sizeof(details))); } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_OsxFileEventFunctions_stopWatching(JNIEnv *env, jclass target, jobject detailsObj, jobject result) { watch_details_t *details = (watch_details_t*) env->GetDirectBufferAddress(detailsObj); if (invalidStateDetected) { // report and reset flag, but try to clean up state as much as possible mark_failed_with_errno(env, "Watcher is in invalid state, reported changes may be incorrect.", result); } freeDetails(env, details); } #endif <commit_msg>Handle locking file event on macOS<commit_after>/* * Initial version copied from https://github.com/JetBrains/intellij-community/blob/master/native/fsNotifier/mac/fsnotifier.c */ // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. /* * Apple specific functions. */ #if defined(__APPLE__) #include "native.h" #include "generic.h" #include <CoreServices/CoreServices.h> #include <pthread.h> #include <strings.h> JavaVM* jvm = NULL; bool invalidStateDetected = false; typedef struct watch_details { CFMutableArrayRef rootsToWatch; FSEventStreamRef watcherStream; pthread_t watcherThread; jobject watcherCallback; CFRunLoopRef threadLoop; } watch_details_t; static void reportEvent(jint type, char *path, jobject watcherCallback) { // TODO What does this do? size_t len = 0; if (path != NULL) { len = strlen(path); for (char *p = path; *p != '\0'; p++) { if (*p == '\n') { *p = '\0'; } } } // TODO Extract this logic to some global function JNIEnv* env; int getEnvStat = jvm->GetEnv((void **)&env, JNI_VERSION_1_6); if (getEnvStat == JNI_EDETACHED) { if (jvm->AttachCurrentThread((void **) &env, NULL) != JNI_OK) { invalidStateDetected = true; return; } } else if (getEnvStat == JNI_EVERSION) { invalidStateDetected = true; return; } printf("~~~~ Changed: %s %d\n", path, type); jclass callback_class = env->GetObjectClass(watcherCallback); jmethodID methodCallback = env->GetMethodID(callback_class, "pathChanged", "(ILjava/lang/String;)V"); env->CallVoidMethod(watcherCallback, methodCallback, type, env->NewStringUTF(path)); } static void callback(ConstFSEventStreamRef streamRef, void *clientCallBackInfo, size_t numEvents, void *eventPaths, const FSEventStreamEventFlags eventFlags[], const FSEventStreamEventId eventIds[]) { if (invalidStateDetected) return; char **paths = (char**) eventPaths; jobject watcherCallback = (jobject) clientCallBackInfo; for (int i = 0; i < numEvents; i++) { FSEventStreamEventFlags flags = eventFlags[i]; printf("~~~~ Event flags: 0x%x for %s\n", flags, paths[i]); jint type; if (IS_SET(flags, kFSEventStreamEventFlagMustScanSubDirs)) { type = FILE_EVENT_INVALIDATE; } else if (IS_SET(flags, kFSEventStreamEventFlagItemRenamed)) { if (IS_SET(flags, kFSEventStreamEventFlagItemCreated)) { type = FILE_EVENT_REMOVED; } else { type = FILE_EVENT_CREATED; } } else if (IS_SET(flags, kFSEventStreamEventFlagItemModified)) { type = FILE_EVENT_MODIFIED; } else if (IS_SET(flags, kFSEventStreamEventFlagItemRemoved)) { type = FILE_EVENT_REMOVED; } else if (IS_SET(flags, kFSEventStreamEventFlagItemCreated)) { type = FILE_EVENT_CREATED; } else if (IS_SET(flags, kFSEventStreamEventFlagItemInodeMetaMod)) { // File locked type = FILE_EVENT_MODIFIED; } else { printf("~~~~ Unknown event 0x%x for %s\n", flags, paths[i]); type = FILE_EVENT_UNKNOWN; } reportEvent(type, paths[i], watcherCallback); } } static void *EventProcessingThread(void *data) { watch_details_t *details = (watch_details_t*) data; printf("~~~~ Starting thread\n"); CFRunLoopRef threadLoop = CFRunLoopGetCurrent(); FSEventStreamScheduleWithRunLoop(details->watcherStream, threadLoop, kCFRunLoopDefaultMode); FSEventStreamStart(details->watcherStream); details->threadLoop = threadLoop; // TODO We should wait for this in the caller thread otherwise stopWatching() might crash // This triggers run loop for this thread, causing it to run until we explicitly stop it. CFRunLoopRun(); printf("~~~~ Stopping thread\n"); return NULL; } void freeDetails(JNIEnv *env, watch_details_t *details) { CFMutableArrayRef rootsToWatch = details->rootsToWatch; FSEventStreamRef watcherStream = details->watcherStream; pthread_t watcherThread = details->watcherThread; jobject watcherCallback = details->watcherCallback; CFRunLoopRef threadLoop = details->threadLoop; free(details); if (threadLoop != NULL) { CFRunLoopStop(threadLoop); } if (watcherThread != NULL) { pthread_join(watcherThread, NULL); } if (rootsToWatch != NULL) { for (int i = 0; i < CFArrayGetCount(rootsToWatch); i++) { const void *value = CFArrayGetValueAtIndex(rootsToWatch, i); CFRelease(value); } // TODO Can we release these earlier? CFRelease(rootsToWatch); } if (watcherStream != NULL) { FSEventStreamStop(watcherStream); FSEventStreamInvalidate(watcherStream); FSEventStreamRelease(watcherStream); // TODO: consider using FSEventStreamFlushSync to flush all pending events. } if (watcherCallback != NULL) { env->DeleteGlobalRef(watcherCallback); } } JNIEXPORT jobject JNICALL Java_net_rubygrapefruit_platform_internal_jni_OsxFileEventFunctions_startWatching(JNIEnv *env, jclass target, jobjectArray paths, long latencyInMillis, jobject javaCallback, jobject result) { printf("\n~~~~ Configuring...\n"); invalidStateDetected = false; CFMutableArrayRef rootsToWatch = CFArrayCreateMutable(NULL, 0, NULL); if (rootsToWatch == NULL) { mark_failed_with_errno(env, "Could not allocate array to store roots to watch.", result); return NULL; } int count = env->GetArrayLength(paths); if (count == 0) { mark_failed_with_errno(env, "No paths given to watch.", result); return NULL; } watch_details_t* details = (watch_details_t*) malloc(sizeof(watch_details_t)); details->rootsToWatch = rootsToWatch; for (int i = 0; i < count; i++) { jstring path = (jstring) env->GetObjectArrayElement(paths, i); char* watchedPath = java_to_char(env, path, result); printf("~~~~ Watching %s\n", watchedPath); if (watchedPath == NULL) { mark_failed_with_errno(env, "Could not allocate string to store root to watch.", result); freeDetails(env, details); return NULL; } CFStringRef stringPath = CFStringCreateWithCString(NULL, watchedPath, kCFStringEncodingUTF8); free(watchedPath); if (stringPath == NULL) { mark_failed_with_errno(env, "Could not create CFStringRef.", result); freeDetails(env, details); return NULL; } CFArrayAppendValue(rootsToWatch, stringPath); } details->watcherCallback = env->NewGlobalRef(javaCallback); if (details->watcherCallback == NULL) { mark_failed_with_errno(env, "Could not create global reference for callback.", result); freeDetails(env, details); return NULL; } FSEventStreamContext context = {0, (void*) details->watcherCallback, NULL, NULL, NULL}; details->watcherStream = FSEventStreamCreate ( NULL, &callback, &context, rootsToWatch, kFSEventStreamEventIdSinceNow, latencyInMillis / 1000.0, kFSEventStreamCreateFlagNoDefer | kFSEventStreamCreateFlagFileEvents); if (details->watcherStream == NULL) { mark_failed_with_errno(env, "Could not create FSEventStreamCreate to track changes.", result); freeDetails(env, details); return NULL; } if (pthread_create(&(details->watcherThread), NULL, EventProcessingThread, details) != 0) { mark_failed_with_errno(env, "Could not create file watcher thread.", result); freeDetails(env, details); return NULL; } // TODO Should this be somewhere global? int jvmStatus = env->GetJavaVM(&jvm); if (jvmStatus < 0) { mark_failed_with_errno(env, "Could not store jvm instance.", result); freeDetails(env, details); return NULL; } jclass clsWatcher = env->FindClass("net/rubygrapefruit/platform/internal/jni/OsxFileEventFunctions$WatcherImpl"); jmethodID constructor = env->GetMethodID(clsWatcher, "<init>", "(Ljava/lang/Object;)V"); return env->NewObject(clsWatcher, constructor, env->NewDirectByteBuffer(details, sizeof(details))); } JNIEXPORT void JNICALL Java_net_rubygrapefruit_platform_internal_jni_OsxFileEventFunctions_stopWatching(JNIEnv *env, jclass target, jobject detailsObj, jobject result) { watch_details_t *details = (watch_details_t*) env->GetDirectBufferAddress(detailsObj); if (invalidStateDetected) { // report and reset flag, but try to clean up state as much as possible mark_failed_with_errno(env, "Watcher is in invalid state, reported changes may be incorrect.", result); } freeDetails(env, details); } #endif <|endoftext|>
<commit_before>// Longest common prefix // 9/2/2017 // Easy #include <iostream> #include <vector> #include <string> #include <cassert> using namespace std; string longestcommonprefix(vector<string> &strs) { if (strs.empty()) return ""; for (int i = 0; i < strs[0].size(); i++) { for (int j = 1; j < strs.size(); j++) { if (strs[0][i] != strs[j][i]) return strs[0].substr(0, i); } } return strs[0]; } int main() { vector<string> strs; strs.push_back("abcdef"); strs.push_back("abc"); strs.push_back("abcf"); string prefix = longestcommonprefix(strs); assert(prefix == "abc"); return 0; } <commit_msg>longest common prefix - 2<commit_after>// Longest common prefix // 9/2/2017 // Easy #include <iostream> #include <vector> #include <string> #include <cassert> using namespace std; string longestcommonprefix(vector<string> &strs) { if (strs.empty()) return ""; for (int i = 0; i < strs[0].size(); i++) { for (int j = 1; j < strs.size(); j++) { if (strs[0][i] != strs[j][i]) return strs[0].substr(0, i); } } return strs[0]; } string longestcommonprefix2(vector<string> &strs) { if (strs.empty()) return ""; int right_most = strs[0].size() - 1; for (int i = 1; i < strs.size(); i++) { for (int j = 0; j <= right_most; j++) if (strs[i][j] != strs[0][j]) right_most = j - 1; } return strs[0].substr(0, right_most + 1); } int main() { vector<string> strs; strs.push_back("abcdef"); strs.push_back("abc"); strs.push_back("abcf"); string prefix = longestcommonprefix(strs); assert(prefix == "abc"); prefix = longestcommonprefix2(strs); assert(prefix == "abc"); return 0; } <|endoftext|>
<commit_before>/******************************************************************************* * Project: Nebula * @file CmdOnSetCustomConf.hpp * @brief 设置自定义配置文件 * @author Bwar * @date: 2019年9月14日 * @note * Modify history: ******************************************************************************/ #include "CmdOnSetCustomConf.hpp" #include "actor/session/sys_session/manager/SessionManager.hpp" namespace neb { CmdOnSetCustomConf::CmdOnSetCustomConf(int32 iCmd) : Cmd(iCmd) { } CmdOnSetCustomConf::~CmdOnSetCustomConf() { } bool CmdOnSetCustomConf::AnyMessage( std::shared_ptr<SocketChannel> pChannel, const MsgHead& oInMsgHead, const MsgBody& oInMsgBody) { if (m_pSessionManager == nullptr) { m_pSessionManager = std::dynamic_pointer_cast<SessionManager>( GetSession("neb::SessionManager")); if (m_pSessionManager == nullptr) { LOG4_ERROR("no session named \"neb::SessionManager\"!"); return(false); } } MsgBody oOutMsgBody; ConfigInfo oConfigInfo; if (oConfigInfo.ParseFromString(oInMsgBody.data())) { std::stringstream ssConfFile; if (oConfigInfo.file_path().size() > 0) { ssConfFile << GetLabor(this)->GetNodeInfo().strWorkPath << "/conf/" << oConfigInfo.file_path() << "/" << oConfigInfo.file_name(); } else { ssConfFile << GetLabor(this)->GetNodeInfo().strWorkPath << "/conf/" << oConfigInfo.file_name(); } std::ofstream fout(ssConfFile.str().c_str()); if (fout.good()) { fout.write(oConfigInfo.file_content().c_str(), oConfigInfo.file_content().size()); fout.close(); oOutMsgBody.mutable_rsp_result()->set_code(ERR_OK); oOutMsgBody.mutable_rsp_result()->set_msg("success"); m_pSessionManager->SendToChild(CMD_REQ_SET_CUSTOM_CONFIG, GetSequence(), oInMsgBody); m_pSessionManager->SendToChild(CMD_REQ_RELOAD_CUSTOM_CONFIG, GetSequence(), oInMsgBody); SendTo(pChannel, oInMsgHead.cmd() + 1, oInMsgHead.seq(), oOutMsgBody); return(true); } else { oOutMsgBody.mutable_rsp_result()->set_code(ERR_FILE_NOT_EXIST); oOutMsgBody.mutable_rsp_result()->set_msg("file \"" + ssConfFile.str() + "\" not exist!"); SendTo(pChannel, oInMsgHead.cmd() + 1, oInMsgHead.seq(), oOutMsgBody); return(false); } } else { oOutMsgBody.mutable_rsp_result()->set_code(ERR_PARASE_PROTOBUF); oOutMsgBody.mutable_rsp_result()->set_msg("ConfigInfo.ParseFromString() failed."); SendTo(pChannel, oInMsgHead.cmd() + 1, oInMsgHead.seq(), oOutMsgBody); return(false); } } } /* namespace neb */ <commit_msg>CMD_REQ_SET_CUSTOM_CONFIG no need in worker<commit_after>/******************************************************************************* * Project: Nebula * @file CmdOnSetCustomConf.hpp * @brief 设置自定义配置文件 * @author Bwar * @date: 2019年9月14日 * @note * Modify history: ******************************************************************************/ #include "CmdOnSetCustomConf.hpp" #include "actor/session/sys_session/manager/SessionManager.hpp" namespace neb { CmdOnSetCustomConf::CmdOnSetCustomConf(int32 iCmd) : Cmd(iCmd) { } CmdOnSetCustomConf::~CmdOnSetCustomConf() { } bool CmdOnSetCustomConf::AnyMessage( std::shared_ptr<SocketChannel> pChannel, const MsgHead& oInMsgHead, const MsgBody& oInMsgBody) { if (m_pSessionManager == nullptr) { m_pSessionManager = std::dynamic_pointer_cast<SessionManager>( GetSession("neb::SessionManager")); if (m_pSessionManager == nullptr) { LOG4_ERROR("no session named \"neb::SessionManager\"!"); return(false); } } MsgBody oOutMsgBody; ConfigInfo oConfigInfo; if (oConfigInfo.ParseFromString(oInMsgBody.data())) { std::stringstream ssConfFile; if (oConfigInfo.file_path().size() > 0) { ssConfFile << GetLabor(this)->GetNodeInfo().strWorkPath << "/conf/" << oConfigInfo.file_path() << "/" << oConfigInfo.file_name(); } else { ssConfFile << GetLabor(this)->GetNodeInfo().strWorkPath << "/conf/" << oConfigInfo.file_name(); } std::ofstream fout(ssConfFile.str().c_str()); if (fout.good()) { fout.write(oConfigInfo.file_content().c_str(), oConfigInfo.file_content().size()); fout.close(); oOutMsgBody.mutable_rsp_result()->set_code(ERR_OK); oOutMsgBody.mutable_rsp_result()->set_msg("success"); m_pSessionManager->SendToChild(CMD_REQ_RELOAD_CUSTOM_CONFIG, GetSequence(), oInMsgBody); SendTo(pChannel, oInMsgHead.cmd() + 1, oInMsgHead.seq(), oOutMsgBody); return(true); } else { oOutMsgBody.mutable_rsp_result()->set_code(ERR_FILE_NOT_EXIST); oOutMsgBody.mutable_rsp_result()->set_msg("file \"" + ssConfFile.str() + "\" not exist!"); SendTo(pChannel, oInMsgHead.cmd() + 1, oInMsgHead.seq(), oOutMsgBody); return(false); } } else { oOutMsgBody.mutable_rsp_result()->set_code(ERR_PARASE_PROTOBUF); oOutMsgBody.mutable_rsp_result()->set_msg("ConfigInfo.ParseFromString() failed."); SendTo(pChannel, oInMsgHead.cmd() + 1, oInMsgHead.seq(), oOutMsgBody); return(false); } } } /* namespace neb */ <|endoftext|>
<commit_before><commit_msg>málfarslagfæringar, smásnittbreytingar<commit_after><|endoftext|>
<commit_before>/* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "Benchmark.h" #include "Resources.h" #include "SkBitmap.h" #include "SkJpegEncoder.h" #include "SkPngEncoder.h" #include "SkWebpEncoder.h" #include "SkStream.h" class EncodeBench : public Benchmark { public: using Encoder = bool (*)(SkWStream*, const SkPixmap&); EncodeBench(const char* filename, Encoder encoder, const char* encoderName) : fSourceFilename(filename) , fEncoder(encoder) , fName(SkStringPrintf("Encode_%s_%s", filename, encoderName)) {} bool isSuitableFor(Backend backend) override { return backend == kNonRendering_Backend; } const char* onGetName() override { return fName.c_str(); } void onDelayedSetup() override { SkAssertResult(GetResourceAsBitmap(fSourceFilename, &fBitmap)); } void onDraw(int loops, SkCanvas*) override { while (loops-- > 0) { SkPixmap pixmap; SkAssertResult(fBitmap.peekPixels(&pixmap)); SkNullWStream dst; SkAssertResult(fEncoder(&dst, pixmap)); SkASSERT(dst.bytesWritten() > 0); } } private: const char* fSourceFilename; Encoder fEncoder; SkString fName; SkBitmap fBitmap; }; static bool encode_jpeg(SkWStream* dst, const SkPixmap& src) { SkJpegEncoder::Options opts; opts.fQuality = 90; return SkJpegEncoder::Encode(dst, src, opts); } static bool encode_webp_lossy(SkWStream* dst, const SkPixmap& src) { SkWebpEncoder::Options opts; opts.fCompression = SkWebpEncoder::Compression::kLossy; opts.fQuality = 90; return SkWebpEncoder::Encode(dst, src, opts); } static bool encode_webp_lossless(SkWStream* dst, const SkPixmap& src) { SkWebpEncoder::Options opts; opts.fCompression = SkWebpEncoder::Compression::kLossless; opts.fQuality = 90; return SkWebpEncoder::Encode(dst, src, opts); } static bool encode_png(SkWStream* dst, const SkPixmap& src, SkPngEncoder::FilterFlag filters, int zlibLevel) { SkPngEncoder::Options opts; opts.fFilterFlags = filters; opts.fZLibLevel = zlibLevel; return SkPngEncoder::Encode(dst, src, opts); } #define PNG(FLAG, ZLIBLEVEL) [](SkWStream* d, const SkPixmap& s) { \ return encode_png(d, s, SkPngEncoder::FilterFlag::FLAG, ZLIBLEVEL); } static const char* srcs[2] = {"images/mandrill_512.png", "images/color_wheel.jpg"}; // The Android Photos app uses a quality of 90 on JPEG encodes DEF_BENCH(return new EncodeBench(srcs[0], &encode_jpeg, "JPEG")); DEF_BENCH(return new EncodeBench(srcs[1], &encode_jpeg, "JPEG")); // TODO: What is the appropriate quality to use to benchmark WEBP encodes? DEF_BENCH(return new EncodeBench(srcs[0], encode_webp_lossy, "WEBP")); DEF_BENCH(return new EncodeBench(srcs[1], encode_webp_lossy, "WEBP")); DEF_BENCH(return new EncodeBench(srcs[0], encode_webp_lossless, "WEBP_LL")); DEF_BENCH(return new EncodeBench(srcs[1], encode_webp_lossless, "WEBP_LL")); DEF_BENCH(return new EncodeBench(srcs[0], PNG(kAll, 6), "PNG")); DEF_BENCH(return new EncodeBench(srcs[0], PNG(kAll, 3), "PNG_3")); DEF_BENCH(return new EncodeBench(srcs[0], PNG(kAll, 1), "PNG_1")); DEF_BENCH(return new EncodeBench(srcs[0], PNG(kSub, 6), "PNG_6s")); DEF_BENCH(return new EncodeBench(srcs[0], PNG(kSub, 3), "PNG_3s")); DEF_BENCH(return new EncodeBench(srcs[0], PNG(kSub, 1), "PNG_1s")); DEF_BENCH(return new EncodeBench(srcs[0], PNG(kNone, 6), "PNG_6n")); DEF_BENCH(return new EncodeBench(srcs[0], PNG(kNone, 3), "PNG_3n")); DEF_BENCH(return new EncodeBench(srcs[0], PNG(kNone, 1), "PNG_1n")); DEF_BENCH(return new EncodeBench(srcs[1], PNG(kAll, 6), "PNG")); DEF_BENCH(return new EncodeBench(srcs[1], PNG(kAll, 3), "PNG_3")); DEF_BENCH(return new EncodeBench(srcs[1], PNG(kAll, 1), "PNG_1")); DEF_BENCH(return new EncodeBench(srcs[1], PNG(kSub, 6), "PNG_6s")); DEF_BENCH(return new EncodeBench(srcs[1], PNG(kSub, 3), "PNG_3s")); DEF_BENCH(return new EncodeBench(srcs[1], PNG(kSub, 1), "PNG_1s")); DEF_BENCH(return new EncodeBench(srcs[1], PNG(kNone, 6), "PNG_6n")); DEF_BENCH(return new EncodeBench(srcs[1], PNG(kNone, 3), "PNG_3n")); DEF_BENCH(return new EncodeBench(srcs[1], PNG(kNone, 1), "PNG_1n")); #undef PNG <commit_msg>Add comment about how to run Decoder benchmarks<commit_after>/* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "Benchmark.h" #include "Resources.h" #include "SkBitmap.h" #include "SkJpegEncoder.h" #include "SkPngEncoder.h" #include "SkWebpEncoder.h" #include "SkStream.h" // Like other Benchmark subclasses, Encoder benchmarks are run by: // nanobench --match ^Encode_ // // There is no corresponding DecodeBench class. Decoder benchmarks are run by: // nanobench --benchType skcodec --images your_images_directory class EncodeBench : public Benchmark { public: using Encoder = bool (*)(SkWStream*, const SkPixmap&); EncodeBench(const char* filename, Encoder encoder, const char* encoderName) : fSourceFilename(filename) , fEncoder(encoder) , fName(SkStringPrintf("Encode_%s_%s", filename, encoderName)) {} bool isSuitableFor(Backend backend) override { return backend == kNonRendering_Backend; } const char* onGetName() override { return fName.c_str(); } void onDelayedSetup() override { SkAssertResult(GetResourceAsBitmap(fSourceFilename, &fBitmap)); } void onDraw(int loops, SkCanvas*) override { while (loops-- > 0) { SkPixmap pixmap; SkAssertResult(fBitmap.peekPixels(&pixmap)); SkNullWStream dst; SkAssertResult(fEncoder(&dst, pixmap)); SkASSERT(dst.bytesWritten() > 0); } } private: const char* fSourceFilename; Encoder fEncoder; SkString fName; SkBitmap fBitmap; }; static bool encode_jpeg(SkWStream* dst, const SkPixmap& src) { SkJpegEncoder::Options opts; opts.fQuality = 90; return SkJpegEncoder::Encode(dst, src, opts); } static bool encode_webp_lossy(SkWStream* dst, const SkPixmap& src) { SkWebpEncoder::Options opts; opts.fCompression = SkWebpEncoder::Compression::kLossy; opts.fQuality = 90; return SkWebpEncoder::Encode(dst, src, opts); } static bool encode_webp_lossless(SkWStream* dst, const SkPixmap& src) { SkWebpEncoder::Options opts; opts.fCompression = SkWebpEncoder::Compression::kLossless; opts.fQuality = 90; return SkWebpEncoder::Encode(dst, src, opts); } static bool encode_png(SkWStream* dst, const SkPixmap& src, SkPngEncoder::FilterFlag filters, int zlibLevel) { SkPngEncoder::Options opts; opts.fFilterFlags = filters; opts.fZLibLevel = zlibLevel; return SkPngEncoder::Encode(dst, src, opts); } #define PNG(FLAG, ZLIBLEVEL) [](SkWStream* d, const SkPixmap& s) { \ return encode_png(d, s, SkPngEncoder::FilterFlag::FLAG, ZLIBLEVEL); } static const char* srcs[2] = {"images/mandrill_512.png", "images/color_wheel.jpg"}; // The Android Photos app uses a quality of 90 on JPEG encodes DEF_BENCH(return new EncodeBench(srcs[0], &encode_jpeg, "JPEG")); DEF_BENCH(return new EncodeBench(srcs[1], &encode_jpeg, "JPEG")); // TODO: What is the appropriate quality to use to benchmark WEBP encodes? DEF_BENCH(return new EncodeBench(srcs[0], encode_webp_lossy, "WEBP")); DEF_BENCH(return new EncodeBench(srcs[1], encode_webp_lossy, "WEBP")); DEF_BENCH(return new EncodeBench(srcs[0], encode_webp_lossless, "WEBP_LL")); DEF_BENCH(return new EncodeBench(srcs[1], encode_webp_lossless, "WEBP_LL")); DEF_BENCH(return new EncodeBench(srcs[0], PNG(kAll, 6), "PNG")); DEF_BENCH(return new EncodeBench(srcs[0], PNG(kAll, 3), "PNG_3")); DEF_BENCH(return new EncodeBench(srcs[0], PNG(kAll, 1), "PNG_1")); DEF_BENCH(return new EncodeBench(srcs[0], PNG(kSub, 6), "PNG_6s")); DEF_BENCH(return new EncodeBench(srcs[0], PNG(kSub, 3), "PNG_3s")); DEF_BENCH(return new EncodeBench(srcs[0], PNG(kSub, 1), "PNG_1s")); DEF_BENCH(return new EncodeBench(srcs[0], PNG(kNone, 6), "PNG_6n")); DEF_BENCH(return new EncodeBench(srcs[0], PNG(kNone, 3), "PNG_3n")); DEF_BENCH(return new EncodeBench(srcs[0], PNG(kNone, 1), "PNG_1n")); DEF_BENCH(return new EncodeBench(srcs[1], PNG(kAll, 6), "PNG")); DEF_BENCH(return new EncodeBench(srcs[1], PNG(kAll, 3), "PNG_3")); DEF_BENCH(return new EncodeBench(srcs[1], PNG(kAll, 1), "PNG_1")); DEF_BENCH(return new EncodeBench(srcs[1], PNG(kSub, 6), "PNG_6s")); DEF_BENCH(return new EncodeBench(srcs[1], PNG(kSub, 3), "PNG_3s")); DEF_BENCH(return new EncodeBench(srcs[1], PNG(kSub, 1), "PNG_1s")); DEF_BENCH(return new EncodeBench(srcs[1], PNG(kNone, 6), "PNG_6n")); DEF_BENCH(return new EncodeBench(srcs[1], PNG(kNone, 3), "PNG_3n")); DEF_BENCH(return new EncodeBench(srcs[1], PNG(kNone, 1), "PNG_1n")); #undef PNG <|endoftext|>
<commit_before>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2017, Irstea * 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 Irstea nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ #include <four_wheel_steering_controller/odometry.h> #include <boost/bind.hpp> #include <ros/ros.h> namespace four_wheel_steering_controller { namespace bacc = boost::accumulators; Odometry::Odometry(size_t velocity_rolling_window_size) : timestamp_(0.0) , last_update_timestamp_(0.0) , x_(0.0) , y_(0.0) , heading_(0.0) , linear_(0.0) , linear_x_(0.0) , linear_y_(0.0) , angular_(0.0) , steering_track_(0.0) , wheel_steering_y_offset_(0.0) , wheel_radius_(0.0) , wheel_base_(0.0) , wheel_old_pos_(0.0) , velocity_rolling_window_size_(velocity_rolling_window_size) , linear_acc_(RollingWindow::window_size = velocity_rolling_window_size) , angular_acc_(RollingWindow::window_size = velocity_rolling_window_size) { } void Odometry::init(const ros::Time& time) { // Reset accumulators and timestamp: resetAccumulators(); timestamp_ = time; } bool Odometry::update(const double &fl_speed, const double &fr_speed, const double &rl_speed, const double &rr_speed, double front_steering, double rear_steering, const ros::Time &time) { const double front_tmp = cos(front_steering)*(tan(front_steering)-tan(rear_steering))/wheel_base_; const double front_left_tmp = front_tmp/sqrt(1-steering_track_*front_tmp*cos(front_steering) +pow(steering_track_*front_tmp/2,2)); const double front_right_tmp = front_tmp/sqrt(1+steering_track_*front_tmp*cos(front_steering) +pow(steering_track_*front_tmp/2,2)); const double fl_speed_tmp = fl_speed * (1/(1-wheel_steering_y_offset_*front_left_tmp)); const double fr_speed_tmp = fr_speed * (1/(1-wheel_steering_y_offset_*front_right_tmp)); const double front_linear_speed = wheel_radius_ * copysign(1.0, fl_speed_tmp+fr_speed_tmp)* sqrt((pow(fl_speed,2)+pow(fr_speed,2))/(2+pow(steering_track_*front_tmp,2)/2.0)); const double rear_tmp = cos(rear_steering)*(tan(front_steering)-tan(rear_steering))/wheel_base_; const double rear_left_tmp = rear_tmp/sqrt(1-steering_track_*rear_tmp*cos(rear_steering) +pow(steering_track_*rear_tmp/2,2)); const double rear_right_tmp = rear_tmp/sqrt(1+steering_track_*rear_tmp*cos(rear_steering) +pow(steering_track_*rear_tmp/2,2)); const double rl_speed_tmp = rl_speed * (1/(1-wheel_steering_y_offset_*rear_left_tmp)); const double rr_speed_tmp = rr_speed * (1/(1-wheel_steering_y_offset_*rear_right_tmp)); const double rear_linear_speed = wheel_radius_ * copysign(1.0, rl_speed_tmp+rr_speed_tmp)* sqrt((pow(rl_speed_tmp,2)+pow(rr_speed_tmp,2))/(2+pow(steering_track_*rear_tmp,2)/2.0)); //ROS_INFO_STREAM("front_angular_speed "<<front_linear_speed*front_tmp<<"rear_angular_speed "<<rear_linear_speed*rear_tmp); angular_ = rear_linear_speed*rear_tmp; linear_x_ = rear_linear_speed*cos(rear_steering); linear_y_ = rear_linear_speed*sin(rear_steering) + wheel_base_*angular_/2.0; linear_ = copysign(1.0, rear_linear_speed)*sqrt(pow(linear_x_,2)+pow(linear_y_,2)); /// Compute x, y and heading using velocity const double dt = (time - last_update_timestamp_).toSec(); last_update_timestamp_ = time; /// Integrate odometry: integrateXY(linear_x_*dt, linear_y_*dt, angular_*dt); return true; } void Odometry::updateOpenLoop(double linear, double angular, const ros::Time &time) { /// Save last linear and angular velocity: linear_ = linear; angular_ = angular; /// Integrate odometry: const double dt = (time - timestamp_).toSec(); timestamp_ = time; integrateExact(linear * dt, angular * dt); } void Odometry::setWheelParams(double steering_track, double wheel_steering_y_offset, double wheel_radius, double wheel_base) { steering_track_ = steering_track; wheel_steering_y_offset_ = wheel_steering_y_offset; wheel_radius_ = wheel_radius; wheel_base_ = wheel_base; } void Odometry::setVelocityRollingWindowSize(size_t velocity_rolling_window_size) { velocity_rolling_window_size_ = velocity_rolling_window_size; resetAccumulators(); } void Odometry::integrateXY(double linear_x, double linear_y, double angular) { const double delta_x = linear_x*cos(heading_) - linear_y*sin(heading_); const double delta_y = linear_x*sin(heading_) + linear_y*cos(heading_); x_ += delta_x; y_ += delta_y; heading_ += angular; } void Odometry::integrateRungeKutta2(double linear, double angular) { const double direction = heading_ + angular * 0.5; /// Runge-Kutta 2nd order integration: x_ += linear * cos(direction); y_ += linear * sin(direction); heading_ += angular; } void Odometry::integrateExact(double linear, double angular) { if (fabs(angular) < 1e-6) integrateRungeKutta2(linear, angular); else { /// Exact integration (should solve problems when angular is zero): const double heading_old = heading_; const double r = linear/angular; heading_ += angular; x_ += r * (sin(heading_) - sin(heading_old)); y_ += -r * (cos(heading_) - cos(heading_old)); } } void Odometry::resetAccumulators() { linear_acc_ = RollingMeanAcc(RollingWindow::window_size = velocity_rolling_window_size_); angular_acc_ = RollingMeanAcc(RollingWindow::window_size = velocity_rolling_window_size_); } } // namespace four_wheel_steering_controller <commit_msg>[4ws] use front and rear speed for odometry<commit_after>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2017, Irstea * 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 Irstea nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ #include <four_wheel_steering_controller/odometry.h> #include <boost/bind.hpp> namespace four_wheel_steering_controller { namespace bacc = boost::accumulators; Odometry::Odometry(size_t velocity_rolling_window_size) : timestamp_(0.0) , last_update_timestamp_(0.0) , x_(0.0) , y_(0.0) , heading_(0.0) , linear_(0.0) , linear_x_(0.0) , linear_y_(0.0) , angular_(0.0) , steering_track_(0.0) , wheel_steering_y_offset_(0.0) , wheel_radius_(0.0) , wheel_base_(0.0) , wheel_old_pos_(0.0) , velocity_rolling_window_size_(velocity_rolling_window_size) , linear_acc_(RollingWindow::window_size = velocity_rolling_window_size) , angular_acc_(RollingWindow::window_size = velocity_rolling_window_size) { } void Odometry::init(const ros::Time& time) { // Reset accumulators and timestamp: resetAccumulators(); timestamp_ = time; } bool Odometry::update(const double &fl_speed, const double &fr_speed, const double &rl_speed, const double &rr_speed, double front_steering, double rear_steering, const ros::Time &time) { const double front_tmp = cos(front_steering)*(tan(front_steering)-tan(rear_steering))/wheel_base_; const double front_left_tmp = front_tmp/sqrt(1-steering_track_*front_tmp*cos(front_steering) +pow(steering_track_*front_tmp/2,2)); const double front_right_tmp = front_tmp/sqrt(1+steering_track_*front_tmp*cos(front_steering) +pow(steering_track_*front_tmp/2,2)); const double fl_speed_tmp = fl_speed * (1/(1-wheel_steering_y_offset_*front_left_tmp)); const double fr_speed_tmp = fr_speed * (1/(1-wheel_steering_y_offset_*front_right_tmp)); const double front_linear_speed = wheel_radius_ * copysign(1.0, fl_speed_tmp+fr_speed_tmp)* sqrt((pow(fl_speed,2)+pow(fr_speed,2))/(2+pow(steering_track_*front_tmp,2)/2.0)); const double rear_tmp = cos(rear_steering)*(tan(front_steering)-tan(rear_steering))/wheel_base_; const double rear_left_tmp = rear_tmp/sqrt(1-steering_track_*rear_tmp*cos(rear_steering) +pow(steering_track_*rear_tmp/2,2)); const double rear_right_tmp = rear_tmp/sqrt(1+steering_track_*rear_tmp*cos(rear_steering) +pow(steering_track_*rear_tmp/2,2)); const double rl_speed_tmp = rl_speed * (1/(1-wheel_steering_y_offset_*rear_left_tmp)); const double rr_speed_tmp = rr_speed * (1/(1-wheel_steering_y_offset_*rear_right_tmp)); const double rear_linear_speed = wheel_radius_ * copysign(1.0, rl_speed_tmp+rr_speed_tmp)* sqrt((pow(rl_speed_tmp,2)+pow(rr_speed_tmp,2))/(2+pow(steering_track_*rear_tmp,2)/2.0)); angular_ = (front_linear_speed*front_tmp + rear_linear_speed*rear_tmp)/2.0; linear_x_ = (front_linear_speed*cos(front_steering) + rear_linear_speed*cos(rear_steering))/2.0; linear_y_ = (front_linear_speed*sin(front_steering) - wheel_base_*angular_/2.0 + rear_linear_speed*sin(rear_steering) + wheel_base_*angular_/2.0)/2.0; linear_ = copysign(1.0, rear_linear_speed)*sqrt(pow(linear_x_,2)+pow(linear_y_,2)); /// Compute x, y and heading using velocity const double dt = (time - last_update_timestamp_).toSec(); last_update_timestamp_ = time; /// Integrate odometry: integrateXY(linear_x_*dt, linear_y_*dt, angular_*dt); return true; } void Odometry::updateOpenLoop(double linear, double angular, const ros::Time &time) { /// Save last linear and angular velocity: linear_ = linear; angular_ = angular; /// Integrate odometry: const double dt = (time - timestamp_).toSec(); timestamp_ = time; integrateExact(linear * dt, angular * dt); } void Odometry::setWheelParams(double steering_track, double wheel_steering_y_offset, double wheel_radius, double wheel_base) { steering_track_ = steering_track; wheel_steering_y_offset_ = wheel_steering_y_offset; wheel_radius_ = wheel_radius; wheel_base_ = wheel_base; } void Odometry::setVelocityRollingWindowSize(size_t velocity_rolling_window_size) { velocity_rolling_window_size_ = velocity_rolling_window_size; resetAccumulators(); } void Odometry::integrateXY(double linear_x, double linear_y, double angular) { const double delta_x = linear_x*cos(heading_) - linear_y*sin(heading_); const double delta_y = linear_x*sin(heading_) + linear_y*cos(heading_); x_ += delta_x; y_ += delta_y; heading_ += angular; } void Odometry::integrateRungeKutta2(double linear, double angular) { const double direction = heading_ + angular * 0.5; /// Runge-Kutta 2nd order integration: x_ += linear * cos(direction); y_ += linear * sin(direction); heading_ += angular; } void Odometry::integrateExact(double linear, double angular) { if (fabs(angular) < 1e-6) integrateRungeKutta2(linear, angular); else { /// Exact integration (should solve problems when angular is zero): const double heading_old = heading_; const double r = linear/angular; heading_ += angular; x_ += r * (sin(heading_) - sin(heading_old)); y_ += -r * (cos(heading_) - cos(heading_old)); } } void Odometry::resetAccumulators() { linear_acc_ = RollingMeanAcc(RollingWindow::window_size = velocity_rolling_window_size_); angular_acc_ = RollingMeanAcc(RollingWindow::window_size = velocity_rolling_window_size_); } } // namespace four_wheel_steering_controller <|endoftext|>
<commit_before>#include <net/if.h> #include <boost/scoped_array.hpp> #include "TLV.hh" #include "endian.hh" // Most Significant Bit in the type field indicates the type is optional. #define OPTIONAL_MASK (1 << 7) /** * Makes a deep copy of the given TLV. */ TLV::TLV(const TLV& other) { this->init(other.getType(), other.getLength(), other.getValue()); } /** * Constructs a new TLV object by storing the given shared_array. */ TLV::TLV(uint8_t type, size_t len, boost::shared_array<uint8_t> value) { this->init(type, len, value); } /** * Constructs a new TLV object by copying the value from the given pointer. */ TLV::TLV(uint8_t type, size_t len, const uint8_t* value) { this->init(type, len, value); } TLV::TLV(uint8_t type, size_t len, uint8_t value) { this->init(type, len, reinterpret_cast<uint8_t*>(&value)); } TLV::TLV(uint8_t type, size_t len, uint16_t value) { this->init(type, len, reinterpret_cast<uint8_t*>(&value)); } TLV::TLV(uint8_t type, size_t len, uint32_t value) { this->init(type, len, reinterpret_cast<uint8_t*>(&value)); } TLV::TLV(uint8_t type, size_t len, uint64_t value) { this->init(type, len, reinterpret_cast<uint8_t*>(&value)); } TLV::TLV(uint8_t type, const MACAddress& addr) { boost::shared_array<uint8_t> buf(new uint8_t[IFHWADDRLEN]); addr.toArray(buf.get()); init(type, IFHWADDRLEN, buf); } TLV::TLV(uint8_t type, const IPAddress& addr, const IPAddress& mask) { boost::shared_array<uint8_t> buf; uint8_t *buf_mask = NULL; size_t length; if (addr.getVersion() == IPV6) { length = sizeof(ip6_match); buf.reset(new uint8_t[length]); buf_mask = buf.get() + (length / 2); } else if (addr.getVersion() == IPV4) { length = sizeof(ip_match); buf.reset(new uint8_t[length]); buf_mask = buf.get() + (length / 2); } else { throw "Invalid IP version"; } addr.toArray(buf.get()); mask.toArray(buf_mask); init(type, length, buf); } TLV& TLV::operator=(const TLV& other) { if (this != &other) { this->init(other.getType(), other.getLength(), other.getValue()); } return *this; } bool TLV::operator==(const TLV& other) { return (this->getType() == other.getType() and (memcmp(other.getValue(), this->getValue(), this->length) == 0)); } uint8_t TLV::getType() const { return this->type; } uint8_t TLV::getUint8() const { if (this->getLength() < sizeof(uint8_t)) { return 0; } return *reinterpret_cast<const uint8_t*>(this->getValue()); } uint16_t TLV::getUint16() const { if (this->getLength() < sizeof(uint16_t)) { return 0; } return *reinterpret_cast<const uint16_t*>(this->getValue()); } uint32_t TLV::getUint32() const { if (this->getLength() < sizeof(uint32_t)) { return 0; } return *reinterpret_cast<const uint32_t*>(this->getValue()); } uint64_t TLV::getUint64() const { if (this->getLength() < sizeof(uint64_t)) { return 0; } return *reinterpret_cast<const uint64_t*>(this->getValue()); } size_t TLV::getLength() const { return this->length; } const uint8_t* TLV::getValue() const { return this->value.get(); } /** * Returns the IP address held internally, in network byte-order. */ const void* TLV::getIPAddress() const { return this->getValue(); } /** * Returns the IP mask held internally, in network byte-order. */ const void* TLV::getIPMask() const { if (this->length == sizeof(ip_match)) { return &reinterpret_cast<const ip_match*>(this->getValue())->mask; } else if (this->length == sizeof(ip6_match)) { return &reinterpret_cast<const ip6_match*>(this->getValue())->mask; } return NULL; } mongo::BSONObj TLV::to_BSON() const { return TLV_to_BSON(this, ORDER_HOST); } /** * Serialises the TLV object to BSON in the following format: * { * "type": (int), * "value": (binary) * } * * Where "value" is converted from "byte_order" to network byte-order. */ mongo::BSONObj TLV::TLV_to_BSON(const TLV* tlv, byte_order order) { const uint8_t* value = tlv->getValue(); boost::scoped_array<uint8_t> arr(new uint8_t[tlv->length]); if (order == ORDER_HOST) { switch (tlv->length) { case sizeof(uint16_t): { uint16_t new_val = htons(tlv->getUint16()); memcpy(arr.get(), &new_val, tlv->length); value = arr.get(); break; } case sizeof(uint32_t): { uint32_t new_val = htonl(tlv->getUint32()); memcpy(arr.get(), &new_val, tlv->length); value = arr.get(); break; } case sizeof(uint64_t): { uint64_t new_val = htonll(tlv->getUint64()); memcpy(arr.get(), &new_val, tlv->length); value = arr.get(); break; } default: break; } } mongo::BSONObjBuilder builder; builder.append("type", tlv->type); builder.appendBinData("value", tlv->length, mongo::BinDataGeneral, value); return builder.obj(); } uint8_t TLV::type_from_BSON(mongo::BSONObj bson) { const mongo::BSONElement& btype = bson["type"]; if (btype.type() != mongo::NumberInt) return 0; return static_cast<uint8_t>(btype.Int()); } boost::shared_array<uint8_t> TLV::value_from_BSON(mongo::BSONObj bson, byte_order order) { boost::shared_array<uint8_t> arr(NULL); const mongo::BSONElement& bvalue = bson["value"]; if (bvalue.type() != mongo::BinData) return arr; int len = bvalue.valuesize(); const uint8_t* value = reinterpret_cast<const uint8_t*> (bvalue.binData(len)); arr.reset(new uint8_t[len]); if (order == ORDER_HOST) { switch (len) { case sizeof(uint16_t): { uint16_t new_val = ntohs(*reinterpret_cast<const uint16_t*> (value)); memcpy(arr.get(), &new_val, len); break; } case sizeof(uint32_t): { uint32_t new_val = ntohl(*reinterpret_cast<const uint32_t*> (value)); memcpy(arr.get(), &new_val, len); break; } case sizeof(uint64_t): { uint64_t new_val = ntohll(*reinterpret_cast<const uint64_t*> (value)); memcpy(arr.get(), &new_val, len); break; } default: memcpy(arr.get(), value, len); break; } } else { memcpy(arr.get(), value, len); } return arr; } std::string TLV::toString() const { boost::scoped_array<char> buf(new char[this->length]); snprintf(buf.get(), this->length, "%*s", static_cast<int>(this->length), this->value.get()); std::stringstream ss; ss << "{\"type\": " << this->type_to_string() << ", \"value\":\""; ss.write(buf.get(), this->length); ss << "\"}"; return ss.str(); } std::string TLV::type_to_string() const { std::stringstream ss; ss << this->type; return ss.str(); } bool TLV::optional() const { if (this->type & OPTIONAL_MASK) { return true; } return false; } void TLV::init(uint8_t type, size_t len, const uint8_t* value) { boost::shared_array<uint8_t> arr(new uint8_t[len]); memcpy(arr.get(), value, len); this->init(type, len, arr); } void TLV::init(uint8_t type, size_t len, boost::shared_array<uint8_t> value) { this->type = type; this->length = 0; if (len == 0 || value.get() == NULL) { return; } this->value = value; this->length = len; } <commit_msg>rflib: TLV: fix shared_array constructor invokation<commit_after>#include <net/if.h> #include <boost/scoped_array.hpp> #include "TLV.hh" #include "endian.hh" // Most Significant Bit in the type field indicates the type is optional. #define OPTIONAL_MASK (1 << 7) /** * Makes a deep copy of the given TLV. */ TLV::TLV(const TLV& other) { this->init(other.getType(), other.getLength(), other.getValue()); } /** * Constructs a new TLV object by storing the given shared_array. */ TLV::TLV(uint8_t type, size_t len, boost::shared_array<uint8_t> value) { this->init(type, len, value); } /** * Constructs a new TLV object by copying the value from the given pointer. */ TLV::TLV(uint8_t type, size_t len, const uint8_t* value) { this->init(type, len, value); } TLV::TLV(uint8_t type, size_t len, uint8_t value) { this->init(type, len, reinterpret_cast<uint8_t*>(&value)); } TLV::TLV(uint8_t type, size_t len, uint16_t value) { this->init(type, len, reinterpret_cast<uint8_t*>(&value)); } TLV::TLV(uint8_t type, size_t len, uint32_t value) { this->init(type, len, reinterpret_cast<uint8_t*>(&value)); } TLV::TLV(uint8_t type, size_t len, uint64_t value) { this->init(type, len, reinterpret_cast<uint8_t*>(&value)); } TLV::TLV(uint8_t type, const MACAddress& addr) { boost::shared_array<uint8_t> buf(new uint8_t[IFHWADDRLEN]); addr.toArray(buf.get()); init(type, IFHWADDRLEN, buf); } TLV::TLV(uint8_t type, const IPAddress& addr, const IPAddress& mask) { boost::shared_array<uint8_t> buf; uint8_t *buf_mask = NULL; size_t length; if (addr.getVersion() == IPV6) { length = sizeof(ip6_match); buf.reset(new uint8_t[length]); buf_mask = buf.get() + (length / 2); } else if (addr.getVersion() == IPV4) { length = sizeof(ip_match); buf.reset(new uint8_t[length]); buf_mask = buf.get() + (length / 2); } else { throw "Invalid IP version"; } addr.toArray(buf.get()); mask.toArray(buf_mask); init(type, length, buf); } TLV& TLV::operator=(const TLV& other) { if (this != &other) { this->init(other.getType(), other.getLength(), other.getValue()); } return *this; } bool TLV::operator==(const TLV& other) { return (this->getType() == other.getType() and (memcmp(other.getValue(), this->getValue(), this->length) == 0)); } uint8_t TLV::getType() const { return this->type; } uint8_t TLV::getUint8() const { if (this->getLength() < sizeof(uint8_t)) { return 0; } return *reinterpret_cast<const uint8_t*>(this->getValue()); } uint16_t TLV::getUint16() const { if (this->getLength() < sizeof(uint16_t)) { return 0; } return *reinterpret_cast<const uint16_t*>(this->getValue()); } uint32_t TLV::getUint32() const { if (this->getLength() < sizeof(uint32_t)) { return 0; } return *reinterpret_cast<const uint32_t*>(this->getValue()); } uint64_t TLV::getUint64() const { if (this->getLength() < sizeof(uint64_t)) { return 0; } return *reinterpret_cast<const uint64_t*>(this->getValue()); } size_t TLV::getLength() const { return this->length; } const uint8_t* TLV::getValue() const { return this->value.get(); } /** * Returns the IP address held internally, in network byte-order. */ const void* TLV::getIPAddress() const { return this->getValue(); } /** * Returns the IP mask held internally, in network byte-order. */ const void* TLV::getIPMask() const { if (this->length == sizeof(ip_match)) { return &reinterpret_cast<const ip_match*>(this->getValue())->mask; } else if (this->length == sizeof(ip6_match)) { return &reinterpret_cast<const ip6_match*>(this->getValue())->mask; } return NULL; } mongo::BSONObj TLV::to_BSON() const { return TLV_to_BSON(this, ORDER_HOST); } /** * Serialises the TLV object to BSON in the following format: * { * "type": (int), * "value": (binary) * } * * Where "value" is converted from "byte_order" to network byte-order. */ mongo::BSONObj TLV::TLV_to_BSON(const TLV* tlv, byte_order order) { const uint8_t* value = tlv->getValue(); boost::scoped_array<uint8_t> arr(new uint8_t[tlv->length]); if (order == ORDER_HOST) { switch (tlv->length) { case sizeof(uint16_t): { uint16_t new_val = htons(tlv->getUint16()); memcpy(arr.get(), &new_val, tlv->length); value = arr.get(); break; } case sizeof(uint32_t): { uint32_t new_val = htonl(tlv->getUint32()); memcpy(arr.get(), &new_val, tlv->length); value = arr.get(); break; } case sizeof(uint64_t): { uint64_t new_val = htonll(tlv->getUint64()); memcpy(arr.get(), &new_val, tlv->length); value = arr.get(); break; } default: break; } } mongo::BSONObjBuilder builder; builder.append("type", tlv->type); builder.appendBinData("value", tlv->length, mongo::BinDataGeneral, value); return builder.obj(); } uint8_t TLV::type_from_BSON(mongo::BSONObj bson) { const mongo::BSONElement& btype = bson["type"]; if (btype.type() != mongo::NumberInt) return 0; return static_cast<uint8_t>(btype.Int()); } boost::shared_array<uint8_t> TLV::value_from_BSON(mongo::BSONObj bson, byte_order order) { boost::shared_array<uint8_t> arr; const mongo::BSONElement& bvalue = bson["value"]; if (bvalue.type() != mongo::BinData) return arr; int len = bvalue.valuesize(); const uint8_t* value = reinterpret_cast<const uint8_t*> (bvalue.binData(len)); arr.reset(new uint8_t[len]); if (order == ORDER_HOST) { switch (len) { case sizeof(uint16_t): { uint16_t new_val = ntohs(*reinterpret_cast<const uint16_t*> (value)); memcpy(arr.get(), &new_val, len); break; } case sizeof(uint32_t): { uint32_t new_val = ntohl(*reinterpret_cast<const uint32_t*> (value)); memcpy(arr.get(), &new_val, len); break; } case sizeof(uint64_t): { uint64_t new_val = ntohll(*reinterpret_cast<const uint64_t*> (value)); memcpy(arr.get(), &new_val, len); break; } default: memcpy(arr.get(), value, len); break; } } else { memcpy(arr.get(), value, len); } return arr; } std::string TLV::toString() const { boost::scoped_array<char> buf(new char[this->length]); snprintf(buf.get(), this->length, "%*s", static_cast<int>(this->length), this->value.get()); std::stringstream ss; ss << "{\"type\": " << this->type_to_string() << ", \"value\":\""; ss.write(buf.get(), this->length); ss << "\"}"; return ss.str(); } std::string TLV::type_to_string() const { std::stringstream ss; ss << this->type; return ss.str(); } bool TLV::optional() const { if (this->type & OPTIONAL_MASK) { return true; } return false; } void TLV::init(uint8_t type, size_t len, const uint8_t* value) { boost::shared_array<uint8_t> arr(new uint8_t[len]); memcpy(arr.get(), value, len); this->init(type, len, arr); } void TLV::init(uint8_t type, size_t len, boost::shared_array<uint8_t> value) { this->type = type; this->length = 0; if (len == 0 || value.get() == NULL) { return; } this->value = value; this->length = len; } <|endoftext|>
<commit_before>// // configview.cpp // // Description: View for configuring the set of targets to be used with the debugger // // // Copyright (c) 2010 Kåre Särs <kare.sars@iki.fi> // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Library General Public // License version 2 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 // Library General Public License for more details. // // You should have received a copy of the GNU Library General Public License // along with this library; see the file COPYING.LIB. If not, write to // the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, // Boston, MA 02110-1301, USA. #include "ioview.h" #include <QVBoxLayout> #include <QFile> #include <QTextEdit> #include <QLineEdit> #include <QScrollBar> #include <QSocketNotifier> #include <QString> #include <QFontDatabase> #include <kcolorscheme.h> #include <krandom.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> IOView::IOView(QWidget *parent) : QWidget(parent) { m_output = new QTextEdit(); m_output->setReadOnly(true); m_output->setUndoRedoEnabled(false); m_output->setAcceptRichText(false); // fixed wide font, like konsole m_output->setFont(QFontDatabase::systemFont(QFontDatabase::FixedFont)); // alternate color scheme, like konsole KColorScheme schemeView(QPalette::Active, KColorScheme::View); m_output->setTextBackgroundColor(schemeView.foreground().color()); m_output->setTextColor(schemeView.background().color()); QPalette p = m_output->palette (); p.setColor(QPalette::Base, schemeView.foreground().color()); m_output->setPalette(p); m_input = new QLineEdit(); m_output->setFocusProxy(m_input); // take the focus from the output QVBoxLayout *layout = new QVBoxLayout(this); layout->addWidget(m_output, 10); layout->addWidget(m_input, 0); layout->setContentsMargins(0,0,0,0); layout->setSpacing(0); connect(m_input, SIGNAL(returnPressed()), this, SLOT(returnPressed())); createFifos(); } IOView::~IOView() { m_stdin.close(); m_stdout.close(); m_stdout.setFileName(m_stdoutFifo); ::close(m_stdoutFD); m_stderr.close(); m_stderr.setFileName(m_stderrFifo); ::close(m_stderrFD); m_stdin.remove(); m_stdout.remove(); m_stderr.remove(); } void IOView::createFifos() { m_stdinFifo = createFifo(QStringLiteral("stdInFifo")); m_stdoutFifo = createFifo(QStringLiteral("stdOutFifo")); m_stderrFifo = createFifo(QStringLiteral("stdErrFifo")); m_stdin.setFileName(m_stdinFifo); if (!m_stdin.open(QIODevice::ReadWrite)) return; m_stdoutD.setFileName(m_stdoutFifo); m_stdoutD.open(QIODevice::ReadWrite); m_stdout.setFileName(m_stdoutFifo); m_stdoutFD = ::open(m_stdoutFifo.toLocal8Bit().data(), O_RDWR|O_NONBLOCK); if (m_stdoutFD == -1) return; if (!m_stdout.open(m_stdoutFD, QIODevice::ReadWrite)) return; m_stdoutNotifier = new QSocketNotifier(m_stdoutFD, QSocketNotifier::Read, this); connect(m_stdoutNotifier, SIGNAL(activated(int)), this, SLOT(readOutput())); m_stdoutNotifier->setEnabled(true); m_stderrD.setFileName(m_stderrFifo); m_stderrD.open(QIODevice::ReadWrite); m_stderr.setFileName(m_stderrFifo); m_stderrFD = ::open(m_stderrFifo.toLocal8Bit().data(), O_RDONLY|O_NONBLOCK); if (m_stderrFD == -1) return; if (!m_stderr.open(m_stderrFD, QIODevice::ReadOnly)) return; m_stderrNotifier = new QSocketNotifier(m_stderrFD, QSocketNotifier::Read, this); connect(m_stderrNotifier, SIGNAL(activated(int)), this, SLOT(readErrors())); m_stderrNotifier->setEnabled(true); return; } void IOView::returnPressed() { m_stdin.write(m_input->text().toLocal8Bit()); m_stdin.write("\n"); m_stdin.flush(); m_input->clear(); } void IOView::readOutput() { m_stdoutNotifier->setEnabled(false); qint64 res; char chData[256]; QByteArray data; do { res = m_stdout.read(chData, 255); if (res <= 0) { m_stdoutD.flush(); } else { data.append(chData, res); } } while (res == 255); if (data.size() > 0) { emit stdOutText(QString::fromLocal8Bit(data)); } m_stdoutNotifier->setEnabled(true); } void IOView::readErrors() { m_stderrNotifier->setEnabled(false); qint64 res; char chData[256]; QByteArray data; do { res = m_stderr.read(chData, 255); if (res <= 0) { m_stderrD.flush(); } else { data.append(chData, res); } } while (res == 255); if (data.size() > 0) { emit stdErrText(QString::fromLocal8Bit(data)); } m_stderrNotifier->setEnabled(true); } void IOView::addStdOutText(const QString &text) { QScrollBar *scrollb = m_output->verticalScrollBar(); if (!scrollb) return; bool atEnd = (scrollb->value() == scrollb->maximum()); QTextCursor cursor = m_output->textCursor(); if (!cursor.atEnd()) cursor.movePosition(QTextCursor::End); cursor.insertText(text); if (atEnd) { scrollb->setValue(scrollb->maximum()); } } void IOView::addStdErrText(const QString &text) { m_output->setFontItalic(true); addStdOutText(text); m_output->setFontItalic(false); } QString IOView::createFifo(const QString &prefix) { QString fifo = QStandardPaths::writableLocation(QStandardPaths::RuntimeLocation) + prefix + KRandom::randomString(3); int result = mkfifo(QFile::encodeName(fifo).data(), 0666); if (result != 0) return QString(); return fifo; } const QString IOView::stdinFifo() { return m_stdinFifo; } const QString IOView::stdoutFifo() { return m_stdoutFifo; } const QString IOView::stderrFifo() { return m_stderrFifo; } void IOView::enableInput(bool enable) { m_input->setEnabled(enable); } void IOView::clearOutput() { m_output->clear(); } <commit_msg>GDB: Fix fifo creation<commit_after>// // configview.cpp // // Description: View for configuring the set of targets to be used with the debugger // // // Copyright (c) 2010 Kåre Särs <kare.sars@iki.fi> // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Library General Public // License version 2 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 // Library General Public License for more details. // // You should have received a copy of the GNU Library General Public License // along with this library; see the file COPYING.LIB. If not, write to // the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, // Boston, MA 02110-1301, USA. #include "ioview.h" #include <QVBoxLayout> #include <QFile> #include <QDir> #include <QTextEdit> #include <QLineEdit> #include <QScrollBar> #include <QSocketNotifier> #include <QString> #include <QFontDatabase> #include <kcolorscheme.h> #include <krandom.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> IOView::IOView(QWidget *parent) : QWidget(parent) { m_output = new QTextEdit(); m_output->setReadOnly(true); m_output->setUndoRedoEnabled(false); m_output->setAcceptRichText(false); // fixed wide font, like konsole m_output->setFont(QFontDatabase::systemFont(QFontDatabase::FixedFont)); // alternate color scheme, like konsole KColorScheme schemeView(QPalette::Active, KColorScheme::View); m_output->setTextBackgroundColor(schemeView.foreground().color()); m_output->setTextColor(schemeView.background().color()); QPalette p = m_output->palette (); p.setColor(QPalette::Base, schemeView.foreground().color()); m_output->setPalette(p); m_input = new QLineEdit(); m_output->setFocusProxy(m_input); // take the focus from the output QVBoxLayout *layout = new QVBoxLayout(this); layout->addWidget(m_output, 10); layout->addWidget(m_input, 0); layout->setContentsMargins(0,0,0,0); layout->setSpacing(0); connect(m_input, SIGNAL(returnPressed()), this, SLOT(returnPressed())); createFifos(); } IOView::~IOView() { m_stdin.close(); m_stdout.close(); m_stdout.setFileName(m_stdoutFifo); ::close(m_stdoutFD); m_stderr.close(); m_stderr.setFileName(m_stderrFifo); ::close(m_stderrFD); m_stdin.remove(); m_stdout.remove(); m_stderr.remove(); } void IOView::createFifos() { m_stdinFifo = createFifo(QStringLiteral("stdInFifo")); m_stdoutFifo = createFifo(QStringLiteral("stdOutFifo")); m_stderrFifo = createFifo(QStringLiteral("stdErrFifo")); m_stdin.setFileName(m_stdinFifo); if (!m_stdin.open(QIODevice::ReadWrite)) return; m_stdoutD.setFileName(m_stdoutFifo); m_stdoutD.open(QIODevice::ReadWrite); m_stdout.setFileName(m_stdoutFifo); m_stdoutFD = ::open(m_stdoutFifo.toLocal8Bit().data(), O_RDWR|O_NONBLOCK); if (m_stdoutFD == -1) return; if (!m_stdout.open(m_stdoutFD, QIODevice::ReadWrite)) return; m_stdoutNotifier = new QSocketNotifier(m_stdoutFD, QSocketNotifier::Read, this); connect(m_stdoutNotifier, SIGNAL(activated(int)), this, SLOT(readOutput())); m_stdoutNotifier->setEnabled(true); m_stderrD.setFileName(m_stderrFifo); m_stderrD.open(QIODevice::ReadWrite); m_stderr.setFileName(m_stderrFifo); m_stderrFD = ::open(m_stderrFifo.toLocal8Bit().data(), O_RDONLY|O_NONBLOCK); if (m_stderrFD == -1) return; if (!m_stderr.open(m_stderrFD, QIODevice::ReadOnly)) return; m_stderrNotifier = new QSocketNotifier(m_stderrFD, QSocketNotifier::Read, this); connect(m_stderrNotifier, SIGNAL(activated(int)), this, SLOT(readErrors())); m_stderrNotifier->setEnabled(true); return; } void IOView::returnPressed() { m_stdin.write(m_input->text().toLocal8Bit()); m_stdin.write("\n"); m_stdin.flush(); m_input->clear(); } void IOView::readOutput() { m_stdoutNotifier->setEnabled(false); qint64 res; char chData[256]; QByteArray data; do { res = m_stdout.read(chData, 255); if (res <= 0) { m_stdoutD.flush(); } else { data.append(chData, res); } } while (res == 255); if (data.size() > 0) { emit stdOutText(QString::fromLocal8Bit(data)); } m_stdoutNotifier->setEnabled(true); } void IOView::readErrors() { m_stderrNotifier->setEnabled(false); qint64 res; char chData[256]; QByteArray data; do { res = m_stderr.read(chData, 255); if (res <= 0) { m_stderrD.flush(); } else { data.append(chData, res); } } while (res == 255); if (data.size() > 0) { emit stdErrText(QString::fromLocal8Bit(data)); } m_stderrNotifier->setEnabled(true); } void IOView::addStdOutText(const QString &text) { QScrollBar *scrollb = m_output->verticalScrollBar(); if (!scrollb) return; bool atEnd = (scrollb->value() == scrollb->maximum()); QTextCursor cursor = m_output->textCursor(); if (!cursor.atEnd()) cursor.movePosition(QTextCursor::End); cursor.insertText(text); if (atEnd) { scrollb->setValue(scrollb->maximum()); } } void IOView::addStdErrText(const QString &text) { m_output->setFontItalic(true); addStdOutText(text); m_output->setFontItalic(false); } QString IOView::createFifo(const QString &prefix) { QString fifo = QStandardPaths::writableLocation(QStandardPaths::TempLocation) + QDir::separator() + prefix + KRandom::randomString(3); int result = mkfifo(QFile::encodeName(fifo).data(), 0666); if (result != 0) return QString(); return fifo; } const QString IOView::stdinFifo() { return m_stdinFifo; } const QString IOView::stdoutFifo() { return m_stdoutFifo; } const QString IOView::stderrFifo() { return m_stderrFifo; } void IOView::enableInput(bool enable) { m_input->setEnabled(enable); } void IOView::clearOutput() { m_output->clear(); } <|endoftext|>
<commit_before>/****************************************************************/ /* DO NOT MODIFY THIS HEADER */ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* (c) 2010 Battelle Energy Alliance, LLC */ /* ALL RIGHTS RESERVED */ /* */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ /* */ /* See COPYRIGHT for full restrictions */ /****************************************************************/ #include "SetupOverSamplingAction.h" #include "Moose.h" #include "Parser.h" #include "Executioner.h" #include "Output.h" #include "MProblem.h" #include "OutputProblem.h" #include "exodusII_io.h" #include "MooseMesh.h" template<> InputParameters validParams<SetupOverSamplingAction>() { // Note: I am specifically "skipping" the direct parent here because we want a subset of parameters // in this block for now. We may make a common ancestor at some point to clean this up InputParameters params = validParams<Action>(); params.addParam<std::string>("file_base", "out_oversample", "The desired solution output name without an extension"); params.addParam<unsigned int>("refinements", 1, "The number of refinements to output for the over sampled solution"); params.addParam<bool>("exodus", false, "Specifies that you would like Exodus output solution file(s)"); params.addParam<bool>("nemesis", false, "Specifies that you would like Nemesis output solution file(s)"); params.addParam<bool>("gmv", false, "Specifies that you would like GMV output solution file(s)"); params.addParam<bool>("tecplot", false, "Specifies that you would like Tecplot output solution files(s)"); params.addParam<bool>("tecplot_binary", false, "Specifies that you would like Tecplot binary output solution files(s)"); params.addParam<bool>("xda", false, "Specifies that you would like xda output solution files(s)"); params.addParam<std::vector<std::string> >("output_variables", "A list of the variables that should be in the Exodus output file. If this is not provided then all variables will be in the output."); params.addParam<int>("interval", 1, "The iterval at which timesteps are output to the solution file"); params.addParam<Real>("iteration_plot_start_time", std::numeric_limits<Real>::max(), "Specifies a time after which the solution will be written following each nonlinear iteration"); params.addParam<bool>("output_initial", false, "Requests that the initial condition is output to the solution file"); return params; } SetupOverSamplingAction::SetupOverSamplingAction(const std::string & name, InputParameters params) : SetupOutputAction(name, params) { } void SetupOverSamplingAction::act() { Executioner * exec = _parser_handle._executioner; MProblem * problem = dynamic_cast<MProblem *>(&exec->problem()); if (!problem) mooseError("Can't get a handle to Mproblem"); OutputProblem & out_problem = problem->getOutputProblem(getParam<unsigned int>("refinements")); Output & output = out_problem.out(); // can't use use this with coupled problems on different meshes if(!_pars.isParamValid("output_variables") && _parser_handle._problem != NULL) { MProblem & mproblem = *_parser_handle._problem; _pars.set<std::vector<std::string> >("output_variables") = mproblem.getVariableNames(); } setupOutputObject(output, _pars); out_problem.outputInitial(getParam<bool>("output_initial")); if (_parser_handle._problem != NULL) { // TODO: handle this thru Problem interface MProblem & mproblem = *_parser_handle._problem; #ifdef LIBMESH_ENABLE_AMR Adaptivity & adapt = mproblem.adaptivity(); if (adapt.isOn()) output.sequence(true); #endif //LIBMESH_ENABLE_AMR // TODO: Need to set these values on the OutputProblem output.interval(getParam<int>("interval")); output.iterationPlotStartTime(getParam<Real>("iteration_plot_start_time")); } // Test to make sure that the user can write to the directory specified in file_base std::string base = "./" + getParam<std::string>("file_base"); base = base.substr(0, base.find_last_of('/')); if (access(base.c_str(), W_OK) == -1) mooseError("Can not write to directory: " + base + " for file base: " + getParam<std::string>("file_base")); } <commit_msg>Closing ticket #638<commit_after>/****************************************************************/ /* DO NOT MODIFY THIS HEADER */ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* (c) 2010 Battelle Energy Alliance, LLC */ /* ALL RIGHTS RESERVED */ /* */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ /* */ /* See COPYRIGHT for full restrictions */ /****************************************************************/ #include "SetupOverSamplingAction.h" #include "Moose.h" #include "Parser.h" #include "Executioner.h" #include "Output.h" #include "MProblem.h" #include "OutputProblem.h" #include "exodusII_io.h" #include "MooseMesh.h" template<> InputParameters validParams<SetupOverSamplingAction>() { // Note: I am specifically "skipping" the direct parent here because we want a subset of parameters // in this block for now. We may make a common ancestor at some point to clean this up InputParameters params = validParams<Action>(); params.addParam<std::string>("file_base", "The desired oversampled solution output name without an extension. If not supplied, the main file_base will be used with a '_oversample' suffix added."); params.addParam<unsigned int>("refinements", 1, "The number of refinements to output for the over sampled solution"); params.addParam<bool>("exodus", false, "Specifies that you would like Exodus output solution file(s)"); params.addParam<bool>("nemesis", false, "Specifies that you would like Nemesis output solution file(s)"); params.addParam<bool>("gmv", false, "Specifies that you would like GMV output solution file(s)"); params.addParam<bool>("tecplot", false, "Specifies that you would like Tecplot output solution files(s)"); params.addParam<bool>("tecplot_binary", false, "Specifies that you would like Tecplot binary output solution files(s)"); params.addParam<bool>("xda", false, "Specifies that you would like xda output solution files(s)"); params.addParam<std::vector<std::string> >("output_variables", "A list of the variables that should be in the Exodus output file. If this is not provided then all variables will be in the output."); params.addParam<int>("interval", 1, "The iterval at which timesteps are output to the solution file"); params.addParam<Real>("iteration_plot_start_time", std::numeric_limits<Real>::max(), "Specifies a time after which the solution will be written following each nonlinear iteration"); params.addParam<bool>("output_initial", false, "Requests that the initial condition is output to the solution file"); return params; } SetupOverSamplingAction::SetupOverSamplingAction(const std::string & name, InputParameters params) : SetupOutputAction(name, params) { } void SetupOverSamplingAction::act() { Executioner * exec = _parser_handle._executioner; MProblem * problem = dynamic_cast<MProblem *>(&exec->problem()); if (!problem) mooseError("Can't get a handle to Mproblem"); OutputProblem & out_problem = problem->getOutputProblem(getParam<unsigned int>("refinements")); Output & output = out_problem.out(); // can't use use this with coupled problems on different meshes if(!_pars.isParamValid("output_variables") && _parser_handle._problem != NULL) { MProblem & mproblem = *_parser_handle._problem; _pars.set<std::vector<std::string> >("output_variables") = mproblem.getVariableNames(); } // If no filebase was supplied in the parameters object - borrow the main problem's filebase if (!_pars.isParamValid("file_base")) _pars.set<std::string>("file_base") = problem->out().fileBase() + "_oversample"; setupOutputObject(output, _pars); out_problem.outputInitial(getParam<bool>("output_initial")); if (_parser_handle._problem != NULL) { // TODO: handle this thru Problem interface MProblem & mproblem = *_parser_handle._problem; #ifdef LIBMESH_ENABLE_AMR Adaptivity & adapt = mproblem.adaptivity(); if (adapt.isOn()) output.sequence(true); #endif //LIBMESH_ENABLE_AMR // TODO: Need to set these values on the OutputProblem output.interval(getParam<int>("interval")); output.iterationPlotStartTime(getParam<Real>("iteration_plot_start_time")); } // Test to make sure that the user can write to the directory specified in file_base std::string base = "./" + getParam<std::string>("file_base"); base = base.substr(0, base.find_last_of('/')); if (access(base.c_str(), W_OK) == -1) mooseError("Can not write to directory: " + base + " for file base: " + getParam<std::string>("file_base")); } <|endoftext|>
<commit_before> ////using the C++ API #include "zorba_api.h" #include "store/naive/basic_item_factory.h" #include "store/naive/simple_store.h" //for debug #include "compiler/parser/xquery_driver.h" #include "util/logging/loggermanager.hh" #include "timer.h" #include "error_display.h" #include <fstream> #include <iostream> #include <iomanip> using namespace xqp; #ifdef _DEBUG extern const char* xqp::g_error_in_file; extern int xqp::g_error_at_line; #endif //typedef int alert_callback(Zorba_AlertMessage *alert_mess, // XQuery_t current_xquery, // XQueryResult_t current_xqueryresult, // void *param); //define one callback function for receiving the xquery alerts int apitest_alert_callback(Zorba_AlertMessage *alert_mess, XQuery_t current_xquery, XQueryResult_t current_xqueryresult, void *param) { if((alert_mess->alert_type != Zorba_AlertMessage::USER_ERROR_ALERT) && (alert_mess->alert_type != Zorba_AlertMessage::USER_TRACE_ALERT)) { cerr << g_error_in_file << " : " << g_error_at_line << endl; } cerr << "(param " << std::hex << param << " )" << endl; DisplayOneAlert(alert_mess); return -1; } #ifndef _WIN32_WCE int main(int argc, char* argv[]) #else int _tmain(int argc, _TCHAR* argv[]) #endif { Timer timer; timer.start(); xqp::LoggerManager::logmanager()->setLoggerConfig("#1#logging.log"); bool useResultFile = false, inline_query = false; bool useSerializer = false; std::string resultFileName; std::ofstream* resultFile = NULL; std::string query_text = "1+1";///the default query if no file or query is specified ///pick up all the runtime options #ifdef UNICODE #define TEST_ARGV_FLAG( str ) (_tcscmp(*argv, _T(str)) == 0) #else #define TEST_ARGV_FLAG( str ) (*argv == std::string (str)) #endif for (++argv; argv[0]; ++argv) { const char *fname; if (TEST_ARGV_FLAG ("-p")) { g_trace_parsing = true; } else if (TEST_ARGV_FLAG ("-s")) { g_trace_scanning = true; } else if (TEST_ARGV_FLAG ("-r")) { useSerializer = true; } else if (TEST_ARGV_FLAG ("-o")) { useResultFile = true; resultFileName = *++argv; } else if (TEST_ARGV_FLAG ("-e")) { inline_query = true; } else { fname = *argv; #ifndef UNICODE if (inline_query) { // fname = "zorba_query.tmp"; // ofstream qf (fname); // qf << *argv; query_text = *argv; } #endif #ifdef UNICODE if(! inline_query) { char testfile[1024]; WideCharToMultiByte(CP_ACP, 0, // or CP_UTF8 *argv, -1, testfile, sizeof(testfile)/sizeof(char), NULL, NULL); fname = testfile; } #endif if(!inline_query) { // read the file std::ifstream qfile(fname); if(!qfile.is_open()) { // couldn't open file, display error and exit cerr << "Error opening xquery file <" << fname << ">" << endl; return -1; } string temp; query_text = ""; // warning: this method of reading a file might trim the // whitespace at the end of lines while (getline(qfile, temp)) { if (query_text != "") query_text += "\n"; query_text += temp; } } } } ///now start the zorba engine ZorbaFactory& zorba_factory = ZorbaFactory::getInstance(); ///thread specific zorba_factory.InitThread(); ///register the alerts callback Zorba_AlertsManager& errmanager = zorba_factory.getAlertsManagerForCurrentThread(); errmanager.RegisterAlertCallback(apitest_alert_callback, (void*)101); XQuery_t query; XQueryResult_t result = NULL; Item_t it; //create a compiled query query = zorba_factory.createQuery(query_text.c_str()); // if(!query->compile()) // { // goto DisplayErrorsAndExit; // } if(!query.get_ptr()) { goto DisplayErrorsAndExit; } result = query->execute(); if(!result.get_ptr()) { goto DisplayErrorsAndExit; } result->setAlertsParam(result.get_ptr());///to be passed to alerts callback when error occurs if (useResultFile) { resultFile = new ofstream(resultFileName.c_str()); //*resultFile << "Iterator run:" << std::endl << std::endl; } if (useSerializer) { // *resultFile << i_p->show() << endl; // serializer* ser = new serializer(); // ser->serialize(result, *resultFile); result->serializeXML(*resultFile); // endl should not be sent when serializing! // *resultFile << endl; } else { while( true ) { it = result->next(); if(it == NULL) break; if (resultFile != NULL) *resultFile << it->show() << endl; else cout << it->show() << endl; } } if(result->isError()) { goto DisplayErrorsAndExit; } //delete result; //delete query; // zorba_factory.destroyQuery(query); zorba_factory.UninitThread(); ZorbaFactory::shutdownZorbaEngine(); timer.end(); //if (resultFile != NULL) //{ // *resultFile << std::endl; // timer.print(*resultFile); //} //else timer.print(cout); resultFile->close(); delete resultFile; return 0; DisplayErrorsAndExit: cerr << endl << "Display all error list now:" << endl; DisplayErrorListForCurrentThread(); zorba_factory.UninitThread(); ZorbaFactory::shutdownZorbaEngine(); timer.end(); timer.print(cout); return -1; } <commit_msg>Fixed null pointer error in apitest.<commit_after> ////using the C++ API #include "zorba_api.h" #include "store/naive/basic_item_factory.h" #include "store/naive/simple_store.h" //for debug #include "compiler/parser/xquery_driver.h" #include "util/logging/loggermanager.hh" #include "timer.h" #include "error_display.h" #include <fstream> #include <iostream> #include <iomanip> using namespace xqp; #ifdef _DEBUG extern const char* xqp::g_error_in_file; extern int xqp::g_error_at_line; #endif //typedef int alert_callback(Zorba_AlertMessage *alert_mess, // XQuery_t current_xquery, // XQueryResult_t current_xqueryresult, // void *param); //define one callback function for receiving the xquery alerts int apitest_alert_callback(Zorba_AlertMessage *alert_mess, XQuery_t current_xquery, XQueryResult_t current_xqueryresult, void *param) { if((alert_mess->alert_type != Zorba_AlertMessage::USER_ERROR_ALERT) && (alert_mess->alert_type != Zorba_AlertMessage::USER_TRACE_ALERT)) { cerr << g_error_in_file << " : " << g_error_at_line << endl; } cerr << "(param " << std::hex << param << " )" << endl; DisplayOneAlert(alert_mess); return -1; } #ifndef _WIN32_WCE int main(int argc, char* argv[]) #else int _tmain(int argc, _TCHAR* argv[]) #endif { Timer timer; timer.start(); xqp::LoggerManager::logmanager()->setLoggerConfig("#1#logging.log"); bool useResultFile = false, inline_query = false; bool useSerializer = false; std::string resultFileName; std::ofstream* resultFile = NULL; std::string query_text = "1+1";///the default query if no file or query is specified ///pick up all the runtime options #ifdef UNICODE #define TEST_ARGV_FLAG( str ) (_tcscmp(*argv, _T(str)) == 0) #else #define TEST_ARGV_FLAG( str ) (*argv == std::string (str)) #endif for (++argv; argv[0]; ++argv) { const char *fname; if (TEST_ARGV_FLAG ("-p")) { g_trace_parsing = true; } else if (TEST_ARGV_FLAG ("-s")) { g_trace_scanning = true; } else if (TEST_ARGV_FLAG ("-r")) { useSerializer = true; } else if (TEST_ARGV_FLAG ("-o")) { useResultFile = true; resultFileName = *++argv; } else if (TEST_ARGV_FLAG ("-e")) { inline_query = true; } else { fname = *argv; #ifndef UNICODE if (inline_query) { // fname = "zorba_query.tmp"; // ofstream qf (fname); // qf << *argv; query_text = *argv; } #endif #ifdef UNICODE if(! inline_query) { char testfile[1024]; WideCharToMultiByte(CP_ACP, 0, // or CP_UTF8 *argv, -1, testfile, sizeof(testfile)/sizeof(char), NULL, NULL); fname = testfile; } #endif if(!inline_query) { // read the file std::ifstream qfile(fname); if(!qfile.is_open()) { // couldn't open file, display error and exit cerr << "Error opening xquery file <" << fname << ">" << endl; return -1; } string temp; query_text = ""; // warning: this method of reading a file might trim the // whitespace at the end of lines while (getline(qfile, temp)) { if (query_text != "") query_text += "\n"; query_text += temp; } } } } ///now start the zorba engine ZorbaFactory& zorba_factory = ZorbaFactory::getInstance(); ///thread specific zorba_factory.InitThread(); ///register the alerts callback Zorba_AlertsManager& errmanager = zorba_factory.getAlertsManagerForCurrentThread(); errmanager.RegisterAlertCallback(apitest_alert_callback, (void*)101); XQuery_t query; XQueryResult_t result = NULL; Item_t it; //create a compiled query query = zorba_factory.createQuery(query_text.c_str()); // if(!query->compile()) // { // goto DisplayErrorsAndExit; // } if(!query.get_ptr()) { goto DisplayErrorsAndExit; } result = query->execute(); if(!result.get_ptr()) { goto DisplayErrorsAndExit; } result->setAlertsParam(result.get_ptr());///to be passed to alerts callback when error occurs if (useResultFile) { resultFile = new ofstream(resultFileName.c_str()); //*resultFile << "Iterator run:" << std::endl << std::endl; } if (useSerializer) { // *resultFile << i_p->show() << endl; // serializer* ser = new serializer(); // ser->serialize(result, *resultFile); result->serializeXML(*resultFile); // endl should not be sent when serializing! // *resultFile << endl; } else { while( true ) { it = result->next(); if(it == NULL) break; if (resultFile != NULL) *resultFile << it->show() << endl; else cout << it->show() << endl; } } if(result->isError()) { goto DisplayErrorsAndExit; } //delete result; //delete query; // zorba_factory.destroyQuery(query); zorba_factory.UninitThread(); ZorbaFactory::shutdownZorbaEngine(); timer.end(); //if (resultFile != NULL) //{ // *resultFile << std::endl; // timer.print(*resultFile); //} //else timer.print(cout); if (resultFile != NULL) { resultFile->close(); delete resultFile; } return 0; DisplayErrorsAndExit: cerr << endl << "Display all error list now:" << endl; DisplayErrorListForCurrentThread(); zorba_factory.UninitThread(); ZorbaFactory::shutdownZorbaEngine(); timer.end(); timer.print(cout); return -1; } <|endoftext|>
<commit_before> #include "ImwPlatformWindow.h" #include "ImwWindowManager.h" namespace ImWindow { //SFF_BEGIN ImwPlatformWindow::ImwPlatformWindow(bool bMain, bool bIsDragWindow, bool bCreateState) { m_bMain = bMain; m_bIsDragWindow = bIsDragWindow; m_pContainer = new ImwContainer(this); m_pState = NULL; m_pPreviousState = NULL; m_bNeedRender = false; m_bShowContent = true; if (bCreateState) { void* pTemp = ImGui::GetInternalState(); ImGuiIO& oCurrentIO = ImGui::GetIO(); m_pState = ImwMalloc(ImGui::GetInternalStateSize()); ImGui::SetInternalState(m_pState, true); ImGuiIO& oNewIO = ImGui::GetIO(); memcpy(&((ImGuiState*)m_pState)->IO.KeyMap, &((ImGuiState*)pTemp)->IO.KeyMap, sizeof(int) * ImGuiKey_COUNT); oNewIO.RenderDrawListsFn = oCurrentIO.RenderDrawListsFn; oNewIO.GetClipboardTextFn = oCurrentIO.GetClipboardTextFn; oNewIO.SetClipboardTextFn = oCurrentIO.SetClipboardTextFn; oNewIO.MemAllocFn = oCurrentIO.MemAllocFn; oNewIO.MemFreeFn = oCurrentIO.MemFreeFn; oNewIO.ImeSetInputScreenPosFn = oCurrentIO.ImeSetInputScreenPosFn; ImGui::GetIO().IniFilename = NULL; ImGui::SetInternalState(pTemp); } } ImwPlatformWindow::~ImwPlatformWindow() { ImwSafeDelete(m_pContainer); SetState(); if (!IsMain()) { ImGui::GetIO().Fonts = NULL; } ImGui::Shutdown(); RestoreState(); ImwSafeFree(m_pState); } bool ImwPlatformWindow::Init(ImwPlatformWindow* /*pParent*/) { return true; } const ImVec2 c_oVec2_0 = ImVec2(0,0); ImVec2 ImwPlatformWindow::GetPosition() const { return c_oVec2_0; } ImVec2 ImwPlatformWindow::GetSize() const { return ImGui::GetIO().DisplaySize; } bool ImwPlatformWindow::IsWindowMaximized() const { return false; } void ImwPlatformWindow::Show() { } void ImwPlatformWindow::Hide() { } void ImwPlatformWindow::SetSize(int /*iWidth*/, int /*iHeight*/) { } void ImwPlatformWindow::SetPosition(int /*iX*/, int /*iY*/) { } void ImwPlatformWindow::SetWindowMaximized(bool /*bMaximized*/) { } void ImwPlatformWindow::SetTitle(const char* /*pTtile*/) { } bool ImwPlatformWindow::IsShowContent() const { return m_bShowContent; } void ImwPlatformWindow::SetShowContent(bool bShow) { m_bShowContent = bShow; } void ImwPlatformWindow::OnClose() { ImwWindowManager::GetInstance()->OnClosePlatformWindow(this); } bool ImwPlatformWindow::Save(JsonValue& oJson) { oJson["Width"] = (long)GetSize().x; oJson["Height"] = (long)GetSize().y; oJson["Left"] = (long)GetPosition().x; oJson["Top"] = (long)GetPosition().y; oJson["Maximized"] = IsWindowMaximized(); return m_pContainer->Save(oJson["Container"]); } bool ImwPlatformWindow::Load(const JsonValue& oJson, bool bJustCheck) { if (!oJson["Width"].IsNumeric() || !oJson["Height"].IsNumeric() || !oJson["Left"].IsNumeric() || !oJson["Top"].IsNumeric() || !oJson["Maximized"].IsBoolean()) return false; if (!bJustCheck) { SetSize((long)oJson["Width"], (long)oJson["Height"]); SetPosition((long)oJson["Left"], (long)oJson["Top"]); SetWindowMaximized(oJson["Maximized"]); } return m_pContainer->Load(oJson["Container"], bJustCheck); } static bool s_bStatePush = false; bool ImwPlatformWindow::IsStateSet() { return s_bStatePush; } bool ImwPlatformWindow::HasState() const { return m_pState != NULL; } void ImwPlatformWindow::SetState() { IM_ASSERT(s_bStatePush == false); s_bStatePush = true; if (m_pState != NULL) { m_pPreviousState = ImGui::GetInternalState(); ImGui::SetInternalState(m_pState); memcpy(&((ImGuiState*)m_pState)->Style, &((ImGuiState*)m_pPreviousState)->Style, sizeof(ImGuiStyle)); } } void ImwPlatformWindow::RestoreState() { IM_ASSERT(s_bStatePush == true); s_bStatePush = false; if (m_pState != NULL) { memcpy(&((ImGuiState*)m_pPreviousState)->Style, &((ImGuiState*)m_pState)->Style, sizeof(ImGuiStyle)); ImGui::SetInternalState(m_pPreviousState); } } void ImwPlatformWindow::OnLoseFocus() { if (NULL != m_pState) { ImGuiState& g = *((ImGuiState*)m_pState); g.SetNextWindowPosCond = g.SetNextWindowSizeCond = g.SetNextWindowContentSizeCond = g.SetNextWindowCollapsedCond = g.SetNextWindowFocus = 0; } } void ImwPlatformWindow::PreUpdate() { } void ImwPlatformWindow::Destroy() { } void ImwPlatformWindow::StartDrag() { } void ImwPlatformWindow::StopDrag() { } bool ImwPlatformWindow::IsDraging() { return false; } void ImwPlatformWindow::Render() { if (m_bNeedRender) { m_bNeedRender = false; SetState(); ImGui::Render(); RestoreState(); } } bool ImwPlatformWindow::IsMain() { return m_bMain; } void ImwPlatformWindow::Dock(ImwWindow* pWindow) { m_pContainer->Dock(pWindow); } bool ImwPlatformWindow::UnDock(ImwWindow* pWindow) { return m_pContainer->UnDock(pWindow); } ImwContainer* ImwPlatformWindow::GetContainer() { return m_pContainer; } ImwContainer* ImwPlatformWindow::HasWindow(ImwWindow* pWindow) { return m_pContainer->HasWindow(pWindow); } bool ImwPlatformWindow::FocusWindow(ImwWindow* pWindow) { return m_pContainer->FocusWindow(pWindow); } void ImwPlatformWindow::PaintContainer() { m_pContainer->Paint(); } //SFF_END }<commit_msg>Clear input on lose focus<commit_after> #include "ImwPlatformWindow.h" #include "ImwWindowManager.h" namespace ImWindow { //SFF_BEGIN ImwPlatformWindow::ImwPlatformWindow(bool bMain, bool bIsDragWindow, bool bCreateState) { m_bMain = bMain; m_bIsDragWindow = bIsDragWindow; m_pContainer = new ImwContainer(this); m_pState = NULL; m_pPreviousState = NULL; m_bNeedRender = false; m_bShowContent = true; if (bCreateState) { void* pTemp = ImGui::GetInternalState(); ImGuiIO& oCurrentIO = ImGui::GetIO(); m_pState = ImwMalloc(ImGui::GetInternalStateSize()); ImGui::SetInternalState(m_pState, true); ImGuiIO& oNewIO = ImGui::GetIO(); memcpy(&((ImGuiState*)m_pState)->IO.KeyMap, &((ImGuiState*)pTemp)->IO.KeyMap, sizeof(int) * ImGuiKey_COUNT); oNewIO.RenderDrawListsFn = oCurrentIO.RenderDrawListsFn; oNewIO.GetClipboardTextFn = oCurrentIO.GetClipboardTextFn; oNewIO.SetClipboardTextFn = oCurrentIO.SetClipboardTextFn; oNewIO.MemAllocFn = oCurrentIO.MemAllocFn; oNewIO.MemFreeFn = oCurrentIO.MemFreeFn; oNewIO.ImeSetInputScreenPosFn = oCurrentIO.ImeSetInputScreenPosFn; ImGui::GetIO().IniFilename = NULL; ImGui::SetInternalState(pTemp); } } ImwPlatformWindow::~ImwPlatformWindow() { ImwSafeDelete(m_pContainer); SetState(); if (!IsMain()) { ImGui::GetIO().Fonts = NULL; } ImGui::Shutdown(); RestoreState(); ImwSafeFree(m_pState); } bool ImwPlatformWindow::Init(ImwPlatformWindow* /*pParent*/) { return true; } const ImVec2 c_oVec2_0 = ImVec2(0,0); ImVec2 ImwPlatformWindow::GetPosition() const { return c_oVec2_0; } ImVec2 ImwPlatformWindow::GetSize() const { return ImGui::GetIO().DisplaySize; } bool ImwPlatformWindow::IsWindowMaximized() const { return false; } void ImwPlatformWindow::Show() { } void ImwPlatformWindow::Hide() { } void ImwPlatformWindow::SetSize(int /*iWidth*/, int /*iHeight*/) { } void ImwPlatformWindow::SetPosition(int /*iX*/, int /*iY*/) { } void ImwPlatformWindow::SetWindowMaximized(bool /*bMaximized*/) { } void ImwPlatformWindow::SetTitle(const char* /*pTtile*/) { } bool ImwPlatformWindow::IsShowContent() const { return m_bShowContent; } void ImwPlatformWindow::SetShowContent(bool bShow) { m_bShowContent = bShow; } void ImwPlatformWindow::OnClose() { ImwWindowManager::GetInstance()->OnClosePlatformWindow(this); } bool ImwPlatformWindow::Save(JsonValue& oJson) { oJson["Width"] = (long)GetSize().x; oJson["Height"] = (long)GetSize().y; oJson["Left"] = (long)GetPosition().x; oJson["Top"] = (long)GetPosition().y; oJson["Maximized"] = IsWindowMaximized(); return m_pContainer->Save(oJson["Container"]); } bool ImwPlatformWindow::Load(const JsonValue& oJson, bool bJustCheck) { if (!oJson["Width"].IsNumeric() || !oJson["Height"].IsNumeric() || !oJson["Left"].IsNumeric() || !oJson["Top"].IsNumeric() || !oJson["Maximized"].IsBoolean()) return false; if (!bJustCheck) { SetSize((long)oJson["Width"], (long)oJson["Height"]); SetPosition((long)oJson["Left"], (long)oJson["Top"]); SetWindowMaximized(oJson["Maximized"]); } return m_pContainer->Load(oJson["Container"], bJustCheck); } static bool s_bStatePush = false; bool ImwPlatformWindow::IsStateSet() { return s_bStatePush; } bool ImwPlatformWindow::HasState() const { return m_pState != NULL; } void ImwPlatformWindow::SetState() { IM_ASSERT(s_bStatePush == false); s_bStatePush = true; if (m_pState != NULL) { m_pPreviousState = ImGui::GetInternalState(); ImGui::SetInternalState(m_pState); memcpy(&((ImGuiState*)m_pState)->Style, &((ImGuiState*)m_pPreviousState)->Style, sizeof(ImGuiStyle)); } } void ImwPlatformWindow::RestoreState() { IM_ASSERT(s_bStatePush == true); s_bStatePush = false; if (m_pState != NULL) { memcpy(&((ImGuiState*)m_pPreviousState)->Style, &((ImGuiState*)m_pState)->Style, sizeof(ImGuiStyle)); ImGui::SetInternalState(m_pPreviousState); } } void ImwPlatformWindow::OnLoseFocus() { if (NULL != m_pState) { ImGuiState& g = *((ImGuiState*)m_pState); g.SetNextWindowPosCond = g.SetNextWindowSizeCond = g.SetNextWindowContentSizeCond = g.SetNextWindowCollapsedCond = g.SetNextWindowFocus = 0; for (int i = 0; i < 512; ++i) g.IO.KeysDown[i] = false; for (int i = 0; i < 5; ++i) g.IO.MouseDown[i] = false; g.IO.KeyAlt = false; g.IO.KeyCtrl = false; g.IO.KeyShift = false; } } void ImwPlatformWindow::PreUpdate() { } void ImwPlatformWindow::Destroy() { } void ImwPlatformWindow::StartDrag() { } void ImwPlatformWindow::StopDrag() { } bool ImwPlatformWindow::IsDraging() { return false; } void ImwPlatformWindow::Render() { if (m_bNeedRender) { m_bNeedRender = false; SetState(); ImGui::Render(); RestoreState(); } } bool ImwPlatformWindow::IsMain() { return m_bMain; } void ImwPlatformWindow::Dock(ImwWindow* pWindow) { m_pContainer->Dock(pWindow); } bool ImwPlatformWindow::UnDock(ImwWindow* pWindow) { return m_pContainer->UnDock(pWindow); } ImwContainer* ImwPlatformWindow::GetContainer() { return m_pContainer; } ImwContainer* ImwPlatformWindow::HasWindow(ImwWindow* pWindow) { return m_pContainer->HasWindow(pWindow); } bool ImwPlatformWindow::FocusWindow(ImwWindow* pWindow) { return m_pContainer->FocusWindow(pWindow); } void ImwPlatformWindow::PaintContainer() { m_pContainer->Paint(); } //SFF_END }<|endoftext|>
<commit_before>#include "x11api.h" #ifdef __LINUX__ #include <X11/X.h> #include <X11/Xlib.h> #include <X11/Xatom.h> #include <X11/Xos.h> #include <X11/keysymdef.h> #include <X11/Xutil.h> //#include <GL/glx.h> //FIXME #include <Tempest/Event> #include <Tempest/TextCodec> #include <Tempest/Window> #include <atomic> #include <stdexcept> #include <cstring> #include <thread> #include <unordered_map> struct HWND final { ::Window wnd; HWND()=default; HWND(::Window w):wnd(w) { } HWND(Tempest::SystemApi::Window* p) { std::memcpy(&wnd,&p,sizeof(wnd)); } HWND& operator = (::Window w) { wnd = w; return *this; } operator ::Window() { return wnd; } Tempest::SystemApi::Window* ptr() { static_assert (sizeof(::Window)<=sizeof(void*),"cannot map X11 window handle to pointer"); Tempest::SystemApi::Window* ret=nullptr; std::memcpy(&ret,&wnd,sizeof(wnd)); return ret; } }; using namespace Tempest; static const char* wndClassName="Tempest.Window"; static Display* dpy = nullptr; static ::Window root = {}; static std::atomic_bool isExit{0}; static int activeCursorChange = 0; static std::unordered_map<SystemApi::Window*,Tempest::Window*> windows; static Atom& wmDeleteMessage(){ static Atom w = XInternAtom( dpy, "WM_DELETE_WINDOW", 0); return w; } static Atom& _NET_WM_STATE(){ static Atom w = XInternAtom( dpy, "_NET_WM_STATE", 0); return w; } static Atom& _NET_WM_STATE_MAXIMIZED_HORZ(){ static Atom w = XInternAtom( dpy, "_NET_WM_STATE_MAXIMIZED_HORZ", 0); return w; } static Atom& _NET_WM_STATE_MAXIMIZED_VERT(){ static Atom w = XInternAtom( dpy, "_NET_WM_STATE_MAXIMIZED_VERT", 0); return w; } static Atom& _NET_WM_STATE_FULLSCREEN(){ static Atom w = XInternAtom( dpy, "_NET_WM_STATE_FULLSCREEN", 0); return w; } static Event::MouseButton toButton( XButtonEvent& msg ){ if( msg.button==Button1 ) return Event::ButtonLeft; if( msg.button==Button3 ) return Event::ButtonRight; if( msg.button==Button2 ) return Event::ButtonMid; return Event::ButtonNone; } static void maximizeWindow(HWND& w) { Atom a[2]; a[0] = _NET_WM_STATE_MAXIMIZED_HORZ(); a[1] = _NET_WM_STATE_MAXIMIZED_VERT(); XChangeProperty ( dpy, w, _NET_WM_STATE(), XA_ATOM, 32, PropModeReplace, (unsigned char*)a, 2); XSync(dpy,False); } X11Api::X11Api() { XInitThreads(); dpy = XOpenDisplay(nullptr); if(dpy == nullptr) throw std::runtime_error("cannot connect to X server!"); root = DefaultRootWindow(dpy); static const TranslateKeyPair k[] = { { XK_Control_L, Event::K_LControl }, { XK_Control_R, Event::K_RControl }, { XK_Shift_L, Event::K_LShift }, { XK_Shift_R, Event::K_RShift }, { XK_Alt_L, Event::K_LAlt }, { XK_Alt_R, Event::K_RAlt }, { XK_Left, Event::K_Left }, { XK_Right, Event::K_Right }, { XK_Up, Event::K_Up }, { XK_Down, Event::K_Down }, { XK_Escape, Event::K_ESCAPE }, { XK_Tab, Event::K_Tab }, { XK_BackSpace, Event::K_Back }, { XK_Delete, Event::K_Delete }, { XK_Insert, Event::K_Insert }, { XK_Home, Event::K_Home }, { XK_End, Event::K_End }, { XK_Pause, Event::K_Pause }, { XK_Return, Event::K_Return }, { XK_space, Event::K_Space }, { XK_Caps_Lock, Event::K_CapsLock }, { XK_F1, Event::K_F1 }, { 48, Event::K_0 }, { 97, Event::K_A }, { 0, Event::K_NoKey } }; setupKeyTranslate(k,24); } void *X11Api::display() { return dpy; } void X11Api::alignGeometry(SystemApi::Window *w, Tempest::Window& owner) { XWindowAttributes xwa={}; if(XGetWindowAttributes(dpy, HWND(w), &xwa)){ Tempest::SizeEvent e(xwa.width, xwa.height); SystemApi::dispatchResize(owner,e); } } SystemApi::Window *X11Api::implCreateWindow(Tempest::Window *owner, uint32_t w, uint32_t h) { //GLint att[] = { GLX_RGBA, GLX_DEPTH_SIZE, 24, GLX_DOUBLEBUFFER, None }; //XVisualInfo * vi = glXChooseVisual(dpy, 0, att); long visualMask = VisualScreenMask; int numberOfVisuals; XVisualInfo vInfoTemplate = {}; vInfoTemplate.screen = DefaultScreen(dpy); XVisualInfo * vi = XGetVisualInfo(dpy, visualMask, &vInfoTemplate, &numberOfVisuals); Colormap cmap; cmap = XCreateColormap(dpy, root, vi->visual, AllocNone); XSetWindowAttributes swa={}; swa.colormap = cmap; swa.event_mask = PointerMotionMask | ExposureMask | ButtonPressMask | ButtonReleaseMask | KeyPressMask | KeyReleaseMask; HWND win = XCreateWindow( dpy, root, 0, 0, w, h, 0, vi->depth, InputOutput, vi->visual, CWColormap | CWEventMask, &swa ); XSetWMProtocols(dpy, win, &wmDeleteMessage(), 1); XStoreName(dpy, win, wndClassName); XFreeColormap( dpy, cmap ); XFree(vi); auto ret = reinterpret_cast<SystemApi::Window*>(win.ptr()); windows[ret] = owner; XMapWindow(dpy, win); XSync(dpy,False); if(owner!=nullptr) alignGeometry(win.ptr(),*owner); return ret; } SystemApi::Window *X11Api::implCreateWindow(Tempest::Window *owner, SystemApi::ShowMode sm) { Screen* s = DefaultScreenOfDisplay(dpy); int width = s->width; int height = s->height; SystemApi::Window* hwnd = nullptr; switch(sm) { case Hidden: hwnd = implCreateWindow(owner,1, 1); // TODO: make window invisible break; case Normal: hwnd = implCreateWindow(owner,800, 600); break; case Minimized: case Maximized: // TODO hwnd = implCreateWindow(owner,width, height); break; case FullScreen: hwnd = implCreateWindow(owner,width, height); implSetAsFullscreen(hwnd,true); break; } return hwnd; } void X11Api::implDestroyWindow(SystemApi::Window *w) { windows.erase(w); //NOTE: X11 can send events to ded window XDestroyWindow(dpy, HWND(w)); } bool X11Api::implSetAsFullscreen(SystemApi::Window *w, bool fullScreen) { XEvent e = {}; e.xclient.type = ClientMessage; e.xclient.window = HWND(w); e.xclient.message_type = _NET_WM_STATE(); e.xclient.format = 32; e.xclient.data.l[0] = 2; // _NET_WM_STATE_TOGGLE e.xclient.data.l[1] = _NET_WM_STATE_FULLSCREEN(); e.xclient.data.l[2] = 0; // no second property to toggle if(fullScreen) e.xclient.data.l[3] = 1; else e.xclient.data.l[3] = 0; XSendEvent(dpy, DefaultRootWindow(dpy), False, SubstructureRedirectMask | SubstructureNotifyMask, &e); return true; } bool X11Api::implIsFullscreen(SystemApi::Window *w) { Atom actualType; int actualFormat; unsigned long i, numItems, bytesAfter; unsigned char *propertyValue = NULL; long maxLength = 1024; if (XGetWindowProperty(dpy, HWND(w), _NET_WM_STATE(), 0l, maxLength, False, XA_ATOM, &actualType, &actualFormat, &numItems, &bytesAfter, &propertyValue) == Success) { int fullscreen = 0; Atom *atoms = (Atom *) propertyValue; for (i = 0; i < numItems; ++i) { if (atoms[i] == _NET_WM_STATE_FULLSCREEN()) { fullscreen = 1; } } if(fullscreen) { return true; } } return false; } void X11Api::implSetCursorPosition(SystemApi::Window *w, int x, int y) { activeCursorChange = 1; XWarpPointer(dpy, None, HWND(w), 0, 0, 0, 0, x, y); XFlush(dpy); } void X11Api::implShowCursor(bool show) { if(windows.size()==0) return; if(show) { XUndefineCursor(dpy, HWND(windows.begin()->first)); } else { Cursor invisibleCursor; ::Pixmap bitmapNoData; XColor black; static char noData[] = { 0,0,0,0,0,0,0,0 }; black.red = black.green = black.blue = 0; bitmapNoData = XCreateBitmapFromData(dpy, HWND(windows.begin()->first), noData, 8, 8); invisibleCursor = XCreatePixmapCursor(dpy, bitmapNoData, bitmapNoData, &black, &black, 0, 0); XDefineCursor(dpy, HWND(windows.begin()->first), invisibleCursor); XFreeCursor(dpy, invisibleCursor); XFreePixmap(dpy, bitmapNoData); } XSync(dpy, False); } Rect X11Api::implWindowClientRect(SystemApi::Window *w) { XWindowAttributes xwa; XGetWindowAttributes(dpy, HWND(w), &xwa); return Rect( xwa.x, xwa.y, xwa.width, xwa.height ); } void X11Api::implExit() { isExit.store(true); } bool X11Api::implIsRunning() { return !isExit.load(); } int X11Api::implExec(SystemApi::AppCallBack &cb) { // main message loop while (!isExit.load()) { implProcessEvents(cb); } return 0; } void X11Api::implProcessEvents(SystemApi::AppCallBack &cb) { // main message loop if(XPending(dpy)>0) { XEvent xev={}; XNextEvent(dpy, &xev); HWND hWnd = xev.xclient.window; auto it = windows.find(hWnd.ptr()); if(it==windows.end() || it->second==nullptr) return; Tempest::Window& cb = *it->second; //TODO: validation switch( xev.type ) { case ClientMessage: { if( xev.xclient.data.l[0] == long(wmDeleteMessage()) ){ SystemApi::exit(); } break; } case ButtonPress: case ButtonRelease: { bool isWheel = false; if( xev.type==ButtonPress && XPending(dpy) && (xev.xbutton.button == Button4 || xev.xbutton.button == Button5) ){ XEvent ev; XNextEvent(dpy, &ev); isWheel = (ev.type==ButtonRelease); } if( isWheel ){ int ticks = 0; if( xev.xbutton.button == Button4 ) { ticks = 100; } else if ( xev.xbutton.button == Button5 ) { ticks = -100; } Tempest::MouseEvent e( xev.xbutton.x, xev.xbutton.y, Tempest::Event::ButtonNone, Event::M_NoModifier, ticks, 0, Event::MouseWheel ); SystemApi::dispatchMouseWheel(cb, e); } else { MouseEvent e( xev.xbutton.x, xev.xbutton.y, toButton( xev.xbutton ), Event::M_NoModifier, 0, 0, xev.type==ButtonPress ? Event::MouseDown : Event::MouseUp ); if(xev.type==ButtonPress) SystemApi::dispatchMouseDown(cb, e); else SystemApi::dispatchMouseUp(cb, e); } break; } case MotionNotify: { if(activeCursorChange == 1) { // FIXME: mouse behave crazy in OpenGothic activeCursorChange = 0; break; } MouseEvent e( xev.xmotion.x, xev.xmotion.y, Event::ButtonNone, Event::M_NoModifier, 0, 0, Event::MouseMove ); SystemApi::dispatchMouseMove(cb, e); break; } case KeyPress: case KeyRelease: { int keysyms_per_keycode_return = 0; KeySym *ksym = XGetKeyboardMapping( dpy, KeyCode(xev.xkey.keycode), 1, &keysyms_per_keycode_return ); char txt[10]={}; XLookupString(&xev.xkey, txt, sizeof(txt)-1, ksym, nullptr ); auto u16 = TextCodec::toUtf16(txt); // TODO: remove dynamic allocation auto key = SystemApi::translateKey(XLookupKeysym(&xev.xkey,0)); uint32_t scan = xev.xkey.keycode; Tempest::KeyEvent e(Event::KeyType(key),uint32_t(u16.size()>0 ? u16[0] : 0),Event::M_NoModifier,(xev.type==KeyPress) ? Event::KeyDown : Event::KeyUp); if(xev.type==KeyPress) SystemApi::dispatchKeyDown(cb,e,scan); else SystemApi::dispatchKeyUp (cb,e,scan); break; } } std::this_thread::yield(); } else { if(cb.onTimer()==0) std::this_thread::yield(); for(auto& i:windows) { if(i.second==nullptr) continue; // artificial move/resize event alignGeometry(i.first,*i.second); SystemApi::dispatchRender(*i.second); } } } #endif <commit_msg>support for X11 mouse button back/forward (#20)<commit_after>#include "x11api.h" #ifdef __LINUX__ #include <X11/X.h> #include <X11/Xlib.h> #include <X11/Xatom.h> #include <X11/Xos.h> #include <X11/keysymdef.h> #include <X11/Xutil.h> //#include <GL/glx.h> //FIXME #include <Tempest/Event> #include <Tempest/TextCodec> #include <Tempest/Window> #include <atomic> #include <stdexcept> #include <cstring> #include <thread> #include <unordered_map> struct HWND final { ::Window wnd; HWND()=default; HWND(::Window w):wnd(w) { } HWND(Tempest::SystemApi::Window* p) { std::memcpy(&wnd,&p,sizeof(wnd)); } HWND& operator = (::Window w) { wnd = w; return *this; } operator ::Window() { return wnd; } Tempest::SystemApi::Window* ptr() { static_assert (sizeof(::Window)<=sizeof(void*),"cannot map X11 window handle to pointer"); Tempest::SystemApi::Window* ret=nullptr; std::memcpy(&ret,&wnd,sizeof(wnd)); return ret; } }; using namespace Tempest; static const char* wndClassName="Tempest.Window"; static Display* dpy = nullptr; static ::Window root = {}; static std::atomic_bool isExit{0}; static int activeCursorChange = 0; static std::unordered_map<SystemApi::Window*,Tempest::Window*> windows; static Atom& wmDeleteMessage(){ static Atom w = XInternAtom( dpy, "WM_DELETE_WINDOW", 0); return w; } static Atom& _NET_WM_STATE(){ static Atom w = XInternAtom( dpy, "_NET_WM_STATE", 0); return w; } static Atom& _NET_WM_STATE_MAXIMIZED_HORZ(){ static Atom w = XInternAtom( dpy, "_NET_WM_STATE_MAXIMIZED_HORZ", 0); return w; } static Atom& _NET_WM_STATE_MAXIMIZED_VERT(){ static Atom w = XInternAtom( dpy, "_NET_WM_STATE_MAXIMIZED_VERT", 0); return w; } static Atom& _NET_WM_STATE_FULLSCREEN(){ static Atom w = XInternAtom( dpy, "_NET_WM_STATE_FULLSCREEN", 0); return w; } static Event::MouseButton toButton( XButtonEvent& msg ){ if( msg.button==Button1 ) return Event::ButtonLeft; if( msg.button==Button3 ) return Event::ButtonRight; if( msg.button==Button2 ) return Event::ButtonMid; if( msg.button==8 ) return Event::ButtonBack; if( msg.button==9 ) return Event::ButtonForward; return Event::ButtonNone; } static void maximizeWindow(HWND& w) { Atom a[2]; a[0] = _NET_WM_STATE_MAXIMIZED_HORZ(); a[1] = _NET_WM_STATE_MAXIMIZED_VERT(); XChangeProperty ( dpy, w, _NET_WM_STATE(), XA_ATOM, 32, PropModeReplace, (unsigned char*)a, 2); XSync(dpy,False); } X11Api::X11Api() { XInitThreads(); dpy = XOpenDisplay(nullptr); if(dpy == nullptr) throw std::runtime_error("cannot connect to X server!"); root = DefaultRootWindow(dpy); static const TranslateKeyPair k[] = { { XK_Control_L, Event::K_LControl }, { XK_Control_R, Event::K_RControl }, { XK_Shift_L, Event::K_LShift }, { XK_Shift_R, Event::K_RShift }, { XK_Alt_L, Event::K_LAlt }, { XK_Alt_R, Event::K_RAlt }, { XK_Left, Event::K_Left }, { XK_Right, Event::K_Right }, { XK_Up, Event::K_Up }, { XK_Down, Event::K_Down }, { XK_Escape, Event::K_ESCAPE }, { XK_Tab, Event::K_Tab }, { XK_BackSpace, Event::K_Back }, { XK_Delete, Event::K_Delete }, { XK_Insert, Event::K_Insert }, { XK_Home, Event::K_Home }, { XK_End, Event::K_End }, { XK_Pause, Event::K_Pause }, { XK_Return, Event::K_Return }, { XK_space, Event::K_Space }, { XK_Caps_Lock, Event::K_CapsLock }, { XK_F1, Event::K_F1 }, { 48, Event::K_0 }, { 97, Event::K_A }, { 0, Event::K_NoKey } }; setupKeyTranslate(k,24); } void *X11Api::display() { return dpy; } void X11Api::alignGeometry(SystemApi::Window *w, Tempest::Window& owner) { XWindowAttributes xwa={}; if(XGetWindowAttributes(dpy, HWND(w), &xwa)){ Tempest::SizeEvent e(xwa.width, xwa.height); SystemApi::dispatchResize(owner,e); } } SystemApi::Window *X11Api::implCreateWindow(Tempest::Window *owner, uint32_t w, uint32_t h) { //GLint att[] = { GLX_RGBA, GLX_DEPTH_SIZE, 24, GLX_DOUBLEBUFFER, None }; //XVisualInfo * vi = glXChooseVisual(dpy, 0, att); long visualMask = VisualScreenMask; int numberOfVisuals; XVisualInfo vInfoTemplate = {}; vInfoTemplate.screen = DefaultScreen(dpy); XVisualInfo * vi = XGetVisualInfo(dpy, visualMask, &vInfoTemplate, &numberOfVisuals); Colormap cmap; cmap = XCreateColormap(dpy, root, vi->visual, AllocNone); XSetWindowAttributes swa={}; swa.colormap = cmap; swa.event_mask = PointerMotionMask | ExposureMask | ButtonPressMask | ButtonReleaseMask | KeyPressMask | KeyReleaseMask; HWND win = XCreateWindow( dpy, root, 0, 0, w, h, 0, vi->depth, InputOutput, vi->visual, CWColormap | CWEventMask, &swa ); XSetWMProtocols(dpy, win, &wmDeleteMessage(), 1); XStoreName(dpy, win, wndClassName); XFreeColormap( dpy, cmap ); XFree(vi); auto ret = reinterpret_cast<SystemApi::Window*>(win.ptr()); windows[ret] = owner; XMapWindow(dpy, win); XSync(dpy,False); if(owner!=nullptr) alignGeometry(win.ptr(),*owner); return ret; } SystemApi::Window *X11Api::implCreateWindow(Tempest::Window *owner, SystemApi::ShowMode sm) { Screen* s = DefaultScreenOfDisplay(dpy); int width = s->width; int height = s->height; SystemApi::Window* hwnd = nullptr; switch(sm) { case Hidden: hwnd = implCreateWindow(owner,1, 1); // TODO: make window invisible break; case Normal: hwnd = implCreateWindow(owner,800, 600); break; case Minimized: case Maximized: // TODO hwnd = implCreateWindow(owner,width, height); break; case FullScreen: hwnd = implCreateWindow(owner,width, height); implSetAsFullscreen(hwnd,true); break; } return hwnd; } void X11Api::implDestroyWindow(SystemApi::Window *w) { windows.erase(w); //NOTE: X11 can send events to ded window XDestroyWindow(dpy, HWND(w)); } bool X11Api::implSetAsFullscreen(SystemApi::Window *w, bool fullScreen) { XEvent e = {}; e.xclient.type = ClientMessage; e.xclient.window = HWND(w); e.xclient.message_type = _NET_WM_STATE(); e.xclient.format = 32; e.xclient.data.l[0] = 2; // _NET_WM_STATE_TOGGLE e.xclient.data.l[1] = _NET_WM_STATE_FULLSCREEN(); e.xclient.data.l[2] = 0; // no second property to toggle if(fullScreen) e.xclient.data.l[3] = 1; else e.xclient.data.l[3] = 0; XSendEvent(dpy, DefaultRootWindow(dpy), False, SubstructureRedirectMask | SubstructureNotifyMask, &e); return true; } bool X11Api::implIsFullscreen(SystemApi::Window *w) { Atom actualType; int actualFormat; unsigned long i, numItems, bytesAfter; unsigned char *propertyValue = NULL; long maxLength = 1024; if (XGetWindowProperty(dpy, HWND(w), _NET_WM_STATE(), 0l, maxLength, False, XA_ATOM, &actualType, &actualFormat, &numItems, &bytesAfter, &propertyValue) == Success) { int fullscreen = 0; Atom *atoms = (Atom *) propertyValue; for (i = 0; i < numItems; ++i) { if (atoms[i] == _NET_WM_STATE_FULLSCREEN()) { fullscreen = 1; } } if(fullscreen) { return true; } } return false; } void X11Api::implSetCursorPosition(SystemApi::Window *w, int x, int y) { activeCursorChange = 1; XWarpPointer(dpy, None, HWND(w), 0, 0, 0, 0, x, y); XFlush(dpy); } void X11Api::implShowCursor(bool show) { if(windows.size()==0) return; if(show) { XUndefineCursor(dpy, HWND(windows.begin()->first)); } else { Cursor invisibleCursor; ::Pixmap bitmapNoData; XColor black; static char noData[] = { 0,0,0,0,0,0,0,0 }; black.red = black.green = black.blue = 0; bitmapNoData = XCreateBitmapFromData(dpy, HWND(windows.begin()->first), noData, 8, 8); invisibleCursor = XCreatePixmapCursor(dpy, bitmapNoData, bitmapNoData, &black, &black, 0, 0); XDefineCursor(dpy, HWND(windows.begin()->first), invisibleCursor); XFreeCursor(dpy, invisibleCursor); XFreePixmap(dpy, bitmapNoData); } XSync(dpy, False); } Rect X11Api::implWindowClientRect(SystemApi::Window *w) { XWindowAttributes xwa; XGetWindowAttributes(dpy, HWND(w), &xwa); return Rect( xwa.x, xwa.y, xwa.width, xwa.height ); } void X11Api::implExit() { isExit.store(true); } bool X11Api::implIsRunning() { return !isExit.load(); } int X11Api::implExec(SystemApi::AppCallBack &cb) { // main message loop while (!isExit.load()) { implProcessEvents(cb); } return 0; } void X11Api::implProcessEvents(SystemApi::AppCallBack &cb) { // main message loop if(XPending(dpy)>0) { XEvent xev={}; XNextEvent(dpy, &xev); HWND hWnd = xev.xclient.window; auto it = windows.find(hWnd.ptr()); if(it==windows.end() || it->second==nullptr) return; Tempest::Window& cb = *it->second; //TODO: validation switch( xev.type ) { case ClientMessage: { if( xev.xclient.data.l[0] == long(wmDeleteMessage()) ){ SystemApi::exit(); } break; } case ButtonPress: case ButtonRelease: { bool isWheel = false; if( xev.type==ButtonPress && XPending(dpy) && (xev.xbutton.button == Button4 || xev.xbutton.button == Button5) ){ XEvent ev; XNextEvent(dpy, &ev); isWheel = (ev.type==ButtonRelease); } if( isWheel ){ int ticks = 0; if( xev.xbutton.button == Button4 ) { ticks = 100; } else if ( xev.xbutton.button == Button5 ) { ticks = -100; } Tempest::MouseEvent e( xev.xbutton.x, xev.xbutton.y, Tempest::Event::ButtonNone, Event::M_NoModifier, ticks, 0, Event::MouseWheel ); SystemApi::dispatchMouseWheel(cb, e); } else { MouseEvent e( xev.xbutton.x, xev.xbutton.y, toButton( xev.xbutton ), Event::M_NoModifier, 0, 0, xev.type==ButtonPress ? Event::MouseDown : Event::MouseUp ); if(xev.type==ButtonPress) SystemApi::dispatchMouseDown(cb, e); else SystemApi::dispatchMouseUp(cb, e); } break; } case MotionNotify: { if(activeCursorChange == 1) { // FIXME: mouse behave crazy in OpenGothic activeCursorChange = 0; break; } MouseEvent e( xev.xmotion.x, xev.xmotion.y, Event::ButtonNone, Event::M_NoModifier, 0, 0, Event::MouseMove ); SystemApi::dispatchMouseMove(cb, e); break; } case KeyPress: case KeyRelease: { int keysyms_per_keycode_return = 0; KeySym *ksym = XGetKeyboardMapping( dpy, KeyCode(xev.xkey.keycode), 1, &keysyms_per_keycode_return ); char txt[10]={}; XLookupString(&xev.xkey, txt, sizeof(txt)-1, ksym, nullptr ); auto u16 = TextCodec::toUtf16(txt); // TODO: remove dynamic allocation auto key = SystemApi::translateKey(XLookupKeysym(&xev.xkey,0)); uint32_t scan = xev.xkey.keycode; Tempest::KeyEvent e(Event::KeyType(key),uint32_t(u16.size()>0 ? u16[0] : 0),Event::M_NoModifier,(xev.type==KeyPress) ? Event::KeyDown : Event::KeyUp); if(xev.type==KeyPress) SystemApi::dispatchKeyDown(cb,e,scan); else SystemApi::dispatchKeyUp (cb,e,scan); break; } } std::this_thread::yield(); } else { if(cb.onTimer()==0) std::this_thread::yield(); for(auto& i:windows) { if(i.second==nullptr) continue; // artificial move/resize event alignGeometry(i.first,*i.second); SystemApi::dispatchRender(*i.second); } } } #endif <|endoftext|>
<commit_before>/* docker-script: run script files inside Docker containers Copyright (c) 2017, Adam Rehn 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 "NvidiaDockerImages.h" #include "Utility.h" #include <stdexcept> #include <iostream> #include <fstream> #include <cstdlib> #include <vector> using std::ifstream; using std::vector; using std::clog; using std::endl; //The different versions of docker we support #define VANILLA_DOCKER "docker" #define NVIDIA_DOCKER "nvidia-docker" int main (int argc, char* argv[]) { //Check that a script file was specified if (argc > 1) { try { //Parse CLI arguments, keeping docker-script options separate from script options string docker = VANILLA_DOCKER; bool interactive = true; bool verboseOutput = false; bool enableDebugging = false; bool dryrun = false; string trailingArgs = ""; for (int i = 2; i < argc; ++i) { string currArg = string(argv[i]); if (currArg == "---verbose") { verboseOutput = true; } else if (currArg == "---debug") { enableDebugging = true; } else if (currArg == "---non-interactive") { interactive = false; } else if (currArg == "---nvidia-docker") { docker = NVIDIA_DOCKER; } else if (currArg == "---dry-run") { dryrun = true; } else { trailingArgs += "\"" + currArg + "\" "; } } //Attempt to open the script file string scriptPath = argv[1]; ifstream script(scriptPath.c_str()); if (script.is_open() == false) { throw std::runtime_error("failed to open script file \"" + scriptPath + "\""); } //Attempt to read the second shebang line in the script file string shebang = ""; std::getline(script, shebang); std::getline(script, shebang); if (script.fail()) { throw std::runtime_error("failed to read second shebang line from \"" + scriptPath + "\""); } //Verify that the shebang line is well-formed size_t spacePos = shebang.find(" "); if (shebang.substr(0,2) != "#!" || spacePos == string::npos) { throw std::runtime_error("invalid second shebang line in script file \"" + scriptPath + "\""); } //Parse the shebang line string dockerImage = shebang.substr(2, spacePos - 2); string interpreter = shebang.substr(spacePos + 1); //Determine the full path to the script file scriptPath = Utility::realPath(scriptPath); //Extract the directory and filename components of the script's path, as well as our current working directory string scriptFile = Utility::baseName(scriptPath); string scriptDir = Utility::dirName(scriptPath); string workingDir = Utility::cwd(); //Extract the docker image name, without trailing tag name string imageWithoutTag = dockerImage.substr(0, dockerImage.find(":")); //If the specified docker image (or the specific image and tag combination) requires //nvidia-docker, we invoke nvidia-docker instead of regular docker auto nvDockerImages = NvidiaDockerImages::getList(); if (Utility::contains(nvDockerImages, imageWithoutTag) || Utility::contains(nvDockerImages, dockerImage)) { docker = NVIDIA_DOCKER; } //If we were invoked using the symlink `nvidia-docker-script`, always use `nvidia-docker` if (string(argv[0]) == "nvidia-docker-script") { docker = NVIDIA_DOCKER; } //Build the `docker run` command string command = docker + " run " + string("\"-v") + scriptDir + ":/scriptdir\" " + string("\"-v") + workingDir + ":/workingdir\" " + string((enableDebugging == true) ? "--privileged=true " : "") + string("--workdir=/workingdir ") + string("-e \"HOST_CWD=") + workingDir + "\" " + string((interactive == true) ? "-ti " : "-t ") + string("--rm --entrypoint=\"\" ") + string("\"") + dockerImage + "\" " + string("\"") + interpreter + "\" " + string("\"/scriptdir/") + scriptFile + "\" " + trailingArgs; //If verbose output was requested, display diagnostic information if (verboseOutput == true) { clog << "Docker image: " << dockerImage << endl; clog << "Interpreter: " << interpreter << endl; clog << "Script path: " << scriptPath << endl; clog << "Script basename: " << scriptFile << endl; clog << "Script dirname: " << scriptDir << endl; clog << "Working directory: " << workingDir << endl; clog << "Trailing arguments: " << trailingArgs << endl; clog << endl << "Docker command:" << endl << command << endl << endl; } //If we are performing a dry run, simply print the command that would have been invoked if (dryrun == true) { std::clog << command << std::endl; } else { //Invoke docker return system(command.c_str()); } } catch (std::runtime_error& e) { clog << "Error: " << e.what() << endl << endl; return 1; } } else { clog << "Usage:" << endl << argv[0] << " <SCRIPT> [---verbose] [---debug] [args for script]" << endl << endl; clog << "The first line of the script file should be a normal Unix shebang line." << endl; clog << "The second line of the script file should be:" << endl; clog << "#!<IMAGE> <INTERPRETER>" << endl << endl; } return 0; } <commit_msg>Output dry-run results on stdout instead of stderr<commit_after>/* docker-script: run script files inside Docker containers Copyright (c) 2017, Adam Rehn 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 "NvidiaDockerImages.h" #include "Utility.h" #include <stdexcept> #include <iostream> #include <fstream> #include <cstdlib> #include <vector> using std::ifstream; using std::vector; using std::clog; using std::endl; //The different versions of docker we support #define VANILLA_DOCKER "docker" #define NVIDIA_DOCKER "nvidia-docker" int main (int argc, char* argv[]) { //Check that a script file was specified if (argc > 1) { try { //Parse CLI arguments, keeping docker-script options separate from script options string docker = VANILLA_DOCKER; bool interactive = true; bool verboseOutput = false; bool enableDebugging = false; bool dryrun = false; string trailingArgs = ""; for (int i = 2; i < argc; ++i) { string currArg = string(argv[i]); if (currArg == "---verbose") { verboseOutput = true; } else if (currArg == "---debug") { enableDebugging = true; } else if (currArg == "---non-interactive") { interactive = false; } else if (currArg == "---nvidia-docker") { docker = NVIDIA_DOCKER; } else if (currArg == "---dry-run") { dryrun = true; } else { trailingArgs += "\"" + currArg + "\" "; } } //Attempt to open the script file string scriptPath = argv[1]; ifstream script(scriptPath.c_str()); if (script.is_open() == false) { throw std::runtime_error("failed to open script file \"" + scriptPath + "\""); } //Attempt to read the second shebang line in the script file string shebang = ""; std::getline(script, shebang); std::getline(script, shebang); if (script.fail()) { throw std::runtime_error("failed to read second shebang line from \"" + scriptPath + "\""); } //Verify that the shebang line is well-formed size_t spacePos = shebang.find(" "); if (shebang.substr(0,2) != "#!" || spacePos == string::npos) { throw std::runtime_error("invalid second shebang line in script file \"" + scriptPath + "\""); } //Parse the shebang line string dockerImage = shebang.substr(2, spacePos - 2); string interpreter = shebang.substr(spacePos + 1); //Determine the full path to the script file scriptPath = Utility::realPath(scriptPath); //Extract the directory and filename components of the script's path, as well as our current working directory string scriptFile = Utility::baseName(scriptPath); string scriptDir = Utility::dirName(scriptPath); string workingDir = Utility::cwd(); //Extract the docker image name, without trailing tag name string imageWithoutTag = dockerImage.substr(0, dockerImage.find(":")); //If the specified docker image (or the specific image and tag combination) requires //nvidia-docker, we invoke nvidia-docker instead of regular docker auto nvDockerImages = NvidiaDockerImages::getList(); if (Utility::contains(nvDockerImages, imageWithoutTag) || Utility::contains(nvDockerImages, dockerImage)) { docker = NVIDIA_DOCKER; } //If we were invoked using the symlink `nvidia-docker-script`, always use `nvidia-docker` if (string(argv[0]) == "nvidia-docker-script") { docker = NVIDIA_DOCKER; } //Build the `docker run` command string command = docker + " run " + string("\"-v") + scriptDir + ":/scriptdir\" " + string("\"-v") + workingDir + ":/workingdir\" " + string((enableDebugging == true) ? "--privileged=true " : "") + string("--workdir=/workingdir ") + string("-e \"HOST_CWD=") + workingDir + "\" " + string((interactive == true) ? "-ti " : "-t ") + string("--rm --entrypoint=\"\" ") + string("\"") + dockerImage + "\" " + string("\"") + interpreter + "\" " + string("\"/scriptdir/") + scriptFile + "\" " + trailingArgs; //If verbose output was requested, display diagnostic information if (verboseOutput == true) { clog << "Docker image: " << dockerImage << endl; clog << "Interpreter: " << interpreter << endl; clog << "Script path: " << scriptPath << endl; clog << "Script basename: " << scriptFile << endl; clog << "Script dirname: " << scriptDir << endl; clog << "Working directory: " << workingDir << endl; clog << "Trailing arguments: " << trailingArgs << endl; clog << endl << "Docker command:" << endl << command << endl << endl; } //If we are performing a dry run, simply print the command that would have been invoked if (dryrun == true) { std::cout << command << std::endl; } else { //Invoke docker return system(command.c_str()); } } catch (std::runtime_error& e) { clog << "Error: " << e.what() << endl << endl; return 1; } } else { clog << "Usage:" << endl << argv[0] << " <SCRIPT> [---verbose] [---debug] [args for script]" << endl << endl; clog << "The first line of the script file should be a normal Unix shebang line." << endl; clog << "The second line of the script file should be:" << endl; clog << "#!<IMAGE> <INTERPRETER>" << endl << endl; } return 0; } <|endoftext|>
<commit_before>/** * PcapSearch application * ====================== * This application searches all pcap files in a given directory and all its sub-directories (unless stated otherwise) and outputs how many and which * packets in those files match a certain pattern given by the user. The pattern is given in Berkeley Packet Filter (BPF) syntax * (http://biot.com/capstats/bpf.html). For example: if running the application with the following parameters: * PcapSearch.exe -d C:\ -s "ip net 1.1.1.1" -r C:\report.txt * The application will search all '.pcap' files in all directories under C drive and try to match packets that matches IP 1.1.1.1. The result will be * printed to stdout and a more detailed report will be printed to c:\report.txt * Output example: * 1 packets found in 'C:\\path\example\Dns.pcap' * 5 packets found in 'C:\\path\example\bla1\my_pcap2.pcap' * 7299 packets found in 'C:\\path2\example\example2\big_pcap.pcap' * 7435 packets found in 'C:\\path3\dir1\dir2\dir3\dir4\another.pcap' * 435 packets found in 'C:\\path3\dirx\diry\dirz\ok.pcap' * 4662 packets found in 'C:\\path4\gotit.pcap' * 7299 packets found in 'C:\\enough.pcap' * * There are switches that allows the user to search only in the provided folder (without sub-directories), search user-defined file extensions (sometimes * pcap files have an extension which is not '.pcap'), and output or not output the detailed report * * For more details about modes of operation and parameters please run PcapSearch -h */ #include <stdlib.h> #include <getopt.h> #include <iostream> #include <fstream> #include <sstream> #include <sys/stat.h> #include <dirent.h> #include <vector> #include <map> #include <Logger.h> #include <RawPacket.h> #include <Packet.h> #include <PcapFileDevice.h> using namespace pcpp; static struct option PcapSearchOptions[] = { {"input-dir", required_argument, 0, 'd'}, {"not-include-sub-dir", no_argument, 0, 'n'}, {"search", required_argument, 0, 's'}, {"detailed-report", required_argument, 0, 'r'}, {"set-extensions", required_argument, 0, 'e'}, {"help", no_argument, 0, 'h'}, {0, 0, 0, 0} }; #define EXIT_WITH_ERROR(reason, ...) do { \ printf("\nError: " reason "\n\n", ## __VA_ARGS__); \ printUsage(); \ exit(1); \ } while(0) #ifdef WIN32 #define DIR_SEPARATOR "\\" #else #define DIR_SEPARATOR "/" #endif #define ERROR_STRING_LEN 500 char errorString[ERROR_STRING_LEN]; /** * Print application usage */ void printUsage() { printf("\nUsage:\n" "-------\n" "PcapPrinter [-h] [-n] [-r file_name] [-e extension_list] -d directory -s search_criteria\n" "\nOptions:\n\n" " -d directory : Input directory\n" " -n : Don't include sub-directories (default is include them)\n" " -s search_criteria : Criteria to search in Berkeley Packet Filter (BPF) syntax (http://biot.com/capstats/bpf.html) i.e: 'ip net 1.1.1.1'\n" " -r file_name : Write a detailed search report to a file\n" " -e extension_list : Set file extensions to search. The default is searching '.pcap' files only.\n" " extnesions_list should be a comma-separated list of extensions, for example: pcap,net,dmp\n" " -h : Displays this help message and exits\n"); exit(0); } /* * Returns the extension of a given file name */ std::string getExtension(std::string fileName) { return fileName.substr(fileName.find_last_of(".") + 1); } /** * Searches all packet in a given pcap file for a certain search criteria. Returns how many packets matched the seatch criteria */ int searchPcap(std::string pcapFilePath, std::string searchCriteria, std::ofstream* detailedReportFile) { // create the pcap reader PcapFileReaderDevice reader(pcapFilePath.c_str()); // if the reader fails to open if (!reader.open()) { if (detailedReportFile != NULL) { // PcapPlusPlus writes the error to the error string variable we set it to write to // write this error to the report file (*detailedReportFile) << "File '" << pcapFilePath << "':" << std::endl; (*detailedReportFile) << " "; std::string errorStr = errorString; (*detailedReportFile) << errorStr << std::endl; } return 0; } // set the filter for the file so only packets that match the search criteria will be read if (!reader.setFilter(searchCriteria)) { return 0; } if (detailedReportFile != NULL) { (*detailedReportFile) << "File '" << pcapFilePath << "':" << std::endl; } int packetCount = 0; RawPacket rawPacket; // read packets from the file. Since we already set the filter, only packets that matches the filter will be read while (reader.getNextPacket(rawPacket)) { // if a detailed report is required, parse the packet and print it to the report file if (detailedReportFile != NULL) { // parse the packet Packet parsedPacket(&rawPacket); // print layer by layer by layer as we want to add a few spaces before each layer std::vector<std::string> packetLayers; parsedPacket.printToStringList(packetLayers); for (std::vector<std::string>::iterator iter = packetLayers.begin(); iter != packetLayers.end(); iter++) (*detailedReportFile) << "\n " << (*iter); (*detailedReportFile) << std::endl; } // count the packet read packetCount++; } // close the reader file reader.close(); // finalize the report if (detailedReportFile != NULL) { if (packetCount > 0) (*detailedReportFile) << "\n"; (*detailedReportFile) << " ----> Found " << packetCount << " packets" << std::endl << std::endl; } // return how many packets matched the search criteria return packetCount; } /** * Searches all pcap files in given directory (and sub-directories if directed by the user) and output how many packets in each file matches a given * search criteria. This method outputs how many directories were searched, how many files were searched and how many packets were matched */ void searchtDirectories(std::string directory, bool includeSubDirectories, std::string searchCriteria, std::ofstream* detailedReportFile, std::map<std::string, bool> extensionsToSearch, int& totalDirSearched, int& totalFilesSearched, int& totalPacketsFound) { // open the directory DIR *dir = opendir(directory.c_str()); struct dirent *entry = readdir(dir); std::vector<std::string> pcapList; // go over all files in this directory while (entry != NULL) { std::string name(entry->d_name); std::string dirPath = directory + DIR_SEPARATOR + name; struct stat info; // get file attributes if (stat(dirPath.c_str(), &info) != 0) { entry = readdir(dir); continue; } // if the file is not a directory if (!(info.st_mode & S_IFDIR)) { // check if the file extension matches the requested extensions to search. If it does, put the file name in a list of files // that should be searched (don't do the search just yet) if (extensionsToSearch.find(getExtension(name)) != extensionsToSearch.end()) pcapList.push_back(dirPath); entry = readdir(dir); continue; } // if the file is a '.' or '..' skip it if (name == "." || name == "..") { entry = readdir(dir); continue; } // if we got to here it means the file is actually a directory. If required to search sub-directories, call this method recursively to search // inside this sub-directory if (includeSubDirectories) searchtDirectories(dirPath, true, searchCriteria, detailedReportFile, extensionsToSearch, totalDirSearched, totalFilesSearched, totalPacketsFound); // move to the next file entry = readdir(dir); } // close dir closedir(dir); totalDirSearched++; // when we get to here we already covered all sub-directories and collected all the files in this directory that are required for search // go over each such file and search its packets to find the search criteria for (std::vector<std::string>::iterator iter = pcapList.begin(); iter != pcapList.end(); iter++) { // do the actual search int packetsFound = searchPcap(*iter, searchCriteria, detailedReportFile); // add to total matched packets totalFilesSearched++; if (packetsFound > 0) { printf("%d packets found in '%s'\n", packetsFound, iter->c_str()); totalPacketsFound += packetsFound; } } } /** * main method of this utility */ int main(int argc, char* argv[]) { std::string inputDirectory = ""; std::string searchCriteria = ""; bool includeSubDirectories = true; std::string detailedReportFileName = ""; std::map<std::string, bool> extensionsToSearch; // the default (unless set otherwise) is to search in '.pcap' extension only extensionsToSearch["pcap"] = true; int optionIndex = 0; char opt = 0; while((opt = getopt_long (argc, argv, "d:s:r:e:hn", PcapSearchOptions, &optionIndex)) != -1) { switch (opt) { case 0: break; case 'd': inputDirectory = optarg; break; case 'n': includeSubDirectories = false; break; case 's': searchCriteria = optarg; break; case 'r': detailedReportFileName = optarg; break; case 'e': { // read the extension list into the map extensionsToSearch.clear(); std::string extensionsListAsString = std::string(optarg); std::stringstream stream(extensionsListAsString); std::string extension; // break comma-separated string into string list while(std::getline(stream, extension, ',')) { // add the extension into the map if it doesn't already exist if (extensionsToSearch.find(extension) == extensionsToSearch.end()) extensionsToSearch[extension] = true; } // verify list is not empty if (extensionsToSearch.empty()) { EXIT_WITH_ERROR("Couldn't parse extensions list"); } break; } case 'h': printUsage(); break; default: printUsage(); exit(-1); } } if (inputDirectory == "") { EXIT_WITH_ERROR("Input directory was not given"); } if (searchCriteria == "") { EXIT_WITH_ERROR("Search criteria was not given"); } DIR *dir = opendir(inputDirectory.c_str()); if (dir == NULL) { EXIT_WITH_ERROR("Cannot find or open input directory"); } // verify the search criteria is a valid BPF filter if (!pcpp::IPcapDevice::verifyFilter(searchCriteria)) { EXIT_WITH_ERROR("Search criteria isn't valid"); } // open the detailed report file if requested by the user std::ofstream* detailedReportFile = NULL; if (detailedReportFileName != "") { detailedReportFile = new std::ofstream(); detailedReportFile->open(detailedReportFileName.c_str()); if (detailedReportFile->fail()) { EXIT_WITH_ERROR("Couldn't open detailed report file '%s' for writing", detailedReportFileName.c_str()); } // in cases where the user requests a detailed report, all errors will be written to the report also. That's why we need to save the error messages // to a variable and write them to the report file later pcpp::LoggerPP::getInstance().setErrorString(errorString, ERROR_STRING_LEN); } printf("Searching...\n"); int totalDirSearched = 0; int totalFilesSearched = 0; int totalPacketsFound = 0; // the main call - start searching! searchtDirectories(inputDirectory, includeSubDirectories, searchCriteria, detailedReportFile, extensionsToSearch, totalDirSearched, totalFilesSearched, totalPacketsFound); // after search is done, close the report file and delete its instance printf("\n\nDone! Searched %d files in %d directories, %d packets were matched to search criteria\n", totalFilesSearched, totalDirSearched, totalPacketsFound); if (detailedReportFile != NULL) { if (detailedReportFile->is_open()) detailedReportFile->close(); delete detailedReportFile; printf("Detailed report written to '%s'\n", detailedReportFileName.c_str()); } return 0; } <commit_msg>Bugfixes in PcapSearch<commit_after>/** * PcapSearch application * ====================== * This application searches all pcap files in a given directory and all its sub-directories (unless stated otherwise) and outputs how many and which * packets in those files match a certain pattern given by the user. The pattern is given in Berkeley Packet Filter (BPF) syntax * (http://biot.com/capstats/bpf.html). For example: if running the application with the following parameters: * PcapSearch.exe -d C:\ -s "ip net 1.1.1.1" -r C:\report.txt * The application will search all '.pcap' files in all directories under C drive and try to match packets that matches IP 1.1.1.1. The result will be * printed to stdout and a more detailed report will be printed to c:\report.txt * Output example: * 1 packets found in 'C:\\path\example\Dns.pcap' * 5 packets found in 'C:\\path\example\bla1\my_pcap2.pcap' * 7299 packets found in 'C:\\path2\example\example2\big_pcap.pcap' * 7435 packets found in 'C:\\path3\dir1\dir2\dir3\dir4\another.pcap' * 435 packets found in 'C:\\path3\dirx\diry\dirz\ok.pcap' * 4662 packets found in 'C:\\path4\gotit.pcap' * 7299 packets found in 'C:\\enough.pcap' * * There are switches that allows the user to search only in the provided folder (without sub-directories), search user-defined file extensions (sometimes * pcap files have an extension which is not '.pcap'), and output or not output the detailed report * * For more details about modes of operation and parameters please run PcapSearch -h */ #include <stdlib.h> #include <getopt.h> #include <iostream> #include <fstream> #include <sstream> #include <sys/stat.h> #include <dirent.h> #include <vector> #include <map> #include <Logger.h> #include <RawPacket.h> #include <Packet.h> #include <PcapFileDevice.h> using namespace pcpp; static struct option PcapSearchOptions[] = { {"input-dir", required_argument, 0, 'd'}, {"not-include-sub-dir", no_argument, 0, 'n'}, {"search", required_argument, 0, 's'}, {"detailed-report", required_argument, 0, 'r'}, {"set-extensions", required_argument, 0, 'e'}, {"help", no_argument, 0, 'h'}, {0, 0, 0, 0} }; #define EXIT_WITH_ERROR(reason, ...) do { \ printf("\nError: " reason "\n\n", ## __VA_ARGS__); \ printUsage(); \ exit(1); \ } while(0) #ifdef WIN32 #define DIR_SEPARATOR "\\" #else #define DIR_SEPARATOR "/" #endif #define ERROR_STRING_LEN 500 char errorString[ERROR_STRING_LEN]; /** * Print application usage */ void printUsage() { printf("\nUsage:\n" "-------\n" "PcapPrinter [-h] [-n] [-r file_name] [-e extension_list] -d directory -s search_criteria\n" "\nOptions:\n\n" " -d directory : Input directory\n" " -n : Don't include sub-directories (default is include them)\n" " -s search_criteria : Criteria to search in Berkeley Packet Filter (BPF) syntax (http://biot.com/capstats/bpf.html) i.e: 'ip net 1.1.1.1'\n" " -r file_name : Write a detailed search report to a file\n" " -e extension_list : Set file extensions to search. The default is searching '.pcap' files only.\n" " extnesions_list should be a comma-separated list of extensions, for example: pcap,net,dmp\n" " -h : Displays this help message and exits\n"); exit(0); } /* * Returns the extension of a given file name */ std::string getExtension(std::string fileName) { return fileName.substr(fileName.find_last_of(".") + 1); } /** * Searches all packet in a given pcap file for a certain search criteria. Returns how many packets matched the seatch criteria */ int searchPcap(std::string pcapFilePath, std::string searchCriteria, std::ofstream* detailedReportFile) { // create the pcap reader PcapFileReaderDevice reader(pcapFilePath.c_str()); // if the reader fails to open if (!reader.open()) { if (detailedReportFile != NULL) { // PcapPlusPlus writes the error to the error string variable we set it to write to // write this error to the report file (*detailedReportFile) << "File '" << pcapFilePath << "':" << std::endl; (*detailedReportFile) << " "; std::string errorStr = errorString; (*detailedReportFile) << errorStr << std::endl; } return 0; } // set the filter for the file so only packets that match the search criteria will be read if (!reader.setFilter(searchCriteria)) { return 0; } if (detailedReportFile != NULL) { (*detailedReportFile) << "File '" << pcapFilePath << "':" << std::endl; } int packetCount = 0; RawPacket rawPacket; // read packets from the file. Since we already set the filter, only packets that matches the filter will be read while (reader.getNextPacket(rawPacket)) { // if a detailed report is required, parse the packet and print it to the report file if (detailedReportFile != NULL) { // parse the packet Packet parsedPacket(&rawPacket); // print layer by layer by layer as we want to add a few spaces before each layer std::vector<std::string> packetLayers; parsedPacket.printToStringList(packetLayers); for (std::vector<std::string>::iterator iter = packetLayers.begin(); iter != packetLayers.end(); iter++) (*detailedReportFile) << "\n " << (*iter); (*detailedReportFile) << std::endl; } // count the packet read packetCount++; } // close the reader file reader.close(); // finalize the report if (detailedReportFile != NULL) { if (packetCount > 0) (*detailedReportFile) << "\n"; (*detailedReportFile) << " ----> Found " << packetCount << " packets" << std::endl << std::endl; } // return how many packets matched the search criteria return packetCount; } /** * Searches all pcap files in given directory (and sub-directories if directed by the user) and output how many packets in each file matches a given * search criteria. This method outputs how many directories were searched, how many files were searched and how many packets were matched */ void searchtDirectories(std::string directory, bool includeSubDirectories, std::string searchCriteria, std::ofstream* detailedReportFile, std::map<std::string, bool> extensionsToSearch, int& totalDirSearched, int& totalFilesSearched, int& totalPacketsFound) { // open the directory DIR *dir = opendir(directory.c_str()); // dir is null usually when user has no access permissions if (dir == NULL) return; struct dirent *entry = readdir(dir); std::vector<std::string> pcapList; // go over all files in this directory while (entry != NULL) { std::string name(entry->d_name); std::string dirPath = directory + DIR_SEPARATOR + name; struct stat info; // get file attributes if (stat(dirPath.c_str(), &info) != 0) { entry = readdir(dir); continue; } // if the file is not a directory if (!(info.st_mode & S_IFDIR)) { // check if the file extension matches the requested extensions to search. If it does, put the file name in a list of files // that should be searched (don't do the search just yet) if (extensionsToSearch.find(getExtension(name)) != extensionsToSearch.end()) pcapList.push_back(dirPath); entry = readdir(dir); continue; } // if the file is a '.' or '..' skip it if (name == "." || name == "..") { entry = readdir(dir); continue; } // if we got to here it means the file is actually a directory. If required to search sub-directories, call this method recursively to search // inside this sub-directory if (includeSubDirectories) searchtDirectories(dirPath, true, searchCriteria, detailedReportFile, extensionsToSearch, totalDirSearched, totalFilesSearched, totalPacketsFound); // move to the next file entry = readdir(dir); } // close dir closedir(dir); totalDirSearched++; // when we get to here we already covered all sub-directories and collected all the files in this directory that are required for search // go over each such file and search its packets to find the search criteria for (std::vector<std::string>::iterator iter = pcapList.begin(); iter != pcapList.end(); iter++) { // do the actual search int packetsFound = searchPcap(*iter, searchCriteria, detailedReportFile); // add to total matched packets totalFilesSearched++; if (packetsFound > 0) { printf("%d packets found in '%s'\n", packetsFound, iter->c_str()); totalPacketsFound += packetsFound; } } } /** * main method of this utility */ int main(int argc, char* argv[]) { std::string inputDirectory = ""; std::string searchCriteria = ""; bool includeSubDirectories = true; std::string detailedReportFileName = ""; std::map<std::string, bool> extensionsToSearch; // the default (unless set otherwise) is to search in '.pcap' extension only extensionsToSearch["pcap"] = true; int optionIndex = 0; char opt = 0; while((opt = getopt_long (argc, argv, "d:s:r:e:hn", PcapSearchOptions, &optionIndex)) != -1) { switch (opt) { case 0: break; case 'd': inputDirectory = optarg; break; case 'n': includeSubDirectories = false; break; case 's': searchCriteria = optarg; break; case 'r': detailedReportFileName = optarg; break; case 'e': { // read the extension list into the map extensionsToSearch.clear(); std::string extensionsListAsString = std::string(optarg); std::stringstream stream(extensionsListAsString); std::string extension; // break comma-separated string into string list while(std::getline(stream, extension, ',')) { // add the extension into the map if it doesn't already exist if (extensionsToSearch.find(extension) == extensionsToSearch.end()) extensionsToSearch[extension] = true; } // verify list is not empty if (extensionsToSearch.empty()) { EXIT_WITH_ERROR("Couldn't parse extensions list"); } break; } case 'h': printUsage(); break; default: printUsage(); exit(-1); } } if (inputDirectory == "") { EXIT_WITH_ERROR("Input directory was not given"); } if (searchCriteria == "") { EXIT_WITH_ERROR("Search criteria was not given"); } DIR *dir = opendir(inputDirectory.c_str()); if (dir == NULL) { EXIT_WITH_ERROR("Cannot find or open input directory"); } // verify the search criteria is a valid BPF filter if (!pcpp::IPcapDevice::verifyFilter(searchCriteria)) { EXIT_WITH_ERROR("Search criteria isn't valid"); } // open the detailed report file if requested by the user std::ofstream* detailedReportFile = NULL; if (detailedReportFileName != "") { detailedReportFile = new std::ofstream(); detailedReportFile->open(detailedReportFileName.c_str()); if (detailedReportFile->fail()) { EXIT_WITH_ERROR("Couldn't open detailed report file '%s' for writing", detailedReportFileName.c_str()); } // in cases where the user requests a detailed report, all errors will be written to the report also. That's why we need to save the error messages // to a variable and write them to the report file later pcpp::LoggerPP::getInstance().setErrorString(errorString, ERROR_STRING_LEN); } printf("Searching...\n"); int totalDirSearched = 0; int totalFilesSearched = 0; int totalPacketsFound = 0; // if input dir contains a directory separator at the end, remove it std::string dirSep = DIR_SEPARATOR; if (0 == inputDirectory.compare(inputDirectory.length() - dirSep.length(), dirSep.length(), dirSep)) { inputDirectory = inputDirectory.substr(0, inputDirectory.size()-1); } // the main call - start searching! searchtDirectories(inputDirectory, includeSubDirectories, searchCriteria, detailedReportFile, extensionsToSearch, totalDirSearched, totalFilesSearched, totalPacketsFound); // after search is done, close the report file and delete its instance printf("\n\nDone! Searched %d files in %d directories, %d packets were matched to search criteria\n", totalFilesSearched, totalDirSearched, totalPacketsFound); if (detailedReportFile != NULL) { if (detailedReportFile->is_open()) detailedReportFile->close(); delete detailedReportFile; printf("Detailed report written to '%s'\n", detailedReportFileName.c_str()); } return 0; } <|endoftext|>
<commit_before>#include "FPSCounter.h" #include "../Application.h" #include "../FSE-ImGui/imgui-plotvar.h" #include <rttr/registration> namespace fse { FPSCounter::FPSCounter(Scene* scene) : FPSCounter(scene, sf::Vector2f(0, 0)) { } FPSCounter::FPSCounter(Scene* scene, const sf::Vector2f& spawnPos) : FSEObject(scene, spawnPos) { font_.loadFromFile("./data/fonts/bitstream-vera/VeraMoBd.ttf"); fps_text_.setFont(font_); fps_text_.setFillColor(sf::Color::Green); fps_text_.setString(L"FPS: 0"); fps_text_.setCharacterSize(16); sf::FloatRect rekt = fps_text_.getLocalBounds(); background_.setSize(sf::Vector2f(rekt.width + 10, rekt.height + 10)); background_.setPosition(rekt.left - 10, rekt.top - 10); background_.setFillColor(sf::Color(0, 0, 0, 128)); setZOrder(257); counter_view_ = sf::View(sf::FloatRect(0.f, 0.f, static_cast<float>(scene_->getApplication()->getWindow()->getSize().x), static_cast<float>(scene_->getApplication()->getWindow()->getSize().y))); on_resize_connection_ = scene_->getApplication()->on_window_resized_.connect([this]() { counter_view_ = sf::View(sf::FloatRect(0.f, 0.f, static_cast<float>(scene_->getApplication()->getWindow()->getSize().x), static_cast<float>(scene_->getApplication()->getWindow()->getSize().y))); }); } FPSCounter::~FPSCounter() { scene_->getApplication()->on_window_resized_.disconnect(on_resize_connection_); } void FPSCounter::update(float deltaTime) { } void FPSCounter::draw(sf::RenderTarget& target) { current_time_ = measureclock_.restart().asSeconds(); fps_ = (fps_ * smoothing_) + ((1.f / current_time_) * (1.f - smoothing_)); if (!detailed_view_) { if (updclock_.getElapsedTime().asMilliseconds() > 250) { fps_text_.setString(std::wstring(L"FPS: " + std::to_wstring(static_cast<int>((fps_ + last_fps_) / 2.f)))); last_fps_ = fps_; sf::FloatRect rekt = fps_text_.getLocalBounds(); background_.setSize(sf::Vector2f(rekt.width + 10, rekt.height + 10)); background_.setPosition(rekt.left - 5, rekt.top - 5); updclock_.restart(); } sf::View origView = target.getView(); target.setView(counter_view_); target.draw(background_); target.draw(fps_text_); target.setView(origView); } else { ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0); ImGui::PushStyleColor(ImGuiCol_WindowBg, ImVec4(0.f, 0.f, 0.f, 0.5f)); ImGui::PushStyleColor(ImGuiCol_FrameBg, ImVec4(0.f, 0.f, 0.f, 0.0f)); ImGui::Begin("##FPSDetailed", nullptr, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoTitleBar); ImGui::SetWindowPos(ImVec2(0, 0)); if (updclock_.getElapsedTime().asSeconds() > 1) { ImGui::PlotVarFlushOldEntries(); updclock_.restart(); } ImGui::PlotVar("FPS", fps_, 0, 250, 250); ImGui::PlotVar("Frametime", current_time_, 0, 0.1f, 250); ImGui::End(); ImGui::PopStyleColor(2); ImGui::PopStyleVar(); } } void FPSCounter::spawned() { } void FPSCounter::setShowDetailed(bool detailed) { detailed_view_ = detailed; } bool FPSCounter::isDetailed() const { return detailed_view_; } } RTTR_REGISTRATION { using namespace rttr; using namespace fse; registration::class_<FPSCounter>("fse::FPSCounter") .property("detailed_view_", &FPSCounter::detailed_view_) ; } <commit_msg>Fix fps counter on android / Disable ImGui (SFML SUCKS)<commit_after>#include "FPSCounter.h" #include "../Application.h" #include "../FSE-ImGui/imgui-plotvar.h" #include <rttr/registration> namespace fse { FPSCounter::FPSCounter(Scene* scene) : FPSCounter(scene, sf::Vector2f(0, 0)) { } FPSCounter::FPSCounter(Scene* scene, const sf::Vector2f& spawnPos) : FSEObject(scene, spawnPos) { font_.loadFromFile("data/fonts/bitstream-vera/VeraMoBd.ttf"); fps_text_.setFont(font_); fps_text_.setFillColor(sf::Color::Green); fps_text_.setString(L"FPS: 0"); fps_text_.setCharacterSize(16); sf::FloatRect rekt = fps_text_.getLocalBounds(); background_.setSize(sf::Vector2f(rekt.width + 10, rekt.height + 10)); background_.setPosition(rekt.left - 10, rekt.top - 10); background_.setFillColor(sf::Color(0, 0, 0, 128)); setZOrder(257); counter_view_ = sf::View(sf::FloatRect(0.f, 0.f, static_cast<float>(scene_->getApplication()->getWindow()->getSize().x), static_cast<float>(scene_->getApplication()->getWindow()->getSize().y))); on_resize_connection_ = scene_->getApplication()->on_window_resized_.connect([this]() { counter_view_ = sf::View(sf::FloatRect(0.f, 0.f, static_cast<float>(scene_->getApplication()->getWindow()->getSize().x), static_cast<float>(scene_->getApplication()->getWindow()->getSize().y))); }); } FPSCounter::~FPSCounter() { scene_->getApplication()->on_window_resized_.disconnect(on_resize_connection_); } void FPSCounter::update(float deltaTime) { } void FPSCounter::draw(sf::RenderTarget& target) { current_time_ = measureclock_.restart().asSeconds(); fps_ = (fps_ * smoothing_) + ((1.f / current_time_) * (1.f - smoothing_)); if (!detailed_view_) { if (updclock_.getElapsedTime().asMilliseconds() > 250) { fps_text_.setString(std::wstring(L"FPS: " + std::to_wstring(static_cast<int>((fps_ + last_fps_) / 2.f)))); last_fps_ = fps_; sf::FloatRect rekt = fps_text_.getLocalBounds(); background_.setSize(sf::Vector2f(rekt.width + 10, rekt.height + 10)); background_.setPosition(rekt.left - 5, rekt.top - 5); updclock_.restart(); } sf::View origView = target.getView(); target.setView(counter_view_); target.draw(background_); target.draw(fps_text_); target.setView(origView); } else { ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0); ImGui::PushStyleColor(ImGuiCol_WindowBg, ImVec4(0.f, 0.f, 0.f, 0.5f)); ImGui::PushStyleColor(ImGuiCol_FrameBg, ImVec4(0.f, 0.f, 0.f, 0.0f)); ImGui::Begin("##FPSDetailed", nullptr, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoTitleBar); ImGui::SetWindowPos(ImVec2(0, 0)); if (updclock_.getElapsedTime().asSeconds() > 1) { ImGui::PlotVarFlushOldEntries(); updclock_.restart(); } ImGui::PlotVar("FPS", fps_, 0, 250, 250); ImGui::PlotVar("Frametime", current_time_, 0, 0.1f, 250); ImGui::End(); ImGui::PopStyleColor(2); ImGui::PopStyleVar(); } } void FPSCounter::spawned() { } void FPSCounter::setShowDetailed(bool detailed) { #ifdef ANDROID detailed_view_ = false; #else detailed_view_ = detailed; #endif } bool FPSCounter::isDetailed() const { return detailed_view_; } } RTTR_REGISTRATION { using namespace rttr; using namespace fse; registration::class_<FPSCounter>("fse::FPSCounter") .property("detailed_view_", &FPSCounter::detailed_view_) ; } <|endoftext|>
<commit_before>#include "Destination.h" #include "Identity.h" #include "ClientContext.h" #include "I2PService.h" namespace i2p { namespace client { static const i2p::data::SigningKeyType I2P_SERVICE_DEFAULT_KEY_TYPE = i2p::data::SIGNING_KEY_TYPE_ECDSA_SHA256_P256; I2PService::I2PService (std::shared_ptr<ClientDestination> localDestination): m_LocalDestination (localDestination ? localDestination : i2p::client::context.CreateNewLocalDestination (false, I2P_SERVICE_DEFAULT_KEY_TYPE)) { } I2PService::I2PService (i2p::data::SigningKeyType kt): m_LocalDestination (i2p::client::context.CreateNewLocalDestination (false, kt)) { } void I2PService::CreateStream (StreamRequestComplete streamRequestComplete, const std::string& dest, int port) { assert(streamRequestComplete); i2p::data::IdentHash identHash; if (i2p::client::context.GetAddressBook ().GetIdentHash (dest, identHash)) m_LocalDestination->CreateStream (streamRequestComplete, identHash, port); else { LogPrint (eLogWarning, "I2PService: Remote destination ", dest, " not found"); streamRequestComplete (nullptr); } } TCPIPPipe::TCPIPPipe(I2PService * owner, std::shared_ptr<boost::asio::ip::tcp::socket> upstream, std::shared_ptr<boost::asio::ip::tcp::socket> downstream) : I2PServiceHandler(owner), m_up(upstream), m_down(downstream) {} TCPIPPipe::~TCPIPPipe() { Terminate(); } void TCPIPPipe::Start() { AsyncReceiveUpstream(); AsyncReceiveDownstream(); } void TCPIPPipe::Terminate() { if(Kill()) return; Done(shared_from_this()); if (m_up) { if (m_up->is_open()) { m_up->close(); } m_up = nullptr; } if (m_down) { if (m_down->is_open()) { m_down->close(); } m_down = nullptr; } } void TCPIPPipe::AsyncReceiveUpstream() { if (m_up) { m_up->async_read_some(boost::asio::buffer(m_upstream_to_down_buf, TCP_IP_PIPE_BUFFER_SIZE), std::bind(&TCPIPPipe::HandleUpstreamReceived, shared_from_this(), std::placeholders::_1, std::placeholders::_2)); } else { LogPrint(eLogError, "TCPIPPipe: no upstream socket for read"); } } void TCPIPPipe::AsyncReceiveDownstream() { if (m_down) { m_down->async_read_some(boost::asio::buffer(m_downstream_to_up_buf, TCP_IP_PIPE_BUFFER_SIZE), std::bind(&TCPIPPipe::HandleDownstreamReceived, shared_from_this(), std::placeholders::_1, std::placeholders::_2)); } else { LogPrint(eLogError, "TCPIPPipe: no downstream socket for read"); } } void TCPIPPipe::UpstreamWrite(const uint8_t * buf, size_t len) { if (m_up) { LogPrint(eLogDebug, "TCPIPPipe: write upstream ", (int)len); boost::asio::async_write(*m_up, boost::asio::buffer(buf, len), boost::asio::transfer_all(), std::bind(&TCPIPPipe::HandleUpstreamWrite, shared_from_this(), std::placeholders::_1) ); } else { LogPrint(eLogError, "tcpip pipe upstream socket null"); } } void TCPIPPipe::DownstreamWrite(const uint8_t * buf, size_t len) { if (m_down) { LogPrint(eLogDebug, "TCPIPPipe: write downstream ", (int)len); boost::asio::async_write(*m_down, boost::asio::buffer(buf, len), boost::asio::transfer_all(), std::bind(&TCPIPPipe::HandleDownstreamWrite, shared_from_this(), std::placeholders::_1) ); } else { LogPrint(eLogError, "tcpip pipe downstream socket null"); } } void TCPIPPipe::HandleDownstreamReceived(const boost::system::error_code & ecode, std::size_t bytes_transfered) { LogPrint(eLogDebug, "TCPIPPipe downstream got ", (int) bytes_transfered); if (ecode) { LogPrint(eLogError, "TCPIPPipe Downstream read error:" , ecode.message()); if (ecode != boost::asio::error::operation_aborted) Terminate(); } else { if (bytes_transfered > 0 ) { memcpy(m_upstream_buf, m_downstream_to_up_buf, bytes_transfered); UpstreamWrite(m_upstream_buf, bytes_transfered); } AsyncReceiveDownstream(); } } void TCPIPPipe::HandleDownstreamWrite(const boost::system::error_code & ecode) { if (ecode) { LogPrint(eLogError, "TCPIPPipe Downstream write error:" , ecode.message()); if (ecode != boost::asio::error::operation_aborted) Terminate(); } } void TCPIPPipe::HandleUpstreamWrite(const boost::system::error_code & ecode) { if (ecode) { LogPrint(eLogError, "TCPIPPipe Upstream write error:" , ecode.message()); if (ecode != boost::asio::error::operation_aborted) Terminate(); } } void TCPIPPipe::HandleUpstreamReceived(const boost::system::error_code & ecode, std::size_t bytes_transfered) { LogPrint(eLogDebug, "TCPIPPipe upstream got ", (int) bytes_transfered); if (ecode) { LogPrint(eLogError, "TCPIPPipe Upstream read error:" , ecode.message()); if (ecode != boost::asio::error::operation_aborted) Terminate(); } else { if (bytes_transfered > 0 ) { memcpy(m_upstream_buf, m_upstream_to_down_buf, bytes_transfered); DownstreamWrite(m_upstream_buf, bytes_transfered); } AsyncReceiveUpstream(); } } void TCPIPAcceptor::Start () { m_Acceptor.listen (); Accept (); } void TCPIPAcceptor::Stop () { m_Acceptor.close(); m_Timer.cancel (); ClearHandlers(); } void TCPIPAcceptor::Accept () { auto newSocket = std::make_shared<boost::asio::ip::tcp::socket> (GetService ()); m_Acceptor.async_accept (*newSocket, std::bind (&TCPIPAcceptor::HandleAccept, this, std::placeholders::_1, newSocket)); } void TCPIPAcceptor::HandleAccept (const boost::system::error_code& ecode, std::shared_ptr<boost::asio::ip::tcp::socket> socket) { if (!ecode) { LogPrint(eLogDebug, "I2PService: ", GetName(), " accepted"); auto handler = CreateHandler(socket); if (handler) { AddHandler(handler); handler->Handle(); } else socket->close(); Accept(); } else { if (ecode != boost::asio::error::operation_aborted) LogPrint (eLogError, "I2PService: ", GetName(), " closing socket on accept because: ", ecode.message ()); } } } } <commit_msg>* I2PService.cpp: tune logs<commit_after>#include "Destination.h" #include "Identity.h" #include "ClientContext.h" #include "I2PService.h" namespace i2p { namespace client { static const i2p::data::SigningKeyType I2P_SERVICE_DEFAULT_KEY_TYPE = i2p::data::SIGNING_KEY_TYPE_ECDSA_SHA256_P256; I2PService::I2PService (std::shared_ptr<ClientDestination> localDestination): m_LocalDestination (localDestination ? localDestination : i2p::client::context.CreateNewLocalDestination (false, I2P_SERVICE_DEFAULT_KEY_TYPE)) { } I2PService::I2PService (i2p::data::SigningKeyType kt): m_LocalDestination (i2p::client::context.CreateNewLocalDestination (false, kt)) { } void I2PService::CreateStream (StreamRequestComplete streamRequestComplete, const std::string& dest, int port) { assert(streamRequestComplete); i2p::data::IdentHash identHash; if (i2p::client::context.GetAddressBook ().GetIdentHash (dest, identHash)) m_LocalDestination->CreateStream (streamRequestComplete, identHash, port); else { LogPrint (eLogWarning, "I2PService: Remote destination ", dest, " not found"); streamRequestComplete (nullptr); } } TCPIPPipe::TCPIPPipe(I2PService * owner, std::shared_ptr<boost::asio::ip::tcp::socket> upstream, std::shared_ptr<boost::asio::ip::tcp::socket> downstream) : I2PServiceHandler(owner), m_up(upstream), m_down(downstream) {} TCPIPPipe::~TCPIPPipe() { Terminate(); } void TCPIPPipe::Start() { AsyncReceiveUpstream(); AsyncReceiveDownstream(); } void TCPIPPipe::Terminate() { if(Kill()) return; Done(shared_from_this()); if (m_up) { if (m_up->is_open()) { m_up->close(); } m_up = nullptr; } if (m_down) { if (m_down->is_open()) { m_down->close(); } m_down = nullptr; } } void TCPIPPipe::AsyncReceiveUpstream() { if (m_up) { m_up->async_read_some(boost::asio::buffer(m_upstream_to_down_buf, TCP_IP_PIPE_BUFFER_SIZE), std::bind(&TCPIPPipe::HandleUpstreamReceived, shared_from_this(), std::placeholders::_1, std::placeholders::_2)); } else { LogPrint(eLogError, "TCPIPPipe: upstream receive: no socket"); } } void TCPIPPipe::AsyncReceiveDownstream() { if (m_down) { m_down->async_read_some(boost::asio::buffer(m_downstream_to_up_buf, TCP_IP_PIPE_BUFFER_SIZE), std::bind(&TCPIPPipe::HandleDownstreamReceived, shared_from_this(), std::placeholders::_1, std::placeholders::_2)); } else { LogPrint(eLogError, "TCPIPPipe: downstream receive: no socket"); } } void TCPIPPipe::UpstreamWrite(const uint8_t * buf, size_t len) { if (m_up) { LogPrint(eLogDebug, "TCPIPPipe: upstream: ", (int) len, " bytes written"); boost::asio::async_write(*m_up, boost::asio::buffer(buf, len), boost::asio::transfer_all(), std::bind(&TCPIPPipe::HandleUpstreamWrite, shared_from_this(), std::placeholders::_1) ); } else { LogPrint(eLogError, "TCPIPPipe: upstream write: no socket"); } } void TCPIPPipe::DownstreamWrite(const uint8_t * buf, size_t len) { if (m_down) { LogPrint(eLogDebug, "TCPIPPipe: downstream: ", (int) len, " bytes written"); boost::asio::async_write(*m_down, boost::asio::buffer(buf, len), boost::asio::transfer_all(), std::bind(&TCPIPPipe::HandleDownstreamWrite, shared_from_this(), std::placeholders::_1) ); } else { LogPrint(eLogError, "TCPIPPipe: downstream write: no socket"); } } void TCPIPPipe::HandleDownstreamReceived(const boost::system::error_code & ecode, std::size_t bytes_transfered) { LogPrint(eLogDebug, "TCPIPPipe: downstream: ", (int) bytes_transfered, " bytes received"); if (ecode) { LogPrint(eLogError, "TCPIPPipe: downstream read error:" , ecode.message()); if (ecode != boost::asio::error::operation_aborted) Terminate(); } else { if (bytes_transfered > 0 ) { memcpy(m_upstream_buf, m_downstream_to_up_buf, bytes_transfered); UpstreamWrite(m_upstream_buf, bytes_transfered); } AsyncReceiveDownstream(); } } void TCPIPPipe::HandleDownstreamWrite(const boost::system::error_code & ecode) { if (ecode) { LogPrint(eLogError, "TCPIPPipe: downstream write error:" , ecode.message()); if (ecode != boost::asio::error::operation_aborted) Terminate(); } } void TCPIPPipe::HandleUpstreamWrite(const boost::system::error_code & ecode) { if (ecode) { LogPrint(eLogError, "TCPIPPipe: upstream write error:" , ecode.message()); if (ecode != boost::asio::error::operation_aborted) Terminate(); } } void TCPIPPipe::HandleUpstreamReceived(const boost::system::error_code & ecode, std::size_t bytes_transfered) { LogPrint(eLogDebug, "TCPIPPipe: upstream ", (int) bytes_transfered, , " bytes received"); if (ecode) { LogPrint(eLogError, "TCPIPPipe: upstream read error:" , ecode.message()); if (ecode != boost::asio::error::operation_aborted) Terminate(); } else { if (bytes_transfered > 0 ) { memcpy(m_upstream_buf, m_upstream_to_down_buf, bytes_transfered); DownstreamWrite(m_upstream_buf, bytes_transfered); } AsyncReceiveUpstream(); } } void TCPIPAcceptor::Start () { m_Acceptor.listen (); Accept (); } void TCPIPAcceptor::Stop () { m_Acceptor.close(); m_Timer.cancel (); ClearHandlers(); } void TCPIPAcceptor::Accept () { auto newSocket = std::make_shared<boost::asio::ip::tcp::socket> (GetService ()); m_Acceptor.async_accept (*newSocket, std::bind (&TCPIPAcceptor::HandleAccept, this, std::placeholders::_1, newSocket)); } void TCPIPAcceptor::HandleAccept (const boost::system::error_code& ecode, std::shared_ptr<boost::asio::ip::tcp::socket> socket) { if (!ecode) { LogPrint(eLogDebug, "I2PService: ", GetName(), " accepted"); auto handler = CreateHandler(socket); if (handler) { AddHandler(handler); handler->Handle(); } else socket->close(); Accept(); } else { if (ecode != boost::asio::error::operation_aborted) LogPrint (eLogError, "I2PService: ", GetName(), " closing socket on accept because: ", ecode.message ()); } } } } <|endoftext|>
<commit_before>#include "compute/edflib.h" #include "compute/eeg_spectrogram.h" #include "json11/json11.hpp" #include "wslib/server_ws.hpp" using namespace std; using namespace SimpleWeb; using namespace json11; #define NUM_THREADS 4 #define PORT 8080 #define TEXT_OPCODE 129 #define BINARY_OPCODE 130 void send_message(SocketServer<WS>* server, shared_ptr<SocketServer<WS>::Connection> connection, std::string msg_type, Json content, float* data, size_t data_size) { Json msg = Json::object { {"type", msg_type}, {"content", content} }; std::string header = msg.dump(); uint32_t header_len = header.size() + (8 - ((header.size() + 4) % 8)); // append enough spaces so that the payload starts at an 8-byte // aligned position. The first four bytes will be the length of // the header, encoded as a 32 bit signed integer: header.resize(header_len, ' '); stringstream data_ss; data_ss.write((char*) &header_len, sizeof(uint32_t)); data_ss.write(header.c_str(), header_len); if (data != NULL) { data_ss.write((char*) data, data_size); } // server.send is an asynchronous function server->send(connection, data_ss, [&data](const boost::system::error_code & ec) { if (ec) { cout << "Server: Error sending message. " << //See http://www.boost.org/doc/libs/1_55_0/doc/html/boost_asio/reference.html, Error Codes for error code meanings "Error: " << ec << ", error message: " << ec.message() << endl; } }, BINARY_OPCODE); } void send_spectrogram_new(SocketServer<WS>* server, shared_ptr<SocketServer<WS>::Connection> connection, spec_params_t spec_params, std::string canvasId) { Json content = Json::object { {"action", "new"}, {"nblocks", spec_params.nblocks}, {"nfreqs", spec_params.nfreqs}, {"fs", spec_params.fs}, {"length", spec_params.spec_len}, {"canvasId", canvasId} }; cout << "Sending content " << content.dump() << endl; send_message(server, connection, "spectrogram", content, NULL, -1); } void send_spectrogram_update(SocketServer<WS>* server, shared_ptr<SocketServer<WS>::Connection> connection, spec_params_t spec_params, std::string canvasId, float * spec, size_t data_size) { Json content = Json::object { {"action", "update"}, {"nblocks", spec_params.nblocks}, {"nfreqs", spec_params.nfreqs}, {"canvasId", canvasId} }; cout << "Sending content " << content.dump() << endl; send_message(server, connection, "spectrogram", content, spec, data_size); } void on_file_spectrogram(SocketServer<WS>* server, shared_ptr<SocketServer<WS>::Connection> connection, Json data) { std::string filename = data["filename"].string_value(); float duration = data["duration"].number_value(); spec_params_t spec_params; char *filename_c = new char[filename.length() + 1]; strcpy(filename_c, filename.c_str()); get_eeg_spectrogram_params(&spec_params, filename_c, duration); print_spec_params_t(&spec_params); send_spectrogram_new(server, connection, spec_params, "LL"); size_t data_size = sizeof(float) * spec_params.nblocks * spec_params.nfreqs; float* spec = (float*) malloc(data_size); eeg_spectrogram_handler(&spec_params, LL, spec); send_spectrogram_update(server, connection, spec_params, "LL", spec, data_size); } void receive_message(SocketServer<WS>* server, shared_ptr<SocketServer<WS>::Connection> connection, std::string type, Json content) { if (type == "request_file_spectrogram") { on_file_spectrogram(server, connection, content); } else if (type == "information") { cout << content.string_value() << endl; } else { cout << "Unknown type: " << type << " and content: " << content.string_value() << endl; } } int main() { //WebSocket (WS)-server at PORT using NUM_THREADS threads SocketServer<WS> server(PORT, NUM_THREADS); auto& ws = server.endpoint["^/compute/spectrogram/?$"]; //C++14, lambda parameters declared with auto //For C++11 use: (shared_ptr<SocketServer<WS>::Connection> connection, shared_ptr<SocketServer<WS>::Message> message) ws.onmessage = [&server](auto connection, auto message) { //To receive message from client as string (data_ss.str()) stringstream data_ss; message->data >> data_ss.rdbuf(); std::string data_s, err; data_s = data_ss.str(); Json json = Json::parse(data_s, err); // TODO add error checking for null fields std::string type = json["type"].string_value(); Json content = json["content"]; receive_message(&server, connection, type, content); }; ws.onopen = [](auto connection) { cout << "WebSocket opened" << endl; }; //See RFC 6455 7.4.1. for status codes ws.onclose = [](auto connection, int status, const string & reason) { cout << "Server: Closed connection " << (size_t)connection.get() << " with status code " << status << endl; }; //See http://www.boost.org/doc/libs/1_55_0/doc/html/boost_asio/reference.html, Error Codes for error code meanings ws.onerror = [](auto connection, const boost::system::error_code & ec) { cout << "Server: Error in connection " << (size_t)connection.get() << ". " << "Error: " << ec << ", error message: " << ec.message() << endl; }; thread server_thread([&server]() { cout << "WebSocket Server started at port: " << PORT << endl; //Start WS-server server.start(); }); server_thread.join(); return 0; } <commit_msg>send all spectrograms<commit_after>#include "compute/edflib.h" #include "compute/eeg_spectrogram.h" #include "json11/json11.hpp" #include "wslib/server_ws.hpp" using namespace std; using namespace SimpleWeb; using namespace json11; #define NUM_THREADS 4 #define PORT 8080 #define TEXT_OPCODE 129 #define BINARY_OPCODE 130 const char* CH_ID_MAP[] = {"LL", "LP", "RP", "RL"}; void send_message(SocketServer<WS>* server, shared_ptr<SocketServer<WS>::Connection> connection, std::string msg_type, Json content, float* data, size_t data_size) { Json msg = Json::object { {"type", msg_type}, {"content", content} }; std::string header = msg.dump(); uint32_t header_len = header.size() + (8 - ((header.size() + 4) % 8)); // append enough spaces so that the payload starts at an 8-byte // aligned position. The first four bytes will be the length of // the header, encoded as a 32 bit signed integer: header.resize(header_len, ' '); stringstream data_ss; data_ss.write((char*) &header_len, sizeof(uint32_t)); data_ss.write(header.c_str(), header_len); if (data != NULL) { data_ss.write((char*) data, data_size); } // server.send is an asynchronous function server->send(connection, data_ss, [&data](const boost::system::error_code &ec) { if (ec) { cout << "Server: Error sending message. " << //See http://www.boost.org/doc/libs/1_55_0/doc/html/boost_asio/reference.html, Error Codes for error code meanings "Error: " << ec << ", error message: " << ec.message() << endl; } }, BINARY_OPCODE); } void send_spectrogram_new(SocketServer<WS>* server, shared_ptr<SocketServer<WS>::Connection> connection, spec_params_t spec_params, std::string canvasId) { Json content = Json::object { {"action", "new"}, {"nblocks", spec_params.nblocks}, {"nfreqs", spec_params.nfreqs}, {"fs", spec_params.fs}, {"length", spec_params.spec_len}, {"canvasId", canvasId} }; cout << "Sending content " << content.dump() << endl; send_message(server, connection, "spectrogram", content, NULL, -1); } void send_spectrogram_update(SocketServer<WS>* server, shared_ptr<SocketServer<WS>::Connection> connection, spec_params_t spec_params, std::string canvasId, float * spec, size_t data_size) { Json content = Json::object { {"action", "update"}, {"nblocks", spec_params.nblocks}, {"nfreqs", spec_params.nfreqs}, {"canvasId", canvasId} }; cout << "Sending content " << content.dump() << endl; send_message(server, connection, "spectrogram", content, spec, data_size); } void on_file_spectrogram(SocketServer<WS>* server, shared_ptr<SocketServer<WS>::Connection> connection, Json data) { std::string filename = data["filename"].string_value(); float duration = data["duration"].number_value(); spec_params_t spec_params; char *filename_c = new char[filename.length() + 1]; strcpy(filename_c, filename.c_str()); get_eeg_spectrogram_params(&spec_params, filename_c, duration); print_spec_params_t(&spec_params); size_t data_size = sizeof(float) * spec_params.nblocks * spec_params.nfreqs; const char* ch; for (int ch_id=0; ch_id < NUM_CH; ch_id++) { ch = CH_ID_MAP[ch_id]; send_spectrogram_new(server, connection, spec_params, ch); float* spec = (float*) malloc(data_size); eeg_spectrogram_handler(&spec_params, ch_id, spec); send_spectrogram_update(server, connection, spec_params, ch, spec, data_size); this_thread::sleep_for(chrono::seconds(1)); // TODO(joshblum): fix this.. } close_edf(filename_c); } void receive_message(SocketServer<WS>* server, shared_ptr<SocketServer<WS>::Connection> connection, std::string type, Json content) { if (type == "request_file_spectrogram") { on_file_spectrogram(server, connection, content); } else if (type == "information") { cout << content.string_value() << endl; } else { cout << "Unknown type: " << type << " and content: " << content.string_value() << endl; } } int main() { //WebSocket (WS)-server at PORT using NUM_THREADS threads SocketServer<WS> server(PORT, NUM_THREADS); auto& ws = server.endpoint["^/compute/spectrogram/?$"]; //C++14, lambda parameters declared with auto //For C++11 use: (shared_ptr<SocketServer<WS>::Connection> connection, shared_ptr<SocketServer<WS>::Message> message) ws.onmessage = [&server](auto connection, auto message) { //To receive message from client as string (data_ss.str()) stringstream data_ss; message->data >> data_ss.rdbuf(); std::string data_s, err; data_s = data_ss.str(); Json json = Json::parse(data_s, err); // TODO add error checking for null fields std::string type = json["type"].string_value(); Json content = json["content"]; receive_message(&server, connection, type, content); }; ws.onopen = [](auto connection) { cout << "WebSocket opened" << endl; }; //See RFC 6455 7.4.1. for status codes ws.onclose = [](auto connection, int status, const string & reason) { cout << "Server: Closed connection " << (size_t)connection.get() << " with status code " << status << endl; }; //See http://www.boost.org/doc/libs/1_55_0/doc/html/boost_asio/reference.html, Error Codes for error code meanings ws.onerror = [](auto connection, const boost::system::error_code & ec) { cout << "Server: Error in connection " << (size_t)connection.get() << ". " << "Error: " << ec << ", error message: " << ec.message() << endl; }; thread server_thread([&server]() { cout << "WebSocket Server started at port: " << PORT << endl; //Start WS-server server.start(); }); server_thread.join(); return 0; } <|endoftext|>
<commit_before>#include <queso/Environment.h> #include <queso/GslVector.h> #include <queso/GslMatrix.h> #include <queso/VectorSpace.h> #include <queso/BoxSubset.h> #include <queso/UniformVectorRV.h> #include <queso/GaussianVectorRV.h> #include <queso/GaussianJointPdf.h> #include <queso/InvLogitGaussianJointPdf.h> #include <queso/StatisticalInverseProblem.h> template<class V, class M> class Likelihood : public QUESO::BaseScalarFunction<V, M> { public: Likelihood(const char * prefix, const QUESO::VectorSet<V, M> & domain, const QUESO::GaussianJointPdf<V, M> & pdf) : QUESO::BaseScalarFunction<V, M>(prefix, domain), m_pdf(pdf) { } virtual ~Likelihood() { } virtual double lnValue(const V & domainVector, const V * domainDirection, V * gradVector, M * hessianMatrix, V * hessianEffect) const { return this->m_pdf.lnValue(domainVector, NULL, NULL, NULL, NULL); } virtual double actualValue(const V & domainVector, const V * domainDirection, V * gradVector, M * hessianMatrix, V * hessianEffect) const { return std::exp(this->lnValue(domainVector, domainDirection, gradVector, hessianMatrix, hessianEffect)); } const QUESO::GaussianJointPdf<V, M> & m_pdf; }; int main(int argc, char ** argv) { MPI_Init(&argc, &argv); QUESO::FullEnvironment env(MPI_COMM_WORLD, "test_Regression/adaptedcov_input.txt", "", NULL); QUESO::VectorSpace<QUESO::GslVector, QUESO::GslMatrix> paramSpace(env, "param_", 2, NULL); QUESO::GslVector paramMins(paramSpace.zeroVector()); paramMins.cwSet(0.0); QUESO::GslVector paramMaxs(paramSpace.zeroVector()); paramMaxs.cwSet(1.0); QUESO::BoxSubset<QUESO::GslVector, QUESO::GslMatrix> paramDomain("param_", paramSpace, paramMins, paramMaxs); QUESO::UniformVectorRV<QUESO::GslVector, QUESO::GslMatrix> prior("prior_", paramDomain); QUESO::GslVector mean(paramSpace.zeroVector()); mean.cwSet(0.5); QUESO::GslMatrix cov(paramSpace.zeroVector()); cov(0, 0) = 0.05 * 0.05; cov(0, 1) = 0.001; cov(1, 0) = 0.001; cov(1, 1) = 0.05 * 0.05; QUESO::GaussianJointPdf<QUESO::GslVector, QUESO::GslMatrix> pdf("pdf_", paramDomain, mean, cov); Likelihood<QUESO::GslVector, QUESO::GslMatrix> likelihood("likelihood_", paramDomain, pdf); QUESO::GenericVectorRV<QUESO::GslVector, QUESO::GslMatrix> posterior( "posterior_", paramDomain); QUESO::StatisticalInverseProblem<QUESO::GslVector, QUESO::GslMatrix> ip("", NULL, prior, likelihood, posterior); QUESO::GslVector paramInitials(paramSpace.zeroVector()); paramInitials.cwSet(0.5); QUESO::GslMatrix proposalCovMatrix(paramSpace.zeroVector()); proposalCovMatrix(0, 0) = 0.5; proposalCovMatrix(0, 1) = 0.0; proposalCovMatrix(1, 0) = 0.0; proposalCovMatrix(1, 1) = 0.5; ip.solveWithBayesMetropolisHastings(NULL, paramInitials, &proposalCovMatrix); QUESO::GslMatrix adaptedCovMatrix( dynamic_cast<const QUESO::InvLogitGaussianJointPdf<QUESO::GslVector, QUESO::GslMatrix> &>( ip.sequenceGenerator().transitionKernel().rv(0).pdf()).lawCovMatrix()); std::cout << "Adapted covariance matrix is: " << adaptedCovMatrix(0, 0) << " " << adaptedCovMatrix(0, 1) << adaptedCovMatrix(1, 0) << " " << adaptedCovMatrix(1, 1) << std::endl; MPI_Finalize(); return 0; } <commit_msg>Tidy up cov matrix print output<commit_after>#include <queso/Environment.h> #include <queso/GslVector.h> #include <queso/GslMatrix.h> #include <queso/VectorSpace.h> #include <queso/BoxSubset.h> #include <queso/UniformVectorRV.h> #include <queso/GaussianVectorRV.h> #include <queso/GaussianJointPdf.h> #include <queso/InvLogitGaussianJointPdf.h> #include <queso/StatisticalInverseProblem.h> template<class V, class M> class Likelihood : public QUESO::BaseScalarFunction<V, M> { public: Likelihood(const char * prefix, const QUESO::VectorSet<V, M> & domain, const QUESO::GaussianJointPdf<V, M> & pdf) : QUESO::BaseScalarFunction<V, M>(prefix, domain), m_pdf(pdf) { } virtual ~Likelihood() { } virtual double lnValue(const V & domainVector, const V * domainDirection, V * gradVector, M * hessianMatrix, V * hessianEffect) const { return this->m_pdf.lnValue(domainVector, NULL, NULL, NULL, NULL); } virtual double actualValue(const V & domainVector, const V * domainDirection, V * gradVector, M * hessianMatrix, V * hessianEffect) const { return std::exp(this->lnValue(domainVector, domainDirection, gradVector, hessianMatrix, hessianEffect)); } const QUESO::GaussianJointPdf<V, M> & m_pdf; }; int main(int argc, char ** argv) { MPI_Init(&argc, &argv); QUESO::FullEnvironment env(MPI_COMM_WORLD, "test_Regression/adaptedcov_input.txt", "", NULL); QUESO::VectorSpace<QUESO::GslVector, QUESO::GslMatrix> paramSpace(env, "param_", 2, NULL); QUESO::GslVector paramMins(paramSpace.zeroVector()); paramMins.cwSet(0.0); QUESO::GslVector paramMaxs(paramSpace.zeroVector()); paramMaxs.cwSet(1.0); QUESO::BoxSubset<QUESO::GslVector, QUESO::GslMatrix> paramDomain("param_", paramSpace, paramMins, paramMaxs); QUESO::UniformVectorRV<QUESO::GslVector, QUESO::GslMatrix> prior("prior_", paramDomain); QUESO::GslVector mean(paramSpace.zeroVector()); mean.cwSet(0.5); QUESO::GslMatrix cov(paramSpace.zeroVector()); cov(0, 0) = 0.05 * 0.05; cov(0, 1) = 0.001; cov(1, 0) = 0.001; cov(1, 1) = 0.05 * 0.05; QUESO::GaussianJointPdf<QUESO::GslVector, QUESO::GslMatrix> pdf("pdf_", paramDomain, mean, cov); Likelihood<QUESO::GslVector, QUESO::GslMatrix> likelihood("likelihood_", paramDomain, pdf); QUESO::GenericVectorRV<QUESO::GslVector, QUESO::GslMatrix> posterior( "posterior_", paramDomain); QUESO::StatisticalInverseProblem<QUESO::GslVector, QUESO::GslMatrix> ip("", NULL, prior, likelihood, posterior); QUESO::GslVector paramInitials(paramSpace.zeroVector()); paramInitials.cwSet(0.5); QUESO::GslMatrix proposalCovMatrix(paramSpace.zeroVector()); proposalCovMatrix(0, 0) = 0.5; proposalCovMatrix(0, 1) = 0.0; proposalCovMatrix(1, 0) = 0.0; proposalCovMatrix(1, 1) = 0.5; ip.solveWithBayesMetropolisHastings(NULL, paramInitials, &proposalCovMatrix); QUESO::GslMatrix adaptedCovMatrix( dynamic_cast<const QUESO::InvLogitGaussianJointPdf<QUESO::GslVector, QUESO::GslMatrix> &>( ip.sequenceGenerator().transitionKernel().rv(0).pdf()).lawCovMatrix()); std::cout << "Adapted covariance matrix is:" << std::endl; << adaptedCovMatrix(0, 0) << " " << adaptedCovMatrix(0, 1) << std::endl; << adaptedCovMatrix(1, 0) << " " << adaptedCovMatrix(1, 1) << std::endl; MPI_Finalize(); return 0; } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkShrinkFilter.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 "vtkShrinkFilter.h" #include "vtkCell.h" #include "vtkCellData.h" #include "vtkIdList.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" #include "vtkSmartPointer.h" #include "vtkUnstructuredGrid.h" vtkCxxRevisionMacro(vtkShrinkFilter, "1.67"); vtkStandardNewMacro(vtkShrinkFilter); //---------------------------------------------------------------------------- vtkShrinkFilter::vtkShrinkFilter() { this->ShrinkFactor = 0.5; } //---------------------------------------------------------------------------- vtkShrinkFilter::~vtkShrinkFilter() { } //---------------------------------------------------------------------------- void vtkShrinkFilter::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "Shrink Factor: " << this->ShrinkFactor << "\n"; } //---------------------------------------------------------------------------- int vtkShrinkFilter::FillInputPortInformation(int, vtkInformation* info) { // This filter uses the vtkDataSet cell traversal methods so it // suppors any data set type as input. info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkDataSet"); return 1; } //---------------------------------------------------------------------------- int vtkShrinkFilter::RequestData(vtkInformation*, vtkInformationVector** inputVector, vtkInformationVector* outputVector) { // Get input and output data. vtkDataSet* input = vtkDataSet::GetData(inputVector[0]); vtkUnstructuredGrid* output = vtkUnstructuredGrid::GetData(outputVector); // We are now executing this filter. vtkDebugMacro("Shrinking cells"); // Skip execution if there is no input geometry. vtkIdType numCells = input->GetNumberOfCells(); vtkIdType numPts = input->GetNumberOfPoints(); if(numCells < 1 || numPts < 1) { vtkDebugMacro("No data to shrink!"); return 1; } // Allocate working space for new and old cell point lists. vtkSmartPointer<vtkIdList> ptIds = vtkSmartPointer<vtkIdList>::New(); vtkSmartPointer<vtkIdList> newPtIds = vtkSmartPointer<vtkIdList>::New(); ptIds->Allocate(VTK_CELL_SIZE); newPtIds->Allocate(VTK_CELL_SIZE); // Allocate approximately the space needed for the output cells. output->Allocate(numCells); // Allocate space for a new set of points. vtkSmartPointer<vtkPoints> newPts = vtkSmartPointer<vtkPoints>::New(); newPts->Allocate(numPts*8, numPts); // Allocate space for data associated with the new set of points. vtkPointData* inPD = input->GetPointData(); vtkPointData* outPD = output->GetPointData(); outPD->CopyAllocate(inPD, numPts*8, numPts); // Support progress and abort. vtkIdType tenth = (numCells >= 10? numCells/10 : 1); int abort = 0; // Traverse all cells, obtaining node coordinates. Compute "center" // of cell, then create new vertices shrunk towards center. for(vtkIdType cellId = 0; cellId < numCells && !abort; ++cellId) { // Get the list of points for this cell. input->GetCellPoints(cellId, ptIds); vtkIdType numIds = ptIds->GetNumberOfIds(); // Periodically update progress and check for an abort request. if(cellId % tenth == 0) { this->UpdateProgress((cellId+1)/numCells); abort = this->GetAbortExecute(); } // Compute the center of mass of the cell points. double center[3] = {0,0,0}; vtkIdType i; for(i=0; i < numIds; ++i) { double p[3]; input->GetPoint(ptIds->GetId(i), p); for(int j=0; j < 3; ++j) { center[j] += p[j]; } } for(int j=0; j < 3; ++j) { center[j] /= numIds; } // Create new points for this cell. newPtIds->Reset(); for(i=0; i < numIds; ++i) { // Get the old point location. double p[3]; input->GetPoint(ptIds->GetId(i), p); // Compute the new point location. double newPt[3]; for(int j=0; j < 3; ++j) { newPt[j] = center[j] + this->ShrinkFactor*(p[j] - center[j]); } // Create the new point for this cell. vtkIdType newId = newPts->InsertNextPoint(newPt); newPtIds->InsertId(i, newId); // Copy point data from the old point. vtkIdType oldId = ptIds->GetId(i); outPD->CopyData(inPD, oldId, newId); } // Store the new cell in the output. output->InsertNextCell(input->GetCellType(cellId), newPtIds); } // Store the new set of points in the output. output->SetPoints(newPts); // Just pass cell data through because we still have the same number // and type of cells. output->GetCellData()->PassData(input->GetCellData()); // Avoid keeping extra memory around. output->Squeeze(); return 1; } <commit_msg>COMP: Removing previous for-scope fix to make sure the for-scope work-around is functioning again.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkShrinkFilter.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 "vtkShrinkFilter.h" #include "vtkCell.h" #include "vtkCellData.h" #include "vtkIdList.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" #include "vtkSmartPointer.h" #include "vtkUnstructuredGrid.h" vtkCxxRevisionMacro(vtkShrinkFilter, "1.68"); vtkStandardNewMacro(vtkShrinkFilter); //---------------------------------------------------------------------------- vtkShrinkFilter::vtkShrinkFilter() { this->ShrinkFactor = 0.5; } //---------------------------------------------------------------------------- vtkShrinkFilter::~vtkShrinkFilter() { } //---------------------------------------------------------------------------- void vtkShrinkFilter::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "Shrink Factor: " << this->ShrinkFactor << "\n"; } //---------------------------------------------------------------------------- int vtkShrinkFilter::FillInputPortInformation(int, vtkInformation* info) { // This filter uses the vtkDataSet cell traversal methods so it // suppors any data set type as input. info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkDataSet"); return 1; } //---------------------------------------------------------------------------- int vtkShrinkFilter::RequestData(vtkInformation*, vtkInformationVector** inputVector, vtkInformationVector* outputVector) { // Get input and output data. vtkDataSet* input = vtkDataSet::GetData(inputVector[0]); vtkUnstructuredGrid* output = vtkUnstructuredGrid::GetData(outputVector); // We are now executing this filter. vtkDebugMacro("Shrinking cells"); // Skip execution if there is no input geometry. vtkIdType numCells = input->GetNumberOfCells(); vtkIdType numPts = input->GetNumberOfPoints(); if(numCells < 1 || numPts < 1) { vtkDebugMacro("No data to shrink!"); return 1; } // Allocate working space for new and old cell point lists. vtkSmartPointer<vtkIdList> ptIds = vtkSmartPointer<vtkIdList>::New(); vtkSmartPointer<vtkIdList> newPtIds = vtkSmartPointer<vtkIdList>::New(); ptIds->Allocate(VTK_CELL_SIZE); newPtIds->Allocate(VTK_CELL_SIZE); // Allocate approximately the space needed for the output cells. output->Allocate(numCells); // Allocate space for a new set of points. vtkSmartPointer<vtkPoints> newPts = vtkSmartPointer<vtkPoints>::New(); newPts->Allocate(numPts*8, numPts); // Allocate space for data associated with the new set of points. vtkPointData* inPD = input->GetPointData(); vtkPointData* outPD = output->GetPointData(); outPD->CopyAllocate(inPD, numPts*8, numPts); // Support progress and abort. vtkIdType tenth = (numCells >= 10? numCells/10 : 1); int abort = 0; // Traverse all cells, obtaining node coordinates. Compute "center" // of cell, then create new vertices shrunk towards center. for(vtkIdType cellId = 0; cellId < numCells && !abort; ++cellId) { // Get the list of points for this cell. input->GetCellPoints(cellId, ptIds); vtkIdType numIds = ptIds->GetNumberOfIds(); // Periodically update progress and check for an abort request. if(cellId % tenth == 0) { this->UpdateProgress((cellId+1)/numCells); abort = this->GetAbortExecute(); } // Compute the center of mass of the cell points. double center[3] = {0,0,0}; for(vtkIdType i=0; i < numIds; ++i) { double p[3]; input->GetPoint(ptIds->GetId(i), p); for(int j=0; j < 3; ++j) { center[j] += p[j]; } } for(int j=0; j < 3; ++j) { center[j] /= numIds; } // Create new points for this cell. newPtIds->Reset(); for(vtkIdType i=0; i < numIds; ++i) { // Get the old point location. double p[3]; input->GetPoint(ptIds->GetId(i), p); // Compute the new point location. double newPt[3]; for(int j=0; j < 3; ++j) { newPt[j] = center[j] + this->ShrinkFactor*(p[j] - center[j]); } // Create the new point for this cell. vtkIdType newId = newPts->InsertNextPoint(newPt); newPtIds->InsertId(i, newId); // Copy point data from the old point. vtkIdType oldId = ptIds->GetId(i); outPD->CopyData(inPD, oldId, newId); } // Store the new cell in the output. output->InsertNextCell(input->GetCellType(cellId), newPtIds); } // Store the new set of points in the output. output->SetPoints(newPts); // Just pass cell data through because we still have the same number // and type of cells. output->GetCellData()->PassData(input->GetCellData()); // Avoid keeping extra memory around. output->Squeeze(); return 1; } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkSpherePuzzle.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 "vtkSpherePuzzle.h" #include "vtkAppendPolyData.h" #include "vtkGarbageCollector.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkLinearExtrusionFilter.h" #include "vtkMath.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" #include "vtkPolyData.h" #include "vtkSphereSource.h" #include "vtkTransform.h" #include "vtkTransformFilter.h" #include <math.h> vtkCxxRevisionMacro(vtkSpherePuzzle, "1.16"); vtkStandardNewMacro(vtkSpherePuzzle); //---------------------------------------------------------------------------- // Construct a new puzzle. vtkSpherePuzzle::vtkSpherePuzzle() { this->Transform = vtkTransform::New(); this->Reset(); this->Active = 0; this->SetNumberOfInputPorts(0); } //---------------------------------------------------------------------------- // Construct a new puzzle. vtkSpherePuzzle::~vtkSpherePuzzle() { this->Transform->Delete(); this->Transform = NULL; } //---------------------------------------------------------------------------- void vtkSpherePuzzle::Reset() { int idx; this->Modified(); for (idx = 0; idx < 32; ++idx) { this->State[idx] = idx; this->PieceMask[idx] = 0; } this->Transform->Identity(); for (idx = 0; idx < 4; ++idx) { this->Colors[0 + idx*8*3] = 255; this->Colors[1 + idx*8*3] = 0; this->Colors[2 + idx*8*3] = 0; this->Colors[3 + idx*8*3] = 255; this->Colors[4 + idx*8*3] = 175; this->Colors[5 + idx*8*3] = 0; this->Colors[6 + idx*8*3] = 255; this->Colors[7 + idx*8*3] = 255; this->Colors[8 + idx*8*3] = 0; this->Colors[9 + idx*8*3] = 0; this->Colors[10 + idx*8*3] = 255; this->Colors[11 + idx*8*3] = 0; this->Colors[12 + idx*8*3] = 0; this->Colors[13 + idx*8*3] = 255; this->Colors[14 + idx*8*3] = 255; this->Colors[15 + idx*8*3] = 0; this->Colors[16 + idx*8*3] = 0; this->Colors[17 + idx*8*3] = 255; this->Colors[18 + idx*8*3] = 175; this->Colors[19 + idx*8*3] = 0; this->Colors[20 + idx*8*3] = 255; this->Colors[21 + idx*8*3] = 255; this->Colors[22 + idx*8*3] = 50; this->Colors[23 + idx*8*3] = 150; } } //---------------------------------------------------------------------------- int vtkSpherePuzzle::RequestData( vtkInformation *vtkNotUsed(request), vtkInformationVector **vtkNotUsed(inputVector), vtkInformationVector *outputVector) { // get the info object vtkInformation *outInfo = outputVector->GetInformationObject(0); // get the ouptut vtkPolyData *output = vtkPolyData::SafeDownCast( outInfo->Get(vtkDataObject::DATA_OBJECT())); // We are about to create/destroy alot of objects. Defer garbage // collection until we are done. vtkGarbageCollector::DeferredCollectionPush(); int i, j, k, num; int color; vtkAppendPolyData *append = vtkAppendPolyData::New(); vtkSphereSource *sphere = vtkSphereSource::New(); vtkTransformFilter *tf = vtkTransformFilter::New(); vtkUnsignedCharArray *scalars = vtkUnsignedCharArray::New(); vtkPolyData *tmp; vtkPolyData *originalSphereOutput; int count = 0; unsigned char r, g, b; scalars->SetNumberOfComponents(3); sphere->SetPhiResolution(4); sphere->SetThetaResolution(4); tf->SetTransform(this->Transform); tf->SetInput(sphere->GetOutput()); originalSphereOutput = sphere->GetOutput(); for (j = 0; j < 4; ++j) { for (i = 0; i < 8; ++i) { color = this->State[count] * 3; sphere->SetStartTheta((360.0 * (double)(i) / 8.0)); sphere->SetEndTheta((360.0 * (double)(i+1) / 8.0)); sphere->SetStartPhi((180.0 * (double)(j) / 4.0)); sphere->SetEndPhi((180.0 * (double)(j+1) / 4.0)); tmp = vtkPolyData::New(); if (this->PieceMask[count]) { // Spheres original output is transforms input. Put it back. tf->Update(); tmp->ShallowCopy(tf->GetOutput()); } else { // Piece not involved in partial move. Just use the sphere. sphere->Update(); tmp->ShallowCopy(sphere->GetOutput()); } // Now create the colors for the faces. num = tmp->GetNumberOfPoints(); for (k = 0; k < num; ++k) { r = this->Colors[color]; g = this->Colors[color+1]; b = this->Colors[color+2]; // Lighten the active pieces if (this->Active && this->PieceMask[count]) { r = r + (unsigned char)((255 - r) * 0.4); g = g + (unsigned char)((255 - g) * 0.4); b = b + (unsigned char)((255 - b) * 0.4); } scalars->InsertNextValue(r); scalars->InsertNextValue(g); scalars->InsertNextValue(b); } // append all the pieces. append->AddInput(tmp); tmp->Delete(); ++count; } } append->Update(); // Move the data to the output. tmp = output; tmp->CopyStructure(append->GetOutput()); tmp->GetPointData()->PassData(append->GetOutput()->GetPointData()); tmp->GetPointData()->SetScalars(scalars); sphere->Delete(); scalars->Delete(); append->Delete(); tf->Delete(); // We are done creating/destroying objects. vtkGarbageCollector::DeferredCollectionPop(); return 1; } //---------------------------------------------------------------------------- void vtkSpherePuzzle::MarkHorizontal(int section) { int i; for (i = 0; i < 32; ++i) { this->PieceMask[i] = 0; } // Find the start of the section. section = section * 8; for (i = 0; i < 8; ++i) { this->PieceMask[i+section] = 1; } } //---------------------------------------------------------------------------- void vtkSpherePuzzle::MarkVertical(int section) { int i, j, offset; for (i = 0; i < 32; ++i) { this->PieceMask[i] = 1; } for (i = 0; i < 4; ++i) { offset = (section + i) % 8; for (j = 0; j < 4; ++j) { this->PieceMask[offset+(j*8)] = 0; } } } //---------------------------------------------------------------------------- void vtkSpherePuzzle::MoveHorizontal(int slab, int percentage, int rightFlag) { int offset; int tmp; int i; this->Modified(); // Clear out previous partial moves. this->Transform->Identity(); this->MarkHorizontal(slab); // Move zero does nothing. if (percentage <= 0) { return; } // Offset is used to determine which pieces are involved. offset = slab * 8; // Move 100 percent changes state. if (percentage >= 100) { // Just do the state change. if (rightFlag) { tmp = this->State[offset+7]; for (i = 7; i > 0; --i) { this->State[i+offset] = this->State[i-1+offset]; } this->State[offset] = tmp; } else { tmp = this->State[offset]; for (i = 0; i < 7; ++i) { this->State[i+offset] = this->State[i+1+offset]; } this->State[offset+7] = tmp; } return; } // Partial move. // This does not change the state. It is ust for animating // the move. // Setup the pieces that are involved in the move. if ( ! rightFlag) { percentage = -percentage; } this->Transform->RotateZ(((double)(percentage) / 100.0) * (360.0 / 8.0) ); } //---------------------------------------------------------------------------- void vtkSpherePuzzle::MoveVertical(int half, int percentage, int rightFlag) { int tmp; int off0, off1, off2, off3; double theta; this->Modified(); // Clear out previous partial moves. this->Transform->Identity(); this->MarkVertical(half); // Move zero does nothing. if (percentage <= 0) { return; } off0 = (4+half) % 8; off1 = (5+half) % 8; off2 = (6+half) % 8; off3 = (7+half) % 8; // Move 100 percent changes state. if (percentage >= 100) { // Just do the state change. tmp = this->State[off0]; this->State[off0] = this->State[24+off3]; this->State[24+off3] = tmp; tmp = this->State[off1]; this->State[off1] = this->State[24+off2]; this->State[24+off2] = tmp; tmp = this->State[off2]; this->State[off2] = this->State[24+off1]; this->State[24+off1] = tmp; tmp = this->State[off3]; this->State[off3] = this->State[24+off0]; this->State[24+off0] = tmp; tmp = this->State[8+off0]; this->State[8+off0] = this->State[16+off3]; this->State[16+off3] = tmp; tmp = this->State[8+off1]; this->State[8+off1] = this->State[16+off2]; this->State[16+off2] = tmp; tmp = this->State[8+off2]; this->State[8+off2] = this->State[16+off1]; this->State[16+off1] = tmp; tmp = this->State[8+off3]; this->State[8+off3] = this->State[16+off0]; this->State[16+off0] = tmp; return; } // Partial move. // This does not change the state. It is use for animating the move. if (rightFlag) { percentage = -percentage; } theta = (double)(half) * vtkMath::Pi() / 4.0; this->Transform->RotateWXYZ(((double)(percentage)/100.0)*(360.0/2.0), sin(theta), -cos(theta), 0.0); } //---------------------------------------------------------------------------- int vtkSpherePuzzle::SetPoint(double x, double y, double z) { double pt[3]; double theta, phi; int xi, yi; double xp, yp; double xn, yn; this->Modified(); if (x < 0.2 && x > -0.2 && y < 0.2 && y > -0.2 && z < 0.2 && z > -0.2) { this->Active = 0; return 0; } // normalize pt[0] = x; pt[1] = y; pt[2] = z; vtkMath::Normalize(pt); // Convert this into phi and theta. theta = 180.0 - atan2(pt[0], pt[1]) * 180 / vtkMath::Pi(); phi = 90.0 - asin(pt[2]) * 180 / vtkMath::Pi(); // Compute the piece the point is in. xi = (int)(theta * 8.0 / 360.0); yi = (int)(phi * 8 / 360.0); xn = (theta/(360.0/8.0)) - (double)(xi); yn = (phi/(360.0/8.0)) - (double)(yi); //vtkErrorMacro("point: " << x << ", " << y << ", " << z); //vtkErrorMacro("theta: " << theta << ", phi: " << phi); //vtkErrorMacro("theta: " << xi << ", " << xn << ", phi: " << yi << ", " << y); xp = 1.0 - xn; yp = 1.0 - yn; if (xn > 0.2 && xp > 0.2 && yn > 0.2 && yp > 0.2) { // Do nothing in the center of the face. this->Active = 0; return 0; } this->Active = 1; if (xn < xp && xn < yp && xn < yn) { this->VerticalFlag = 1; this->RightFlag = (yn < yp); this->Section = xi+2; this->MarkVertical(this->Section); return this->Section + this->VerticalFlag * 10 + this->RightFlag * 100; } if (xp < xn && xp < yp && xp < yn) { this->VerticalFlag = 1; this->RightFlag = (yp < yn); this->Section = xi+7; this->MarkVertical(this->Section); return this->Section + this->VerticalFlag * 10 + this->RightFlag * 100; } // The remaining options move a horizontal slab. this->VerticalFlag = 0; this->RightFlag = (xn > xp); this->Section = yi; this->MarkHorizontal(this->Section); return this->Section + this->VerticalFlag * 10 + this->RightFlag * 100; } //---------------------------------------------------------------------------- void vtkSpherePuzzle::MovePoint(int percentage) { if ( ! this->Active) { return; } this->Modified(); if (this->VerticalFlag) { this->MoveVertical(this->Section, percentage, this->RightFlag); } else { this->MoveHorizontal(this->Section, percentage, this->RightFlag); } } //---------------------------------------------------------------------------- void vtkSpherePuzzle::PrintSelf(ostream& os, vtkIndent indent) { int idx; this->Superclass::PrintSelf(os,indent); os << indent << "State: " << this->State[0]; for (idx = 1; idx < 16; ++idx) { os << ", " << this->State[idx]; } os << endl; } <commit_msg>COMP: removing unused variable<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkSpherePuzzle.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 "vtkSpherePuzzle.h" #include "vtkAppendPolyData.h" #include "vtkGarbageCollector.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkLinearExtrusionFilter.h" #include "vtkMath.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" #include "vtkPolyData.h" #include "vtkSphereSource.h" #include "vtkTransform.h" #include "vtkTransformFilter.h" #include <math.h> vtkCxxRevisionMacro(vtkSpherePuzzle, "1.17"); vtkStandardNewMacro(vtkSpherePuzzle); //---------------------------------------------------------------------------- // Construct a new puzzle. vtkSpherePuzzle::vtkSpherePuzzle() { this->Transform = vtkTransform::New(); this->Reset(); this->Active = 0; this->SetNumberOfInputPorts(0); } //---------------------------------------------------------------------------- // Construct a new puzzle. vtkSpherePuzzle::~vtkSpherePuzzle() { this->Transform->Delete(); this->Transform = NULL; } //---------------------------------------------------------------------------- void vtkSpherePuzzle::Reset() { int idx; this->Modified(); for (idx = 0; idx < 32; ++idx) { this->State[idx] = idx; this->PieceMask[idx] = 0; } this->Transform->Identity(); for (idx = 0; idx < 4; ++idx) { this->Colors[0 + idx*8*3] = 255; this->Colors[1 + idx*8*3] = 0; this->Colors[2 + idx*8*3] = 0; this->Colors[3 + idx*8*3] = 255; this->Colors[4 + idx*8*3] = 175; this->Colors[5 + idx*8*3] = 0; this->Colors[6 + idx*8*3] = 255; this->Colors[7 + idx*8*3] = 255; this->Colors[8 + idx*8*3] = 0; this->Colors[9 + idx*8*3] = 0; this->Colors[10 + idx*8*3] = 255; this->Colors[11 + idx*8*3] = 0; this->Colors[12 + idx*8*3] = 0; this->Colors[13 + idx*8*3] = 255; this->Colors[14 + idx*8*3] = 255; this->Colors[15 + idx*8*3] = 0; this->Colors[16 + idx*8*3] = 0; this->Colors[17 + idx*8*3] = 255; this->Colors[18 + idx*8*3] = 175; this->Colors[19 + idx*8*3] = 0; this->Colors[20 + idx*8*3] = 255; this->Colors[21 + idx*8*3] = 255; this->Colors[22 + idx*8*3] = 50; this->Colors[23 + idx*8*3] = 150; } } //---------------------------------------------------------------------------- int vtkSpherePuzzle::RequestData( vtkInformation *vtkNotUsed(request), vtkInformationVector **vtkNotUsed(inputVector), vtkInformationVector *outputVector) { // get the info object vtkInformation *outInfo = outputVector->GetInformationObject(0); // get the ouptut vtkPolyData *output = vtkPolyData::SafeDownCast( outInfo->Get(vtkDataObject::DATA_OBJECT())); // We are about to create/destroy alot of objects. Defer garbage // collection until we are done. vtkGarbageCollector::DeferredCollectionPush(); int i, j, k, num; int color; vtkAppendPolyData *append = vtkAppendPolyData::New(); vtkSphereSource *sphere = vtkSphereSource::New(); vtkTransformFilter *tf = vtkTransformFilter::New(); vtkUnsignedCharArray *scalars = vtkUnsignedCharArray::New(); vtkPolyData *tmp; int count = 0; unsigned char r, g, b; scalars->SetNumberOfComponents(3); sphere->SetPhiResolution(4); sphere->SetThetaResolution(4); tf->SetTransform(this->Transform); tf->SetInput(sphere->GetOutput()); for (j = 0; j < 4; ++j) { for (i = 0; i < 8; ++i) { color = this->State[count] * 3; sphere->SetStartTheta((360.0 * (double)(i) / 8.0)); sphere->SetEndTheta((360.0 * (double)(i+1) / 8.0)); sphere->SetStartPhi((180.0 * (double)(j) / 4.0)); sphere->SetEndPhi((180.0 * (double)(j+1) / 4.0)); tmp = vtkPolyData::New(); if (this->PieceMask[count]) { // Spheres original output is transforms input. Put it back. tf->Update(); tmp->ShallowCopy(tf->GetOutput()); } else { // Piece not involved in partial move. Just use the sphere. sphere->Update(); tmp->ShallowCopy(sphere->GetOutput()); } // Now create the colors for the faces. num = tmp->GetNumberOfPoints(); for (k = 0; k < num; ++k) { r = this->Colors[color]; g = this->Colors[color+1]; b = this->Colors[color+2]; // Lighten the active pieces if (this->Active && this->PieceMask[count]) { r = r + (unsigned char)((255 - r) * 0.4); g = g + (unsigned char)((255 - g) * 0.4); b = b + (unsigned char)((255 - b) * 0.4); } scalars->InsertNextValue(r); scalars->InsertNextValue(g); scalars->InsertNextValue(b); } // append all the pieces. append->AddInput(tmp); tmp->Delete(); ++count; } } append->Update(); // Move the data to the output. tmp = output; tmp->CopyStructure(append->GetOutput()); tmp->GetPointData()->PassData(append->GetOutput()->GetPointData()); tmp->GetPointData()->SetScalars(scalars); sphere->Delete(); scalars->Delete(); append->Delete(); tf->Delete(); // We are done creating/destroying objects. vtkGarbageCollector::DeferredCollectionPop(); return 1; } //---------------------------------------------------------------------------- void vtkSpherePuzzle::MarkHorizontal(int section) { int i; for (i = 0; i < 32; ++i) { this->PieceMask[i] = 0; } // Find the start of the section. section = section * 8; for (i = 0; i < 8; ++i) { this->PieceMask[i+section] = 1; } } //---------------------------------------------------------------------------- void vtkSpherePuzzle::MarkVertical(int section) { int i, j, offset; for (i = 0; i < 32; ++i) { this->PieceMask[i] = 1; } for (i = 0; i < 4; ++i) { offset = (section + i) % 8; for (j = 0; j < 4; ++j) { this->PieceMask[offset+(j*8)] = 0; } } } //---------------------------------------------------------------------------- void vtkSpherePuzzle::MoveHorizontal(int slab, int percentage, int rightFlag) { int offset; int tmp; int i; this->Modified(); // Clear out previous partial moves. this->Transform->Identity(); this->MarkHorizontal(slab); // Move zero does nothing. if (percentage <= 0) { return; } // Offset is used to determine which pieces are involved. offset = slab * 8; // Move 100 percent changes state. if (percentage >= 100) { // Just do the state change. if (rightFlag) { tmp = this->State[offset+7]; for (i = 7; i > 0; --i) { this->State[i+offset] = this->State[i-1+offset]; } this->State[offset] = tmp; } else { tmp = this->State[offset]; for (i = 0; i < 7; ++i) { this->State[i+offset] = this->State[i+1+offset]; } this->State[offset+7] = tmp; } return; } // Partial move. // This does not change the state. It is ust for animating // the move. // Setup the pieces that are involved in the move. if ( ! rightFlag) { percentage = -percentage; } this->Transform->RotateZ(((double)(percentage) / 100.0) * (360.0 / 8.0) ); } //---------------------------------------------------------------------------- void vtkSpherePuzzle::MoveVertical(int half, int percentage, int rightFlag) { int tmp; int off0, off1, off2, off3; double theta; this->Modified(); // Clear out previous partial moves. this->Transform->Identity(); this->MarkVertical(half); // Move zero does nothing. if (percentage <= 0) { return; } off0 = (4+half) % 8; off1 = (5+half) % 8; off2 = (6+half) % 8; off3 = (7+half) % 8; // Move 100 percent changes state. if (percentage >= 100) { // Just do the state change. tmp = this->State[off0]; this->State[off0] = this->State[24+off3]; this->State[24+off3] = tmp; tmp = this->State[off1]; this->State[off1] = this->State[24+off2]; this->State[24+off2] = tmp; tmp = this->State[off2]; this->State[off2] = this->State[24+off1]; this->State[24+off1] = tmp; tmp = this->State[off3]; this->State[off3] = this->State[24+off0]; this->State[24+off0] = tmp; tmp = this->State[8+off0]; this->State[8+off0] = this->State[16+off3]; this->State[16+off3] = tmp; tmp = this->State[8+off1]; this->State[8+off1] = this->State[16+off2]; this->State[16+off2] = tmp; tmp = this->State[8+off2]; this->State[8+off2] = this->State[16+off1]; this->State[16+off1] = tmp; tmp = this->State[8+off3]; this->State[8+off3] = this->State[16+off0]; this->State[16+off0] = tmp; return; } // Partial move. // This does not change the state. It is use for animating the move. if (rightFlag) { percentage = -percentage; } theta = (double)(half) * vtkMath::Pi() / 4.0; this->Transform->RotateWXYZ(((double)(percentage)/100.0)*(360.0/2.0), sin(theta), -cos(theta), 0.0); } //---------------------------------------------------------------------------- int vtkSpherePuzzle::SetPoint(double x, double y, double z) { double pt[3]; double theta, phi; int xi, yi; double xp, yp; double xn, yn; this->Modified(); if (x < 0.2 && x > -0.2 && y < 0.2 && y > -0.2 && z < 0.2 && z > -0.2) { this->Active = 0; return 0; } // normalize pt[0] = x; pt[1] = y; pt[2] = z; vtkMath::Normalize(pt); // Convert this into phi and theta. theta = 180.0 - atan2(pt[0], pt[1]) * 180 / vtkMath::Pi(); phi = 90.0 - asin(pt[2]) * 180 / vtkMath::Pi(); // Compute the piece the point is in. xi = (int)(theta * 8.0 / 360.0); yi = (int)(phi * 8 / 360.0); xn = (theta/(360.0/8.0)) - (double)(xi); yn = (phi/(360.0/8.0)) - (double)(yi); //vtkErrorMacro("point: " << x << ", " << y << ", " << z); //vtkErrorMacro("theta: " << theta << ", phi: " << phi); //vtkErrorMacro("theta: " << xi << ", " << xn << ", phi: " << yi << ", " << y); xp = 1.0 - xn; yp = 1.0 - yn; if (xn > 0.2 && xp > 0.2 && yn > 0.2 && yp > 0.2) { // Do nothing in the center of the face. this->Active = 0; return 0; } this->Active = 1; if (xn < xp && xn < yp && xn < yn) { this->VerticalFlag = 1; this->RightFlag = (yn < yp); this->Section = xi+2; this->MarkVertical(this->Section); return this->Section + this->VerticalFlag * 10 + this->RightFlag * 100; } if (xp < xn && xp < yp && xp < yn) { this->VerticalFlag = 1; this->RightFlag = (yp < yn); this->Section = xi+7; this->MarkVertical(this->Section); return this->Section + this->VerticalFlag * 10 + this->RightFlag * 100; } // The remaining options move a horizontal slab. this->VerticalFlag = 0; this->RightFlag = (xn > xp); this->Section = yi; this->MarkHorizontal(this->Section); return this->Section + this->VerticalFlag * 10 + this->RightFlag * 100; } //---------------------------------------------------------------------------- void vtkSpherePuzzle::MovePoint(int percentage) { if ( ! this->Active) { return; } this->Modified(); if (this->VerticalFlag) { this->MoveVertical(this->Section, percentage, this->RightFlag); } else { this->MoveHorizontal(this->Section, percentage, this->RightFlag); } } //---------------------------------------------------------------------------- void vtkSpherePuzzle::PrintSelf(ostream& os, vtkIndent indent) { int idx; this->Superclass::PrintSelf(os,indent); os << indent << "State: " << this->State[0]; for (idx = 1; idx < 16; ++idx) { os << ", " << this->State[idx]; } os << endl; } <|endoftext|>
<commit_before>// $Id$ //************************************************************************** //* This file is property of and copyright by the ALICE HLT Project * //* ALICE Experiment at CERN, All rights reserved. * //* * //* Primary Authors: Matthias Richter <Matthias.Richter@ift.uib.no> * //* for The ALICE HLT Project. * //* * //* Permission to use, copy, modify and distribute this software and its * //* documentation strictly for non-commercial purposes is hereby granted * //* without fee, provided that the above copyright notice appears in all * //* copies and that both the copyright notice and this permission notice * //* appear in the supporting documentation. The authors make no claims * //* about the suitability of this software for any purpose. It is * //* provided "as is" without express or implied warranty. * //************************************************************************** /** @file AliHLTSimulation.cxx @author Matthias Richter @date @brief Binding class for HLT simulation in AliRoot. */ #include <cassert> #include <cerrno> #include "TObjArray.h" #include "TObjString.h" #include "AliHLTSimulation.h" #include "AliSimulation.h" #include "AliLog.h" #include "AliRun.h" #include "AliRunLoader.h" #include "AliHeader.h" #include "AliCDBManager.h" #include "AliCDBEntry.h" #include "AliCDBPath.h" #include "AliCDBId.h" #include "AliCDBMetaData.h" #include "AliCDBStorage.h" #include "AliGRPObject.h" #include "AliHLTSystem.h" #include "AliHLTPluginBase.h" #include "AliRawReaderFile.h" #include "AliRawReaderDate.h" #include "AliRawReaderRoot.h" #include "AliESDEvent.h" #include "AliHLTOUTComponent.h" #include "AliMagF.h" #include "TGeoGlobalMagField.h" #include "TSystem.h" #include "TMath.h" #if ALIHLTSIMULATION_LIBRARY_VERSION != LIBHLTSIM_VERSION #error library version in header file and lib*.pkg do not match #endif /** ROOT macro for the implementation of ROOT specific class methods */ ClassImp(AliHLTSimulation); AliHLTSimulation::AliHLTSimulation() : fOptions(), fpPluginBase(new AliHLTPluginBase), fpRawReader(NULL) { // see header file for class documentation // or // refer to README to build package // or // visit http://web.ift.uib.no/~kjeks/doc/alice-hlt } AliHLTSimulation::~AliHLTSimulation() { // see header file for function documentation if (fpPluginBase) delete fpPluginBase; fpPluginBase=NULL; if (fpRawReader) { delete fpRawReader; } fpRawReader=NULL; } AliHLTSimulation* AliHLTSimulation::CreateInstance() { // see header file for function documentation return new AliHLTSimulation; } int AliHLTSimulation::DeleteInstance(AliHLTSimulation* pSim) { // see header file for function documentation assert(pSim!=NULL); delete pSim; return 0; } int AliHLTSimulation::Init(AliRunLoader* pRunLoader, const char* options) { // init the simulation fOptions=options; TString sysOp; if(!fpPluginBase) { AliError("internal initialization failed"); return -EINVAL; } AliHLTSystem* pSystem=fpPluginBase->GetInstance(); if (!pSystem) { AliError("can not get AliHLTSystem instance"); return -ENOMEM; } if (pSystem->CheckStatus(AliHLTSystem::kError)) { AliError("HLT system in error state"); return -EFAULT; } // scan options for specific entries TObjArray* pTokens=fOptions.Tokenize(" "); if (pTokens) { int iEntries=pTokens->GetEntries(); for (int i=0; i<iEntries; i++) { TString token=(((TObjString*)pTokens->At(i))->GetString()); if (token.Contains("rawfile=")) { TString param=token.ReplaceAll("rawfile=", ""); if (param.EndsWith("/")) { AliInfo(Form("creating AliRawReaderFile (%s)", param.Data())); fpRawReader = new AliRawReaderFile(param); } else if (param.EndsWith(".root")) { AliInfo(Form("creating AliRawReaderRoot (%s)", param.Data())); fpRawReader = new AliRawReaderRoot(param); } else if (!param.IsNull()) { AliInfo(Form("creating AliRawReaderDate (%s)", param.Data())); fpRawReader = new AliRawReaderDate(param); } if (fpRawReader) { fpRawReader->RewindEvents(); int count=0; for ( ; fpRawReader->NextEvent(); count++) {/* empty body */}; if (count!=pRunLoader->GetNumberOfEvents()) { AliError(Form("mismatch in event count: runloader %d, rawreader %d; ignoring rawreader", pRunLoader->GetNumberOfEvents(), count)); count=0; } if (count>0) { fpRawReader->RewindEvents(); fpRawReader->NextEvent(); } else { delete fpRawReader; fpRawReader=NULL; } } } else if (token.Contains("writerawfiles=")) { if (!token.ReplaceAll("writerawfiles=", "").Contains("HLT")) { AliHLTOUTComponent::ClearGlobalOption(AliHLTOUTComponent::kWriteRawFiles); } } else { if (sysOp.Length()>0) sysOp+=" "; sysOp+=token; } } delete pTokens; } AliCDBManager* man = AliCDBManager::Instance(); if (man && man->IsDefaultStorageSet()) { int runNo=pRunLoader->GetHeader()->GetRun(); // init solenoid field Double_t solenoidBz=0; AliMagF *field = (AliMagF*)TGeoGlobalMagField::Instance()->GetField(); if (field) { // this field definition is rather awkward: AliMagF::SolenoidField returns // a signed value, the amazing thing is that the sign is opposite to that // one in the factor. So the abs value has to be used. Lets assume, there // is a reason for that confusing implementation ... solenoidBz=TMath::Abs(field->SolenoidField())*field->Factor(); AliDebug(0,Form("magnetic field: %f %f", field->SolenoidField(),field->Factor())); } else { // workaround for bug #51285 AliError("can not get the AliMagF instance, falling back to GRP entry"); AliCDBEntry *pGRPEntry = man->Get("GRP/GRP/Data", runNo); if (pGRPEntry) { AliGRPObject* pGRPData=dynamic_cast<AliGRPObject*>(pGRPEntry->GetObject()); assert(pGRPData!=NULL); if (pGRPData) { // this is just a workaround at the moment, common functionality in AliReconstruction // is needed to reconstruct the magnetic field in a common way // the code is partly taken from AliReconstruction::InitGRP Bool_t ok = kTRUE; Float_t l3Current = pGRPData->GetL3Current((AliGRPObject::Stats)0); if (l3Current == AliGRPObject::GetInvalidFloat()) { AliError("GRP/GRP/Data entry: missing value for the L3 current !"); ok = kFALSE; } Char_t l3Polarity = pGRPData->GetL3Polarity(); if (l3Polarity == AliGRPObject::GetInvalidChar()) { AliError("GRP/GRP/Data entry: missing value for the L3 polarity !"); ok = kFALSE; } if (ok) { solenoidBz=l3Current/6000; if (l3Polarity) solenoidBz*=-1; } else { AliError("invalid L3 field information in GRP entry"); } } } } const char* cdbSolenoidPath="HLT/ConfigHLT/SolenoidBz"; TString cdbSolenoidParam; cdbSolenoidParam.Form("-solenoidBz %f", solenoidBz); // check if the entry is already there AliCDBEntry *pEntry = man->Get(cdbSolenoidPath, runNo); TObjString* pString=NULL; if (pEntry) pString=dynamic_cast<TObjString*>(pEntry->GetObject()); if (!pEntry || !pString || pString->GetString().CompareTo(cdbSolenoidParam)!=0) { TObjString obj(cdbSolenoidParam); AliCDBPath cdbSolenoidEntry(cdbSolenoidPath); AliCDBId cdbSolenoidId(cdbSolenoidEntry, runNo, runNo, 0, 0); AliCDBMetaData cdbMetaData; cdbMetaData.SetResponsible("Matthias.Richter@cern.ch"); cdbMetaData.SetComment("Automatically produced GRP entry (AliHLTSimulation) for the magnetic field initialization of HLT components"); man->Put(&obj, cdbSolenoidId, &cdbMetaData); // unload the cache due to bug #51281 man->UnloadFromCache(cdbSolenoidPath); } } else if (man) { AliError("OCDB default storage not yet set, can not prepare OCDB entries"); } else { AliError("unable to get instance of AliCDBMetaData, can not prepare OCDB entries"); } // scan options if (pSystem->ScanOptions(sysOp.Data())<0) { AliError("error setting options for HLT system"); return -EINVAL; } if (!pSystem->CheckStatus(AliHLTSystem::kReady)) { if ((pSystem->Configure(fpRawReader, pRunLoader))<0) { AliError("error during HLT system configuration"); return -EFAULT; } } return 0; } int AliHLTSimulation::Run(AliRunLoader* pRunLoader) { // HLT reconstruction for simulated data if(!fpPluginBase) { AliError("internal initialization failed"); return -EINVAL; } if(!pRunLoader) { AliError("Missing RunLoader! 0x0"); return -EINVAL; } int nEvents = pRunLoader->GetNumberOfEvents(); int iResult=0; AliHLTSystem* pSystem=fpPluginBase->GetInstance(); if (!pSystem) { AliError("can not get AliHLTSystem instance"); return -ENOMEM; } if (pSystem->CheckStatus(AliHLTSystem::kError)) { AliError("HLT system in error state"); return -EFAULT; } // Note: the rawreader is already placed at the first event if ((iResult=pSystem->Reconstruct(1, pRunLoader, fpRawReader))>=0) { pSystem->FillESD(0, pRunLoader, NULL); for (int i=1; i<nEvents; i++) { if (fpRawReader && !fpRawReader->NextEvent()) { AliError("mismatch in event count, rawreader corrupted"); break; } pSystem->Reconstruct(1, pRunLoader, fpRawReader); pSystem->FillESD(i, pRunLoader, NULL); } // send specific 'event' to execute the stop sequence pSystem->Reconstruct(0, NULL, NULL); } return iResult; } AliHLTSimulation* AliHLTSimulationCreateInstance() { // see header file for function documentation return AliHLTSimulation::CreateInstance(); } int AliHLTSimulationDeleteInstance(AliHLTSimulation* pSim) { // see header file for function documentation return AliHLTSimulation::DeleteInstance(pSim); } int AliHLTSimulationInit(AliHLTSimulation* pSim, AliRunLoader* pRunLoader, const char* options) { assert(pSim!=NULL); if (pSim) { return pSim->Init(pRunLoader, options); } return -ENODEV; } int AliHLTSimulationRun(AliHLTSimulation* pSim, AliRunLoader* pRunLoader) { assert(pSim!=NULL); if (pSim) { return pSim->Run(pRunLoader); } return -ENODEV; } int AliHLTSimulationGetLibraryVersion() { // see header file for function documentation return LIBHLTSIM_VERSION; } int AliHLTSimulationSetup(AliHLTSimulation* /*pHLTSim*/, AliSimulation* pSim, const char* specificObjects) { // see header file for function documentation // this is an attempt to solve issue #48360 // since there are many jobs running in parallel during the production, // all the jobs want to put entries into the OCDB. The solution is to // make them temporary, since they are only used to propagate information // from the simulation to the reconstruction. if (!pSim) return -EINVAL; const char* entries[]={ "HLT/ConfigHLT/SolenoidBz", NULL }; TString specificStorage; specificStorage.Form("local://%s",gSystem->pwd()); for (const char** pEntry=entries; *pEntry!=NULL; pEntry++) { const char* pObject=specificObjects?strstr(specificObjects, *pEntry):NULL; if (pObject) { // skip this entry if it is found in the list and either // last one or separated by a blank pObject+=strlen(*pEntry); if (*pObject==0 || *pObject==' ') continue; } pSim->SetSpecificStorage(*pEntry, specificStorage.Data()); } return 0; } #ifndef HAVE_COMPILEINFO extern "C" void CompileInfo(const char*& date, const char*& time) { // the fall back compile info of the HLTsim library // this is not up-to-date if other files have been changed and recompiled date=__DATE__; time=__TIME__; return; } #endif <commit_msg>removing the generation of the local solenoidBz OCDB entry removing default entry<commit_after>// $Id$ //************************************************************************** //* This file is property of and copyright by the ALICE HLT Project * //* ALICE Experiment at CERN, All rights reserved. * //* * //* Primary Authors: Matthias Richter <Matthias.Richter@ift.uib.no> * //* for The ALICE HLT Project. * //* * //* Permission to use, copy, modify and distribute this software and its * //* documentation strictly for non-commercial purposes is hereby granted * //* without fee, provided that the above copyright notice appears in all * //* copies and that both the copyright notice and this permission notice * //* appear in the supporting documentation. The authors make no claims * //* about the suitability of this software for any purpose. It is * //* provided "as is" without express or implied warranty. * //************************************************************************** /** @file AliHLTSimulation.cxx @author Matthias Richter @date @brief Binding class for HLT simulation in AliRoot. */ #include <cassert> #include <cerrno> #include "TObjArray.h" #include "TObjString.h" #include "AliHLTSimulation.h" #include "AliSimulation.h" #include "AliLog.h" #include "AliRun.h" #include "AliRunLoader.h" #include "AliHeader.h" #include "AliCDBManager.h" #include "AliCDBEntry.h" #include "AliCDBPath.h" #include "AliCDBId.h" #include "AliCDBMetaData.h" #include "AliCDBStorage.h" #include "AliGRPObject.h" #include "AliGRPManager.h" #include "AliHLTSystem.h" #include "AliHLTPluginBase.h" #include "AliRawReaderFile.h" #include "AliRawReaderDate.h" #include "AliRawReaderRoot.h" #include "AliESDEvent.h" #include "AliHLTOUTComponent.h" #include "AliTracker.h" #include "TGeoGlobalMagField.h" #include "TSystem.h" #include "TMath.h" #include "TGeoGlobalMagField.h" #if ALIHLTSIMULATION_LIBRARY_VERSION != LIBHLTSIM_VERSION #error library version in header file and lib*.pkg do not match #endif /** ROOT macro for the implementation of ROOT specific class methods */ ClassImp(AliHLTSimulation); AliHLTSimulation::AliHLTSimulation() : fOptions(), fpPluginBase(new AliHLTPluginBase), fpRawReader(NULL) { // see header file for class documentation // or // refer to README to build package // or // visit http://web.ift.uib.no/~kjeks/doc/alice-hlt } AliHLTSimulation::~AliHLTSimulation() { // see header file for function documentation if (fpPluginBase) delete fpPluginBase; fpPluginBase=NULL; if (fpRawReader) { delete fpRawReader; } fpRawReader=NULL; } AliHLTSimulation* AliHLTSimulation::CreateInstance() { // see header file for function documentation return new AliHLTSimulation; } int AliHLTSimulation::DeleteInstance(AliHLTSimulation* pSim) { // see header file for function documentation assert(pSim!=NULL); delete pSim; return 0; } int AliHLTSimulation::Init(AliRunLoader* pRunLoader, const char* options) { // init the simulation fOptions=options; TString sysOp; if(!fpPluginBase) { AliError("internal initialization failed"); return -EINVAL; } AliHLTSystem* pSystem=fpPluginBase->GetInstance(); if (!pSystem) { AliError("can not get AliHLTSystem instance"); return -ENOMEM; } if (pSystem->CheckStatus(AliHLTSystem::kError)) { AliError("HLT system in error state"); return -EFAULT; } // scan options for specific entries TObjArray* pTokens=fOptions.Tokenize(" "); if (pTokens) { int iEntries=pTokens->GetEntries(); for (int i=0; i<iEntries; i++) { TString token=(((TObjString*)pTokens->At(i))->GetString()); if (token.Contains("rawfile=")) { TString param=token.ReplaceAll("rawfile=", ""); if (param.EndsWith("/")) { AliInfo(Form("creating AliRawReaderFile (%s)", param.Data())); fpRawReader = new AliRawReaderFile(param); } else if (param.EndsWith(".root")) { AliInfo(Form("creating AliRawReaderRoot (%s)", param.Data())); fpRawReader = new AliRawReaderRoot(param); } else if (!param.IsNull()) { AliInfo(Form("creating AliRawReaderDate (%s)", param.Data())); fpRawReader = new AliRawReaderDate(param); } if (fpRawReader) { fpRawReader->RewindEvents(); int count=0; for ( ; fpRawReader->NextEvent(); count++) {/* empty body */}; if (count!=pRunLoader->GetNumberOfEvents()) { AliError(Form("mismatch in event count: runloader %d, rawreader %d; ignoring rawreader", pRunLoader->GetNumberOfEvents(), count)); count=0; } if (count>0) { fpRawReader->RewindEvents(); fpRawReader->NextEvent(); } else { delete fpRawReader; fpRawReader=NULL; } } } else if (token.Contains("writerawfiles=")) { if (!token.ReplaceAll("writerawfiles=", "").Contains("HLT")) { AliHLTOUTComponent::ClearGlobalOption(AliHLTOUTComponent::kWriteRawFiles); } } else { if (sysOp.Length()>0) sysOp+=" "; sysOp+=token; } } delete pTokens; } AliCDBManager* man = AliCDBManager::Instance(); if (man && man->IsDefaultStorageSet()) { int runNo=pRunLoader->GetHeader()->GetRun(); // init solenoid field // 2009-11-07 magnetic field handling fo HLT components has been switched to the // global AliMagF instance, the HLT/ConfigHLT/SolenoidBz entry is obsolete // The global instance is either established by the AliRoot environment or the // component external interface. if (TGeoGlobalMagField::Instance()->GetField()) { AliDebug(0, Form("magnetic field: %f", AliTracker::GetBz())); } else { // workaround for bug #51285 AliGRPManager grpman; if (grpman.ReadGRPEntry() && grpman.SetMagField()) { // nothing to do any more } AliError(Form("can not get the AliMagF instance, falling back to GRP entry (%f)", AliTracker::GetBz())); } } else if (man) { AliError("OCDB default storage not yet set, can not prepare OCDB entries"); } else { AliError("unable to get instance of AliCDBMetaData, can not prepare OCDB entries"); } // scan options if (pSystem->ScanOptions(sysOp.Data())<0) { AliError("error setting options for HLT system"); return -EINVAL; } if (!pSystem->CheckStatus(AliHLTSystem::kReady)) { if ((pSystem->Configure(fpRawReader, pRunLoader))<0) { AliError("error during HLT system configuration"); return -EFAULT; } } return 0; } int AliHLTSimulation::Run(AliRunLoader* pRunLoader) { // HLT reconstruction for simulated data if(!fpPluginBase) { AliError("internal initialization failed"); return -EINVAL; } if(!pRunLoader) { AliError("Missing RunLoader! 0x0"); return -EINVAL; } int nEvents = pRunLoader->GetNumberOfEvents(); int iResult=0; AliHLTSystem* pSystem=fpPluginBase->GetInstance(); if (!pSystem) { AliError("can not get AliHLTSystem instance"); return -ENOMEM; } if (pSystem->CheckStatus(AliHLTSystem::kError)) { AliError("HLT system in error state"); return -EFAULT; } // Note: the rawreader is already placed at the first event if ((iResult=pSystem->Reconstruct(1, pRunLoader, fpRawReader))>=0) { pSystem->FillESD(0, pRunLoader, NULL); for (int i=1; i<nEvents; i++) { if (fpRawReader && !fpRawReader->NextEvent()) { AliError("mismatch in event count, rawreader corrupted"); break; } pSystem->Reconstruct(1, pRunLoader, fpRawReader); pSystem->FillESD(i, pRunLoader, NULL); } // send specific 'event' to execute the stop sequence pSystem->Reconstruct(0, NULL, NULL); } return iResult; } AliHLTSimulation* AliHLTSimulationCreateInstance() { // see header file for function documentation return AliHLTSimulation::CreateInstance(); } int AliHLTSimulationDeleteInstance(AliHLTSimulation* pSim) { // see header file for function documentation return AliHLTSimulation::DeleteInstance(pSim); } int AliHLTSimulationInit(AliHLTSimulation* pSim, AliRunLoader* pRunLoader, const char* options) { assert(pSim!=NULL); if (pSim) { return pSim->Init(pRunLoader, options); } return -ENODEV; } int AliHLTSimulationRun(AliHLTSimulation* pSim, AliRunLoader* pRunLoader) { assert(pSim!=NULL); if (pSim) { return pSim->Run(pRunLoader); } return -ENODEV; } int AliHLTSimulationGetLibraryVersion() { // see header file for function documentation return LIBHLTSIM_VERSION; } int AliHLTSimulationSetup(AliHLTSimulation* /*pHLTSim*/, AliSimulation* pSim, const char* specificObjects) { // see header file for function documentation // this is an attempt to solve issue #48360 // since there are many jobs running in parallel during the production, // all the jobs want to put entries into the OCDB. The solution is to // make them temporary, since they are only used to propagate information // from the simulation to the reconstruction. if (!pSim) return -EINVAL; const char* entries[]={ NULL }; TString specificStorage; specificStorage.Form("local://%s",gSystem->pwd()); for (const char** pEntry=entries; *pEntry!=NULL; pEntry++) { const char* pObject=specificObjects?strstr(specificObjects, *pEntry):NULL; if (pObject) { // skip this entry if it is found in the list and either // last one or separated by a blank pObject+=strlen(*pEntry); if (*pObject==0 || *pObject==' ') continue; } pSim->SetSpecificStorage(*pEntry, specificStorage.Data()); } return 0; } #ifndef HAVE_COMPILEINFO extern "C" void CompileInfo(const char*& date, const char*& time) { // the fall back compile info of the HLTsim library // this is not up-to-date if other files have been changed and recompiled date=__DATE__; time=__TIME__; return; } #endif <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * 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 "sdattr.hxx" #include "sdresid.hxx" #include "cusshow.hxx" #include "RemoteDialog.hxx" #include "RemoteDialog.hrc" #include "RemoteServer.hxx" using namespace ::sd; using namespace ::std; RemoteDialog::RemoteDialog( Window *pWindow ) : ModalDialog( pWindow, SdResId( DLG_PAIR_REMOTE ) ), mButtonConnect( this, SdResId( BTN_CONNECT ) ), mButtonCancel( this, SdResId( BTN_CANCEL ) ), mClientBox( this, NULL, SdResId( LB_SERVERS ) ), mPreviouslyDiscoverable() { #ifdef ENABLE_SDREMOTE FreeResource(); #ifdef ENABLE_SDREMOTE_BLUETOOTH mPreviouslyDiscoverable = RemoteServer::isBluetoothDiscoverable(); if ( !mPreviouslyDiscoverable ) RemoteServer::setBluetoothDiscoverable( true ); #else RemoteServer::setBluetoothDiscoverable( false ); #endif vector<ClientInfo*> aClients( RemoteServer::getClients() ); for ( vector<ClientInfo*>::const_iterator aIt( aClients.begin() ); aIt < aClients.end(); aIt++ ) { mClientBox.addEntry( *aIt ); } mButtonConnect.SetClickHdl( LINK( this, RemoteDialog, HandleConnectButton ) ); SetCloseHdl( LINK( this, RemoteDialog, CloseHdl ) ); mButtonCancel.SetClickHdl( LINK( this, RemoteDialog, CloseHdl ) ); #else (void) mPreviouslyDiscoverable; // avoid warnings about unused member #endif } RemoteDialog::~RemoteDialog() { } // ----------------------------------------------------------------------- IMPL_LINK_NOARG(RemoteDialog, HandleConnectButton) { // setBusy( true ); // Fixme: Try and connect #if defined(ENABLE_SDREMOTE) && defined(ENABLE_SDREMOTE_BLUETOOTH) long aSelected = mClientBox.GetActiveEntryIndex(); if ( aSelected < 0 ) return 1; TClientBoxEntry aEntry = mClientBox.GetEntryData(aSelected); OUString aPin ( mClientBox.getPin() ); if ( RemoteServer::connectClient( aEntry->m_pClientInfo, aPin ) ) { return CloseHdl( 0 ); } else return 1; #endif return 0; } IMPL_LINK_NOARG( RemoteDialog, CloseHdl ) { #if defined(ENABLE_SDREMOTE) && defined(ENABLE_SDREMOTE_BLUETOOTH) if ( !mPreviouslyDiscoverable ) { RemoteServer::setBluetoothDiscoverable( false ); } Close(); #endif return 0; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>warning C4702: unreachable code<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * 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 "sdattr.hxx" #include "sdresid.hxx" #include "cusshow.hxx" #include "RemoteDialog.hxx" #include "RemoteDialog.hrc" #include "RemoteServer.hxx" using namespace ::sd; using namespace ::std; RemoteDialog::RemoteDialog( Window *pWindow ) : ModalDialog( pWindow, SdResId( DLG_PAIR_REMOTE ) ), mButtonConnect( this, SdResId( BTN_CONNECT ) ), mButtonCancel( this, SdResId( BTN_CANCEL ) ), mClientBox( this, NULL, SdResId( LB_SERVERS ) ), mPreviouslyDiscoverable() { #ifdef ENABLE_SDREMOTE FreeResource(); #ifdef ENABLE_SDREMOTE_BLUETOOTH mPreviouslyDiscoverable = RemoteServer::isBluetoothDiscoverable(); if ( !mPreviouslyDiscoverable ) RemoteServer::setBluetoothDiscoverable( true ); #else RemoteServer::setBluetoothDiscoverable( false ); #endif vector<ClientInfo*> aClients( RemoteServer::getClients() ); for ( vector<ClientInfo*>::const_iterator aIt( aClients.begin() ); aIt < aClients.end(); aIt++ ) { mClientBox.addEntry( *aIt ); } mButtonConnect.SetClickHdl( LINK( this, RemoteDialog, HandleConnectButton ) ); SetCloseHdl( LINK( this, RemoteDialog, CloseHdl ) ); mButtonCancel.SetClickHdl( LINK( this, RemoteDialog, CloseHdl ) ); #else (void) mPreviouslyDiscoverable; // avoid warnings about unused member #endif } RemoteDialog::~RemoteDialog() { } // ----------------------------------------------------------------------- IMPL_LINK_NOARG(RemoteDialog, HandleConnectButton) { // setBusy( true ); // Fixme: Try and connect #if defined(ENABLE_SDREMOTE) && defined(ENABLE_SDREMOTE_BLUETOOTH) long aSelected = mClientBox.GetActiveEntryIndex(); if ( aSelected < 0 ) return 1; TClientBoxEntry aEntry = mClientBox.GetEntryData(aSelected); OUString aPin ( mClientBox.getPin() ); if ( RemoteServer::connectClient( aEntry->m_pClientInfo, aPin ) ) { return CloseHdl( 0 ); } else { return 1; } #else return 0; #endif } IMPL_LINK_NOARG( RemoteDialog, CloseHdl ) { #if defined(ENABLE_SDREMOTE) && defined(ENABLE_SDREMOTE_BLUETOOTH) if ( !mPreviouslyDiscoverable ) { RemoteServer::setBluetoothDiscoverable( false ); } Close(); #endif return 0; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: PrintManager.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: obo $ $Date: 2004-01-20 11:40:59 $ * * 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 SD_PRINT_MANAGER_HXX #define SD_PRINT_MANAGER_HXX #include <tools/solar.h> #include <tools/errcode.hxx> #include <sfx2/viewsh.hxx> class PrintDialog; class SfxItemSet; class SfxPrinter; class SfxProgress; class SfxTabPage; class Window; namespace sd { class ViewShellBase; /** Provide some functions to aid the view shell in printing a document. The functions are about asking the user for specific information what to print and doing the high level printing. The printing of the actual pages is done by the main sub-shell. */ class PrintManager { public: /* Create a new print manager for the given view shell. @param rViewShell The life time of that view shell has to exceed that of the print manager. */ PrintManager (ViewShellBase& rViewShell); virtual ~PrintManager (void); /// Forwarded to the document shell. virtual SfxPrinter* GetPrinter (BOOL bCreate = FALSE); /// Forwarded to the main sub-shell. virtual USHORT SetPrinter ( SfxPrinter* pNewPrinter, USHORT nDiffFlags = SFX_PRINTER_ALL); /// Forwarded to the main sub-shell. virtual PrintDialog* CreatePrintDialog (::Window *pParent); /** Create an options tab page for the curren document. */ virtual SfxTabPage* CreatePrintOptionsPage ( ::Window *pParent, const SfxItemSet &rOptions); /** Print the document. @param pDialog The dialog specifies what to print. */ virtual USHORT Print (SfxProgress& rProgress, PrintDialog* pDialog); /** Show a dialog that allows the user to select the print range (among other things) before starting the actual printing. */ virtual ErrCode DoPrint ( SfxPrinter *pPrinter, PrintDialog *pPrintDialog, BOOL bSilent); /** When called with <TRUE/> then printing is restricted to the selected pages. Otherwise all pages are printed. Note that you have to set the page range with a call to SetPrintingPageRange(). */ void RestrictPrintingToSelection (bool bFlag); /** Set the range of the pages to print. This is taken into account only after a previous call to RestrictPrintingToSelection() with <TRUE/> as argument. */ void SetPrintingPageRange (const String& rsPageRange); USHORT SetPrinterOptDlg ( SfxPrinter* pNewPrinter, USHORT nDiffFlags = SFX_PRINTER_ALL, BOOL _bShowDialog = TRUE); void PreparePrint (PrintDialog* pPrintDialog = 0); private: ViewShellBase& mrViewShell; bool mbPrintDirectSelected; String msPageRange; /// Copy constructor not supported. PrintManager (const PrintManager&); /// Assignment operator not supported. PrintManager& operator= (const PrintManager&); }; } // end of namespace sd #endif <commit_msg>INTEGRATION: CWS impress34 (1.2.362); FILE MERGED 2005/02/10 13:40:43 af 1.2.362.1: #i26264# Moved code for fitting page to printer to its own FitPageToPrinterWithDialog() method.<commit_after>/************************************************************************* * * $RCSfile: PrintManager.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: vg $ $Date: 2005-02-24 15:05:14 $ * * 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 SD_PRINT_MANAGER_HXX #define SD_PRINT_MANAGER_HXX #include <tools/solar.h> #include <tools/errcode.hxx> #include <sfx2/viewsh.hxx> class PrintDialog; class SfxItemSet; class SfxPrinter; class SfxProgress; class SfxTabPage; class Window; namespace sd { class ViewShellBase; /** Provide some functions to aid the view shell in printing a document. The functions are about asking the user for specific information what to print and doing the high level printing. The printing of the actual pages is done by the main sub-shell. */ class PrintManager { public: /* Create a new print manager for the given view shell. @param rViewShell The life time of that view shell has to exceed that of the print manager. */ PrintManager (ViewShellBase& rViewShell); virtual ~PrintManager (void); /// Forwarded to the document shell. virtual SfxPrinter* GetPrinter (BOOL bCreate = FALSE); /// Forwarded to the main sub-shell. virtual USHORT SetPrinter ( SfxPrinter* pNewPrinter, USHORT nDiffFlags = SFX_PRINTER_ALL); /// Forwarded to the main sub-shell. virtual PrintDialog* CreatePrintDialog (::Window *pParent); /** Create an options tab page for the curren document. */ virtual SfxTabPage* CreatePrintOptionsPage ( ::Window *pParent, const SfxItemSet &rOptions); /** Print the document. @param pDialog The dialog specifies what to print. */ virtual USHORT Print (SfxProgress& rProgress, PrintDialog* pDialog); /** Show a dialog that allows the user to select the print range (among other things) before starting the actual printing. */ virtual ErrCode DoPrint ( SfxPrinter *pPrinter, PrintDialog *pPrintDialog, BOOL bSilent); /** When called with <TRUE/> then printing is restricted to the selected pages. Otherwise all pages are printed. Note that you have to set the page range with a call to SetPrintingPageRange(). */ void RestrictPrintingToSelection (bool bFlag); /** Set the range of the pages to print. This is taken into account only after a previous call to RestrictPrintingToSelection() with <TRUE/> as argument. */ void SetPrintingPageRange (const String& rsPageRange); USHORT SetPrinterOptDlg ( SfxPrinter* pNewPrinter, USHORT nDiffFlags = SFX_PRINTER_ALL, BOOL _bShowDialog = TRUE); void PreparePrint (PrintDialog* pPrintDialog = 0); private: ViewShellBase& mrViewShell; bool mbPrintDirectSelected; String msPageRange; /// Copy constructor not supported. PrintManager (const PrintManager&); /// Assignment operator not supported. PrintManager& operator= (const PrintManager&); /** Make sure that the pages that are to be printed do fit to the printer pages. When the internal pages are larger then the printer pages and no method of resolution has yet been provided then a dialog is opened that asks for one. These methods are a) scale internal page down to the printer page, b) crop internal page c) print internal page on several printer pages. @param pPrinter The printer to print the pages on that are specified by the msPageRange member. @param bSilent This flag, when set, tells the method not to wait for user input, i.e. show a dialog. @return The returned flag indicates whether the method was successfull (<TRUE/>) or whether the printing has to be aborted (<FALSE/>). The later one is the case only when the dialog is shown and the user selects 'Cancel'. */ bool FitPageToPrinterWithDialog ( SfxPrinter *pPrinter, bool bSilent); }; } // end of namespace sd #endif <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sd.hxx" #include "TextLogger.hxx" #include "EditWindow.hxx" #include <osl/mutex.hxx> #include <vcl/svapp.hxx> namespace sd { namespace notes { TextLogger* TextLogger::spInstance = NULL; TextLogger& TextLogger::Instance (void) { if (spInstance == NULL) { SolarMutexGuard aGuard; if (spInstance == NULL) spInstance = new TextLogger (); } return *spInstance; } TextLogger::TextLogger (void) : mpEditWindow (NULL) { } void TextLogger::AppendText (const char* sText) { OSL_TRACE (sText); if (mpEditWindow != NULL) mpEditWindow->InsertText (UniString::CreateFromAscii(sText)); } void TextLogger::AppendText (const String& sText) { ByteString s(sText, RTL_TEXTENCODING_ISO_8859_1); OSL_TRACE (s.GetBuffer()); if (mpEditWindow != NULL) mpEditWindow->InsertText (sText); } void TextLogger::AppendNumber (long int nValue) { AppendText (String::CreateFromInt32(nValue)); } void TextLogger::ConnectToEditWindow (EditWindow* pEditWindow) { if (mpEditWindow != pEditWindow) { if (pEditWindow != NULL) pEditWindow->AddEventListener( LINK(this, TextLogger, WindowEventHandler)); else mpEditWindow->RemoveEventListener( LINK(this, TextLogger, WindowEventHandler)); mpEditWindow = pEditWindow; } } IMPL_LINK(TextLogger, WindowEventHandler, VclWindowEvent*, pEvent) { if (pEvent != NULL) { DBG_ASSERT(static_cast<VclWindowEvent*>(pEvent)->GetWindow() == mpEditWindow, "TextLogger: received event from unknown window"); switch (pEvent->GetId()) { case VCLEVENT_WINDOW_CLOSE: case VCLEVENT_OBJECT_DYING: mpEditWindow = NULL; break; } } return TRUE; } } } // end of namespace ::sd::notes /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>OSL_TRACE: Use format string<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sd.hxx" #include "TextLogger.hxx" #include "EditWindow.hxx" #include <osl/mutex.hxx> #include <vcl/svapp.hxx> namespace sd { namespace notes { TextLogger* TextLogger::spInstance = NULL; TextLogger& TextLogger::Instance (void) { if (spInstance == NULL) { SolarMutexGuard aGuard; if (spInstance == NULL) spInstance = new TextLogger (); } return *spInstance; } TextLogger::TextLogger (void) : mpEditWindow (NULL) { } void TextLogger::AppendText (const char* sText) { OSL_TRACE("%s", sText); if (mpEditWindow != NULL) mpEditWindow->InsertText (UniString::CreateFromAscii(sText)); } void TextLogger::AppendText (const String& sText) { ByteString s(sText, RTL_TEXTENCODING_ISO_8859_1); OSL_TRACE("%s", s.GetBuffer()); if (mpEditWindow != NULL) mpEditWindow->InsertText (sText); } void TextLogger::AppendNumber (long int nValue) { AppendText (String::CreateFromInt32(nValue)); } void TextLogger::ConnectToEditWindow (EditWindow* pEditWindow) { if (mpEditWindow != pEditWindow) { if (pEditWindow != NULL) pEditWindow->AddEventListener( LINK(this, TextLogger, WindowEventHandler)); else mpEditWindow->RemoveEventListener( LINK(this, TextLogger, WindowEventHandler)); mpEditWindow = pEditWindow; } } IMPL_LINK(TextLogger, WindowEventHandler, VclWindowEvent*, pEvent) { if (pEvent != NULL) { DBG_ASSERT(static_cast<VclWindowEvent*>(pEvent)->GetWindow() == mpEditWindow, "TextLogger: received event from unknown window"); switch (pEvent->GetId()) { case VCLEVENT_WINDOW_CLOSE: case VCLEVENT_OBJECT_DYING: mpEditWindow = NULL; break; } } return TRUE; } } } // end of namespace ::sd::notes /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/*! \file uclient.cc **************************************************************************** * * Linux implementation of the URBI interface class * * Copyright (C) 2004, 2006, 2007, 2008 Jean-Christophe Baillie. All rights reserved. * * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. **********************************************************************/ #include <cstdlib> #include "libport/cstdio" #include <cerrno> #include <locale.h> #include "libport/unistd.h" #ifndef WIN32 # include <sys/time.h> # include <time.h> # include <signal.h> #else # include "libport/windows.hh" #endif #include "urbi/uclient.hh" #include "urbi/utag.hh" #include "libport/network.h" #include "libport/lockable.hh" #include "libport/thread.hh" #include "libport/utime.hh" #include "libport/cstdio" #include "libport/cstring" namespace urbi { /*! Establish the connection with the server. Spawn a new thread that will listen to the socket, parse the incoming URBI messages, and notify the appropriate callbacks. */ UClient::UClient(const char *_host, int _port, int _buflen) : UAbstractClient(_host, _port, _buflen), thread(0), pingInterval(0) { setlocale(LC_NUMERIC, "C"); control_fd[0] = control_fd[1] = -1; #ifndef WIN32 if (::pipe(control_fd) == -1) { rc = -1; libport::perror("UClient::UClient failed to create pipe"); return; } //block sigpipe signal(SIGPIPE, SIG_IGN); #endif // Address resolution stage. struct sockaddr_in sa; // Internet address struct memset(&sa, 0, sizeof sa); #ifdef WIN32 WSADATA wsaData; WORD wVersionRequested; wVersionRequested = MAKEWORD( 1, 1 ); WSAStartup( wVersionRequested, &wsaData ); #endif sa.sin_family = AF_INET; sa.sin_port = htons(port); // host-to-IP translation struct hostent* hen = gethostbyname(host); if (!hen) { // maybe it is an IP address sa.sin_addr.s_addr = inet_addr(host); if (sa.sin_addr.s_addr == INADDR_NONE) { std::cerr << "UClient::UClient cannot resolve host name." << std::endl; rc = -1; return; } } else memcpy(&sa.sin_addr.s_addr, hen->h_addr_list[0], hen->h_length); sd = socket(AF_INET, SOCK_STREAM, 0); if (sd < 0) { libport::perror("UClient::UClient socket"); rc = -1; return; } // now connect to the remote server. rc = connect(sd, (struct sockaddr *) &sa, sizeof sa); // If we attempt to connect too fast to aperios ipstack it will fail. if (rc) { usleep(20000); rc = connect(sd, (struct sockaddr *) &sa, sizeof sa); } // Check there was no error. if (rc) { libport::perror("UClient::UClient connect"); return; } //check that it really worked int pos=0; while (pos==0) pos = ::recv(sd, recvBuffer, buflen, 0); if (pos<0) { libport::perror("UClient::UClient recv"); rc = pos; return; } else recvBufferPosition = pos; recvBuffer[recvBufferPosition] = 0; thread = libport::startThread(this, &UClient::listenThread); if (!defaultClient) defaultClient = this; } UClient::~UClient() { if (libport::closeSocket(sd) == -1) libport::perror ("cannot close sd"); sd = -1; if (control_fd[1] != -1 && ::write(control_fd[1], "a", 1) == -1) libport::perror ("cannot write to control_fd[1]"); // If the connection has failed while building the client, the // thread is not created. if (thread) // Must wait for listen thread to terminate. libport::joinThread(thread); if (control_fd[1] != -1 && close(control_fd[1]) == -1) libport::perror ("cannot close controlfd[1]"); if (control_fd[0] != -1 && close(control_fd[0]) == -1) libport::perror ("cannot close controlfd[0]"); } bool UClient::canSend(int) { return true; } int UClient::effectiveSend(const void * buffer, int size) { #if DEBUG char output[size+1]; memcpy (static_cast<void*> (output), buffer, size); output[size]=0; std::cerr << ">>>> SENT : [" << output << "]" << std::endl; #endif if (rc) return -1; int pos = 0; while (pos != size) { int retval = ::send(sd, (char *) buffer + pos, size-pos, 0); if (retval< 0) { rc = retval; clientError("send error", rc); return rc; } pos += retval; } return 0; } UCallbackAction UClient::pongCallback(const UMessage &) { waitingPong = false; return URBI_CONTINUE; } void UClient::listenThread() { const char* pongTag = "__URBI_INTERNAL_PONG"; int maxfd; maxfd = 1 + std::max(sd, control_fd[0]); waitingPong = false; setCallback(callback(*this, &UClient::pongCallback), pongTag); while (true) { if (sd == -1) return; fd_set rfds; fd_set efds; FD_ZERO(&rfds); FD_ZERO(&efds); LIBPORT_FD_SET(sd, &rfds); LIBPORT_FD_SET(sd, &efds); #ifndef WIN32 LIBPORT_FD_SET(control_fd[0], &rfds); #endif int selectReturn; if (pingInterval != 0) { const unsigned delay = waitingPong ? pongTimeout : pingInterval; struct timeval timeout = { delay / 1000, (delay % 1000) * 1000}; selectReturn = ::select(maxfd + 1, &rfds, NULL, &efds, &timeout); } else { selectReturn = ::select(maxfd + 1, &rfds, NULL, &efds, NULL); } // Treat error if (selectReturn < 0 && errno != EINTR) { int errorCode = selectReturn; #ifdef WIN32 errorCode = WSAGetLastError(); #endif rc = -1; clientError("Connection error : ", errorCode); notifyCallbacks(UMessage(*this, 0, connectionTimeoutTag.c_str(), "!!! Connection error", std::list<BinaryData>() )); return; } if (selectReturn < 0) // ::select catch a signal (errno == EINTR) continue; // timeout if (selectReturn == 0) { if (waitingPong) // Timeout while waiting PONG { rc = -1; // FIXME: Choose between two differents way to alert user program clientError("Lost connection with server", 0); notifyCallbacks(UMessage(*this, 0, connectionTimeoutTag.c_str(), "!!! Lost connection with server", std::list<BinaryData>() )); return; } else // Timeout : Ping_interval { send("%s << 1,", pongTag); waitingPong = true; } } if (selectReturn > 0) { int count = ::recv(sd, &recvBuffer[recvBufferPosition], buflen - recvBufferPosition - 1, 0); if (count <= 0) { std::string errorMsg; int errorCode = 0; if (count < 0) { #ifdef WIN32 errorCode = WSAGetLastError(); #else errorCode = errno; #endif errorMsg = "!!! Connection error"; } else // count == 0 => Connection close { errorMsg = "!!! Connection closed"; } rc = -1; clientError(errorMsg.c_str(), errorCode); notifyCallbacks(UMessage(*this, 0, connectionTimeoutTag.c_str(), errorMsg.c_str(), std::list<BinaryData>() )); return; } recvBufferPosition += count; recvBuffer[recvBufferPosition] = 0; processRecvBuffer(); } } } void UClient::printf(const char * format, ...) { va_list arg; va_start(arg, format); vfprintf(stderr, format, arg); va_end(arg); } unsigned int UClient::getCurrentTime() const { // FIXME: Put this into libport. #ifdef WIN32 return GetTickCount(); #else struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_sec*1000+tv.tv_usec/1000; #endif } void execute() { while (true) sleep(100); } void exit(int code) { ::exit(code); } UClient& connect(const char* host) { return *new UClient(host); } void disconnect(UClient &client) { delete &client; } void UClient::setKeepAliveCheck(const unsigned pingInterval, const unsigned pongTimeout) { this->pingInterval = pingInterval; this->pongTimeout = pongTimeout; } } // namespace urbi <commit_msg>Use errno.<commit_after>/*! \file uclient.cc **************************************************************************** * * Linux implementation of the URBI interface class * * Copyright (C) 2004, 2006, 2007, 2008 Jean-Christophe Baillie. All rights reserved. * * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. **********************************************************************/ #include <cstdlib> #include <cerrno> #include <locale.h> #include "libport/windows.hh" #ifndef WIN32 # include <sys/time.h> # include <time.h> # include <signal.h> #endif #include "libport/unistd.h" #include "libport/network.h" #include "libport/lockable.hh" #include "libport/thread.hh" #include "libport/utime.hh" #include "libport/cstdio" #include "libport/cstring" #include "urbi/uclient.hh" #include "urbi/utag.hh" namespace urbi { /*! Establish the connection with the server. Spawn a new thread that will listen to the socket, parse the incoming URBI messages, and notify the appropriate callbacks. */ UClient::UClient(const char *_host, int _port, int _buflen) : UAbstractClient(_host, _port, _buflen), thread(0), pingInterval(0) { setlocale(LC_NUMERIC, "C"); control_fd[0] = control_fd[1] = -1; #ifndef WIN32 if (::pipe(control_fd) == -1) { rc = -1; libport::perror("UClient::UClient failed to create pipe"); return; } //block sigpipe signal(SIGPIPE, SIG_IGN); #endif // Address resolution stage. struct sockaddr_in sa; // Internet address struct memset(&sa, 0, sizeof sa); #ifdef WIN32 WSADATA wsaData; WORD wVersionRequested; wVersionRequested = MAKEWORD( 1, 1 ); WSAStartup( wVersionRequested, &wsaData ); #endif sa.sin_family = AF_INET; sa.sin_port = htons(port); // host-to-IP translation struct hostent* hen = gethostbyname(host); if (!hen) { // maybe it is an IP address sa.sin_addr.s_addr = inet_addr(host); if (sa.sin_addr.s_addr == INADDR_NONE) { std::cerr << "UClient::UClient cannot resolve host name." << std::endl; rc = -1; return; } } else memcpy(&sa.sin_addr.s_addr, hen->h_addr_list[0], hen->h_length); sd = socket(AF_INET, SOCK_STREAM, 0); if (sd < 0) { libport::perror("UClient::UClient socket"); rc = -1; return; } // now connect to the remote server. rc = connect(sd, (struct sockaddr *) &sa, sizeof sa); // If we attempt to connect too fast to aperios ipstack it will fail. if (rc) { usleep(20000); rc = connect(sd, (struct sockaddr *) &sa, sizeof sa); } // Check there was no error. if (rc) { libport::perror("UClient::UClient connect"); return; } //check that it really worked int pos=0; while (pos==0) pos = ::recv(sd, recvBuffer, buflen, 0); if (pos<0) { libport::perror("UClient::UClient recv"); rc = pos; return; } else recvBufferPosition = pos; recvBuffer[recvBufferPosition] = 0; thread = libport::startThread(this, &UClient::listenThread); if (!defaultClient) defaultClient = this; } UClient::~UClient() { if (libport::closeSocket(sd) == -1) libport::perror ("cannot close sd"); sd = -1; if (control_fd[1] != -1 && ::write(control_fd[1], "a", 1) == -1) libport::perror ("cannot write to control_fd[1]"); // If the connection has failed while building the client, the // thread is not created. if (thread) // Must wait for listen thread to terminate. libport::joinThread(thread); if (control_fd[1] != -1 && close(control_fd[1]) == -1) libport::perror ("cannot close controlfd[1]"); if (control_fd[0] != -1 && close(control_fd[0]) == -1) libport::perror ("cannot close controlfd[0]"); } bool UClient::canSend(int) { return true; } int UClient::effectiveSend(const void * buffer, int size) { #if DEBUG char output[size+1]; memcpy (static_cast<void*> (output), buffer, size); output[size]=0; std::cerr << ">>>> SENT : [" << output << "]" << std::endl; #endif if (rc) return -1; int pos = 0; while (pos != size) { int retval = ::send(sd, (char *) buffer + pos, size-pos, 0); if (retval< 0) { rc = retval; clientError("send error", rc); return rc; } pos += retval; } return 0; } UCallbackAction UClient::pongCallback(const UMessage &) { waitingPong = false; return URBI_CONTINUE; } void UClient::listenThread() { const char* pongTag = "__URBI_INTERNAL_PONG"; int maxfd; maxfd = 1 + std::max(sd, control_fd[0]); waitingPong = false; setCallback(callback(*this, &UClient::pongCallback), pongTag); while (true) { if (sd == -1) return; fd_set rfds; fd_set efds; FD_ZERO(&rfds); FD_ZERO(&efds); LIBPORT_FD_SET(sd, &rfds); LIBPORT_FD_SET(sd, &efds); #ifndef WIN32 LIBPORT_FD_SET(control_fd[0], &rfds); #endif int selectReturn; if (pingInterval != 0) { const unsigned delay = waitingPong ? pongTimeout : pingInterval; struct timeval timeout = { delay / 1000, (delay % 1000) * 1000}; selectReturn = ::select(maxfd + 1, &rfds, NULL, &efds, &timeout); } else { selectReturn = ::select(maxfd + 1, &rfds, NULL, &efds, NULL); } // Treat error if (selectReturn < 0 && errno != EINTR) { rc = -1; clientError("Connection error : ", errno); notifyCallbacks(UMessage(*this, 0, connectionTimeoutTag.c_str(), "!!! Connection error", std::list<BinaryData>() )); return; } if (selectReturn < 0) // ::select catch a signal (errno == EINTR) continue; // timeout if (selectReturn == 0) { if (waitingPong) // Timeout while waiting PONG { rc = -1; // FIXME: Choose between two differents way to alert user program clientError("Lost connection with server", ETIMEDOUT); notifyCallbacks(UMessage(*this, 0, connectionTimeoutTag.c_str(), "!!! Lost connection with server", std::list<BinaryData>() )); return; } else // Timeout : Ping_interval { send("%s << 1,", pongTag); waitingPong = true; } } if (selectReturn > 0) { int count = ::recv(sd, &recvBuffer[recvBufferPosition], buflen - recvBufferPosition - 1, 0); if (count <= 0) { std::string errorMsg; int errorCode = 0; if (count < 0) { #ifdef WIN32 errorCode = WSAGetLastError(); #else errorCode = errno; #endif errorMsg = "!!! Connection error"; } else // count == 0 => Connection close { errorMsg = "!!! Connection closed"; } rc = -1; clientError(errorMsg.c_str(), errorCode); notifyCallbacks(UMessage(*this, 0, connectionTimeoutTag.c_str(), errorMsg.c_str(), std::list<BinaryData>() )); return; } recvBufferPosition += count; recvBuffer[recvBufferPosition] = 0; processRecvBuffer(); } } } void UClient::printf(const char * format, ...) { va_list arg; va_start(arg, format); vfprintf(stderr, format, arg); va_end(arg); } unsigned int UClient::getCurrentTime() const { // FIXME: Put this into libport. #ifdef WIN32 return GetTickCount(); #else struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_sec*1000+tv.tv_usec/1000; #endif } void execute() { while (true) sleep(100); } void exit(int code) { ::exit(code); } UClient& connect(const char* host) { return *new UClient(host); } void disconnect(UClient &client) { delete &client; } void UClient::setKeepAliveCheck(const unsigned pingInterval, const unsigned pongTimeout) { this->pingInterval = pingInterval; this->pongTimeout = pongTimeout; } } // namespace urbi <|endoftext|>
<commit_before>#include <iostream> #include <seqan/sequence.h> #include <seqan/file.h> int main() { seqan::String<char> str = "admn"; ///The metafunction @Metafunction.Iterator@ returns the iterator type for a given container type. seqan::Iterator<seqan::String<char> >::Type it = begin(str); std::cout << *it; //output: 'a' ///The following lines show a loop through $str$ in the standard library style: while (it != end(str)) //output: "admn" { std::cout << *it; ++it; } std::cout << std::endl; ///Seqan offers an alternative style for accessing iterators that avoids operators. ///Note that the functions @Function.goBegin@ and @Function.atEnd@ do net get $str$ as arguments, /// because $it$ is a @Concept.Rooted Iterator.rooted iterator@. ///The following loop increments each character in $str$: for (goBegin(it); !atEnd(it); goNext(it)) { ++value(it); } ///This is a reverse loop through $str$. ///Note that @Function.goPrevious@ is called before the value of $it$ is accessed, /// because the end position of a container is the position behind the last item in the container: goEnd(it); while (!atBegin(it)) //output: "oneb" { goPrevious(it); std::cout << getValue(it); } std::cout << std::endl; ///Another (write only) way to access the value of an iterator is @Function.assignValue@: assignValue(begin(str), 'X'); std::cout << str << std::endl; //output: "Xeno" return 0; } <commit_msg><commit_after>#include <iostream> #include <seqan/sequence.h> #include <seqan/file.h> int main() { seqan::String<char> str = "admn"; ///The metafunction @Metafunction.Iterator@ returns the iterator type for a given container type. seqan::Iterator<seqan::String<char> >::Type it = begin(str); std::cout << *it; //output: 'a' ///The following lines show a loop through $str$ in the standard library style: while (it != end(str)) //output: "admn" { std::cout << *it; ++it; } std::cout << std::endl; ///Seqan offers an alternative style for accessing iterators that avoids operators. ///Note that the functions @Function.goBegin@ and @Function.atEnd@ do net get $str$ as arguments, /// because $it2$ is a @Concept.Rooted Iterator.rooted iterator@. ///The following loop increments each character in $str$: seqan::Iterator<seqan::String<char>, seqan::Rooted >::Type it2 = begin(str); for (goBegin(it2); !atEnd(it2); goNext(it2)) { ++value(it2); } ///This is a reverse loop through $str$. ///Note that @Function.goPrevious@ is called before the value of $it2$ is accessed, /// because the end position of a container is the position behind the last item in the container: goEnd(it2); while (!atBegin(it2)) //output: "oneb" { goPrevious(it2); std::cout << getValue(it2); } std::cout << std::endl; ///Another (write only) way to access the value of an iterator is @Function.assignValue@: assignValue(begin(str), 'X'); std::cout << str << std::endl; //output: "Xeno" return 0; } <|endoftext|>