text
stringlengths
54
60.6k
<commit_before>// Copyright (c) 2018 Intel Corporation // // 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 "umc_deinterlacing.h" #include "umc_video_data.h" #include "ippi.h" #include "ippvc.h" using namespace UMC; Deinterlacing::Deinterlacing() { mMethod = DEINTERLACING_DUPLICATE; } Status Deinterlacing::SetMethod(DeinterlacingMethod method) { mMethod = method; return UMC_OK; } static void DeinterlacingEdgeDetect(uint8_t *psrc, int32_t iSrcPitch, uint8_t *pdst, int32_t iDstPitch, int32_t w, int32_t h); Status Deinterlacing::GetFrame(MediaData *input, MediaData *output) { VideoData *in = DynamicCast<VideoData>(input); VideoData *out = DynamicCast<VideoData>(output); DeinterlacingMethod method = mMethod; int k; if (NULL == in || NULL == out) { return UMC_ERR_NULL_PTR; } ColorFormat cFormat = in->GetColorFormat(); if (out->GetColorFormat() != cFormat) { return UMC_ERR_INVALID_PARAMS; } int32_t in_Width = in->GetWidth(); int32_t in_Height = in->GetHeight(); int32_t out_Width = out->GetWidth(); int32_t out_Height = out->GetHeight(); if ( (in_Width != out_Width) || (in_Height != out_Height) ) { return UMC_ERR_INVALID_PARAMS; } for (k = 0; k < in->GetNumPlanes(); k++) { VideoData::PlaneInfo srcPlane; const uint8_t *pSrc0; //, *pSrc1; uint8_t *pDst0, *pDst1; int srcPitch, dstPitch; mfxSize size; in->GetPlaneInfo(&srcPlane, k); pSrc0 = (const uint8_t*)in->GetPlanePointer(k); srcPitch = (int32_t)in->GetPlanePitch(k); pDst0 = (uint8_t*)out->GetPlanePointer(k); dstPitch = (int32_t)out->GetPlanePitch(k); size.width = srcPlane.m_ippSize.width * srcPlane.m_iSamples * srcPlane.m_iSampleSize; size.height = srcPlane.m_ippSize.height; if (method == DEINTERLACING_BLEND) { if (srcPlane.m_iSampleSize != 1) { //return UMC_ERR_UNSUPPORTED; method = DEINTERLACING_DUPLICATE; } mfxiDeinterlaceFilterTriangle_8u_C1R(pSrc0, srcPitch, pDst0, dstPitch, size, 128, IPP_LOWER | IPP_UPPER | IPP_CENTER); continue; } if (method == DEINTERLACING_SPATIAL) { if (k == 0) { // Y if (srcPlane.m_iSampleSize != 1 || srcPlane.m_iSamples != 1) { //return UMC_ERR_UNSUPPORTED; method = DEINTERLACING_DUPLICATE; } DeinterlacingEdgeDetect((uint8_t*)pSrc0, srcPitch, pDst0, dstPitch, size.width, size.height); continue; } else { // U,V method = DEINTERLACING_DUPLICATE; } } // DEINTERLACING_DUPLICATE //pSrc1 = pSrc0 += srcPitch; pSrc0 += srcPitch; srcPitch *= 2; pDst1 = pDst0 + dstPitch; dstPitch *= 2; size.height /= 2; mfxiCopy_8u_C1R(pSrc0, srcPitch, pDst0, dstPitch, size); mfxiCopy_8u_C1R(pSrc0, srcPitch, pDst1, dstPitch, size); } return UMC_OK; } static void DeinterlacingEdgeDetect(uint8_t *psrc, int32_t iSrcPitch, uint8_t *pdst, int32_t iDstPitch, int32_t w, int32_t h) { int32_t /*hi, lo,*/ x, y; int32_t res; uint8_t *pInA, *pInB, *pInC, *pInD, *pInE, *pInF; int32_t dif1, dif2, dif3; mfxSize roi = {w, h/2}; // copy even lines mfxiCopy_8u_C1R(psrc, 2*iSrcPitch, pdst, 2*iDstPitch, roi); // then line #1 and line before last std::copy(psrc + iSrcPitch, psrc + 2*iSrcPitch, pdst + iDstPitch); std::copy(psrc + (h - 2) * iSrcPitch, psrc + (h - 2) * iSrcPitch + w, pdst + (h - 1)*iDstPitch); psrc += 3*iSrcPitch; pdst += 3*iDstPitch; pInB = psrc - iSrcPitch; pInA = pInB - 1; pInC = pInB + 1; pInE = psrc + iSrcPitch; pInD = pInE - 1; pInF = pInE + 1; for (y = 3; y <= h - 3; y += 2) { pdst[0] = psrc[0]; pdst[w - 1] = psrc[w - 1]; for (x = 1; x < w - 1; x++) { dif1 = abs((int32_t)pInA[x] - (int32_t)pInF[x]); dif2 = abs((int32_t)pInC[x] - (int32_t)pInD[x]); dif3 = abs((int32_t)pInB[x] - (int32_t)pInE[x]); if (dif1 < dif2) { if (dif1 < dif3) { res = ((int32_t)pInA[x] + (int32_t)pInF[x]) >> 1; //1 } else { res = ((int32_t)pInB[x] + (int32_t)pInE[x]) >> 1; //3 } } else { if (dif2 < dif3) { res = ((int32_t)pInC[x] + (int32_t)pInD[x]) >> 1; //2 } else { res = ((int32_t)pInB[x] + (int32_t)pInE[x]) >> 1; //3 } } pdst[x] = (uint8_t)res; } psrc += 2*iSrcPitch; pdst += 2*iDstPitch; pInA += 2*iSrcPitch; pInB += 2*iSrcPitch; pInC += 2*iSrcPitch; pInD += 2*iSrcPitch; pInE += 2*iSrcPitch; pInF += 2*iSrcPitch; } } <commit_msg>initialize the variable in umc_deinterlacing<commit_after>// Copyright (c) 2018-2020 Intel Corporation // // 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 "umc_deinterlacing.h" #include "umc_video_data.h" #include "ippi.h" #include "ippvc.h" using namespace UMC; Deinterlacing::Deinterlacing() { mMethod = DEINTERLACING_DUPLICATE; } Status Deinterlacing::SetMethod(DeinterlacingMethod method) { mMethod = method; return UMC_OK; } static void DeinterlacingEdgeDetect(uint8_t *psrc, int32_t iSrcPitch, uint8_t *pdst, int32_t iDstPitch, int32_t w, int32_t h); Status Deinterlacing::GetFrame(MediaData *input, MediaData *output) { VideoData *in = DynamicCast<VideoData>(input); VideoData *out = DynamicCast<VideoData>(output); DeinterlacingMethod method = mMethod; int k; if (NULL == in || NULL == out) { return UMC_ERR_NULL_PTR; } ColorFormat cFormat = in->GetColorFormat(); if (out->GetColorFormat() != cFormat) { return UMC_ERR_INVALID_PARAMS; } int32_t in_Width = in->GetWidth(); int32_t in_Height = in->GetHeight(); int32_t out_Width = out->GetWidth(); int32_t out_Height = out->GetHeight(); if ( (in_Width != out_Width) || (in_Height != out_Height) ) { return UMC_ERR_INVALID_PARAMS; } for (k = 0; k < in->GetNumPlanes(); k++) { VideoData::PlaneInfo srcPlane = {}; const uint8_t *pSrc0; //, *pSrc1; uint8_t *pDst0, *pDst1; int srcPitch, dstPitch; mfxSize size; in->GetPlaneInfo(&srcPlane, k); pSrc0 = (const uint8_t*)in->GetPlanePointer(k); srcPitch = (int32_t)in->GetPlanePitch(k); pDst0 = (uint8_t*)out->GetPlanePointer(k); dstPitch = (int32_t)out->GetPlanePitch(k); size.width = srcPlane.m_ippSize.width * srcPlane.m_iSamples * srcPlane.m_iSampleSize; size.height = srcPlane.m_ippSize.height; if (method == DEINTERLACING_BLEND) { if (srcPlane.m_iSampleSize != 1) { //return UMC_ERR_UNSUPPORTED; method = DEINTERLACING_DUPLICATE; } mfxiDeinterlaceFilterTriangle_8u_C1R(pSrc0, srcPitch, pDst0, dstPitch, size, 128, IPP_LOWER | IPP_UPPER | IPP_CENTER); continue; } if (method == DEINTERLACING_SPATIAL) { if (k == 0) { // Y if (srcPlane.m_iSampleSize != 1 || srcPlane.m_iSamples != 1) { //return UMC_ERR_UNSUPPORTED; method = DEINTERLACING_DUPLICATE; } DeinterlacingEdgeDetect((uint8_t*)pSrc0, srcPitch, pDst0, dstPitch, size.width, size.height); continue; } else { // U,V method = DEINTERLACING_DUPLICATE; } } // DEINTERLACING_DUPLICATE //pSrc1 = pSrc0 += srcPitch; pSrc0 += srcPitch; srcPitch *= 2; pDst1 = pDst0 + dstPitch; dstPitch *= 2; size.height /= 2; mfxiCopy_8u_C1R(pSrc0, srcPitch, pDst0, dstPitch, size); mfxiCopy_8u_C1R(pSrc0, srcPitch, pDst1, dstPitch, size); } return UMC_OK; } static void DeinterlacingEdgeDetect(uint8_t *psrc, int32_t iSrcPitch, uint8_t *pdst, int32_t iDstPitch, int32_t w, int32_t h) { int32_t /*hi, lo,*/ x, y; int32_t res; uint8_t *pInA, *pInB, *pInC, *pInD, *pInE, *pInF; int32_t dif1, dif2, dif3; mfxSize roi = {w, h/2}; // copy even lines mfxiCopy_8u_C1R(psrc, 2*iSrcPitch, pdst, 2*iDstPitch, roi); // then line #1 and line before last std::copy(psrc + iSrcPitch, psrc + 2*iSrcPitch, pdst + iDstPitch); std::copy(psrc + (h - 2) * iSrcPitch, psrc + (h - 2) * iSrcPitch + w, pdst + (h - 1)*iDstPitch); psrc += 3*iSrcPitch; pdst += 3*iDstPitch; pInB = psrc - iSrcPitch; pInA = pInB - 1; pInC = pInB + 1; pInE = psrc + iSrcPitch; pInD = pInE - 1; pInF = pInE + 1; for (y = 3; y <= h - 3; y += 2) { pdst[0] = psrc[0]; pdst[w - 1] = psrc[w - 1]; for (x = 1; x < w - 1; x++) { dif1 = abs((int32_t)pInA[x] - (int32_t)pInF[x]); dif2 = abs((int32_t)pInC[x] - (int32_t)pInD[x]); dif3 = abs((int32_t)pInB[x] - (int32_t)pInE[x]); if (dif1 < dif2) { if (dif1 < dif3) { res = ((int32_t)pInA[x] + (int32_t)pInF[x]) >> 1; //1 } else { res = ((int32_t)pInB[x] + (int32_t)pInE[x]) >> 1; //3 } } else { if (dif2 < dif3) { res = ((int32_t)pInC[x] + (int32_t)pInD[x]) >> 1; //2 } else { res = ((int32_t)pInB[x] + (int32_t)pInE[x]) >> 1; //3 } } pdst[x] = (uint8_t)res; } psrc += 2*iSrcPitch; pdst += 2*iDstPitch; pInA += 2*iSrcPitch; pInB += 2*iSrcPitch; pInC += 2*iSrcPitch; pInD += 2*iSrcPitch; pInE += 2*iSrcPitch; pInF += 2*iSrcPitch; } } <|endoftext|>
<commit_before>/////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2013, PAL Robotics S.L. // // 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 PAL Robotics, Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. ////////////////////////////////////////////////////////////////////////////// /// \author Masaru Morita // NOTE: The contents of this file have been taken largely from the ros_control wiki tutorials // ROS #include <ros/ros.h> // ros_control #include <controller_manager/controller_manager.h> #include "./../include/ackermann_steering_bot.h" int main(int argc, char **argv) { ros::init(argc, argv, "ackermann_steering_bot"); ros::NodeHandle nh; AckermannSteeringBot robot; ROS_WARN_STREAM("period: " << robot.getPeriod().toSec()); controller_manager::ControllerManager cm(&robot, nh); ros::Rate rate(1.0 / robot.getPeriod().toSec()); ros::AsyncSpinner spinner(1); spinner.start(); while(ros::ok()) { ROS_WARN_STREAM("period: " << robot.getPeriod().toSec()); robot.read(); cm.update(robot.getTime(), robot.getPeriod()); robot.write(); rate.sleep(); } spinner.stop(); return 0; } <commit_msg>removed cyclic debug output from ackermann_steering_bot (#448)<commit_after>/////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2013, PAL Robotics S.L. // // 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 PAL Robotics, Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. ////////////////////////////////////////////////////////////////////////////// /// \author Masaru Morita // NOTE: The contents of this file have been taken largely from the ros_control wiki tutorials // ROS #include <ros/ros.h> // ros_control #include <controller_manager/controller_manager.h> #include "./../include/ackermann_steering_bot.h" int main(int argc, char **argv) { ros::init(argc, argv, "ackermann_steering_bot"); ros::NodeHandle nh; AckermannSteeringBot robot; ROS_WARN_STREAM("period: " << robot.getPeriod().toSec()); controller_manager::ControllerManager cm(&robot, nh); ros::Rate rate(1.0 / robot.getPeriod().toSec()); ros::AsyncSpinner spinner(1); spinner.start(); while(ros::ok()) { robot.read(); cm.update(robot.getTime(), robot.getPeriod()); robot.write(); rate.sleep(); } spinner.stop(); return 0; } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/usr/isteps/istep13/call_mss_draminit_mc.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ //Error handling and tracing #include <errl/errlentry.H> #include <errl/errlmanager.H> #include <errl/errludtarget.H> #include <isteps/hwpisteperror.H> #include <initservice/isteps_trace.H> // targeting support #include <targeting/common/commontargeting.H> #include <targeting/common/util.H> #include <targeting/common/utilFilter.H> // Istep 13 framework #include "istep13consts.H" // fapi2 HWP invoker #include <fapi2/plat_hwp_invoker.H> //From Import Directory (EKB Repository) #include <config.h> #include <fapi2.H> #include <p9_mss_draminit_mc.H> using namespace ERRORLOG; using namespace ISTEP; using namespace ISTEP_ERROR; using namespace TARGETING; namespace ISTEP_13 { void* call_mss_draminit_mc (void *io_pArgs) { errlHndl_t l_err = NULL; IStepError l_stepError; TARGETING::Target * sys = NULL; TARGETING::targetService().getTopLevelTarget( sys ); TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,"call_mss_draminit_mc entry" ); // Get all MCBIST TARGETING::TargetHandleList l_mcbistTargetList; getAllChiplets(l_mcbistTargetList, TYPE_MCBIST); for (const auto & l_mcbist_target : l_mcbistTargetList) { // Dump current run on target TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "Running p9_mss_draminit_mc HWP on " "target HUID %.8X", TARGETING::get_huid(l_mcbist_target)); fapi2::Target<fapi2::TARGET_TYPE_MCBIST> l_fapi_mcbist_target (l_mcbist_target); FAPI_INVOKE_HWP(l_err, p9_mss_draminit_mc, l_fapi_mcbist_target); if (l_err) { TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "ERROR 0x%.8X : p9_mss_draminit_mc HWP returns error", l_err->reasonCode()); // capture the target data in the elog ErrlUserDetailsTarget(l_mcbist_target).addToLog( l_err ); // Create IStep error log and cross reference to error that occurred l_stepError.addErrorDetails( l_err ); // Commit Error errlCommit( l_err, HWPF_COMP_ID ); } else { TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "SUCCESS running p9_mss_draminit_mc HWP on " "target HUID %.8X", TARGETING::get_huid(l_mcbist_target)); } } // End; memBuf loop TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "call_mss_draminit_mc exit" ); return l_stepError.getErrorHandle(); } }; <commit_msg>Insert workaround for issue with memdiags<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/usr/isteps/istep13/call_mss_draminit_mc.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ //Error handling and tracing #include <errl/errlentry.H> #include <errl/errlmanager.H> #include <errl/errludtarget.H> #include <isteps/hwpisteperror.H> #include <initservice/isteps_trace.H> // targeting support #include <targeting/common/commontargeting.H> #include <targeting/common/util.H> #include <targeting/common/utilFilter.H> // Istep 13 framework #include "istep13consts.H" // fapi2 HWP invoker #include <fapi2/plat_hwp_invoker.H> //From Import Directory (EKB Repository) #include <config.h> #include <fapi2.H> #include <p9_mss_draminit_mc.H> using namespace ERRORLOG; using namespace ISTEP; using namespace ISTEP_ERROR; using namespace TARGETING; namespace ISTEP_13 { void* call_mss_draminit_mc (void *io_pArgs) { errlHndl_t l_err = NULL; IStepError l_stepError; TARGETING::Target * sys = NULL; TARGETING::targetService().getTopLevelTarget( sys ); TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,"call_mss_draminit_mc entry" ); // Get all MCBIST TARGETING::TargetHandleList l_mcbistTargetList; getAllChiplets(l_mcbistTargetList, TYPE_MCBIST); for (const auto & l_mcbist_target : l_mcbistTargetList) { // Dump current run on target TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "Running p9_mss_draminit_mc HWP on " "target HUID %.8X", TARGETING::get_huid(l_mcbist_target)); fapi2::Target<fapi2::TARGET_TYPE_MCBIST> l_fapi_mcbist_target (l_mcbist_target); FAPI_INVOKE_HWP(l_err, p9_mss_draminit_mc, l_fapi_mcbist_target); if (l_err) { TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, "ERROR 0x%.8X : p9_mss_draminit_mc HWP returns error", l_err->reasonCode()); // capture the target data in the elog ErrlUserDetailsTarget(l_mcbist_target).addToLog( l_err ); // Create IStep error log and cross reference to error that occurred l_stepError.addErrorDetails( l_err ); // Commit Error errlCommit( l_err, HWPF_COMP_ID ); } else { TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "SUCCESS running p9_mss_draminit_mc HWP on " "target HUID %.8X", TARGETING::get_huid(l_mcbist_target)); } } // End; memBuf loop //TODO RTC:167292 Remove this workaround that is clearing this scom register fapi2::buffer<uint64_t> l_data64; l_data64.flush<0>(); // Get all MCAs TARGETING::TargetHandleList l_mcaTargetList; getAllChiplets(l_mcaTargetList, TYPE_MCA); //Clear out the MBA_FARB3Q reg(0x7010916) on all MCAs for (const auto & l_mca_target : l_mcaTargetList) { fapi2::Target<fapi2::TARGET_TYPE_MCA> l_fapi_mca_target (l_mca_target); fapi2::putScom(l_fapi_mca_target, 0x7010916, l_data64); } TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "call_mss_draminit_mc exit" ); return l_stepError.getErrorHandle(); } }; <|endoftext|>
<commit_before>/* * Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland * All rights reserved. * * This library/application is free software; you can redistribute and/or modify it under the terms of * the license that is included with this library/application in the file license.txt. */ //--- interface include -------------------------------------------------------- #include "ITOStorage.h" //--- standard modules used ---------------------------------------------------- #include "SysLog.h" #include "System.h" #include "MemHeader.h" #include "InitFinisManagerFoundation.h" //--- c-library modules used --------------------------------------------------- #include <string.h> #ifdef __370__ extern "C" void finalize(); #endif #include <stdio.h> #if defined(WIN32) #define snprintf _snprintf #endif //#define TRACK_USED_MEMORYBLOCKS 1 MemChecker::MemChecker(const char *scope, Allocator *a) : fAllocator(a) , fSizeAllocated(fAllocator->CurrentlyAllocated()) , fScope(scope) { } MemChecker::~MemChecker() { if ( CheckDelta() > 0 ) { TraceDelta("MemChecker.~MemChecker: "); } } void MemChecker::TraceDelta(const char *message) { char msgbuf[1024] = {'\0'}; if (message) { SysLog::WriteToStderr( message, strlen(message)); } l_long delta = CheckDelta(); int bufsz = snprintf(msgbuf, sizeof(msgbuf), "\nMem Usage change by %.0f bytes in %s\n", (double)delta, fScope); SysLog::WriteToStderr( msgbuf, bufsz ); } l_long MemChecker::CheckDelta() { return fAllocator->CurrentlyAllocated() - fSizeAllocated; } //------------- Utilities for Memory Tracking -------------- MemTracker::MemTracker(const char *name) : fAllocated(0) , fMaxAllocated(0) , fNumAllocs(0) , fSizeAllocated(0) , fNumFrees(0) , fSizeFreed(0) , fId(-1) , fpName(strdup(name)) // copy string to be more flexible when using temporary param objects like Strings { } void *MemTracker::operator new(size_t size) { // never allocate on allocator, because we are tracking exactly the one... void *vp = ::calloc(1, sizeof(MemTracker)); return vp; } void *MemTracker::operator new(size_t size, Allocator *) { // never allocate on allocator, because we are tracking exactly the one... void *vp = ::calloc(1, sizeof(MemTracker)); return vp; } void MemTracker::operator delete(void *vp) { if (vp) { ::operator delete(vp); } } void MemTracker::Init(MemTracker *t) { fAllocated = t->fAllocated; fNumAllocs = t->fNumAllocs; fSizeAllocated = t->fSizeAllocated; fNumFrees = t->fNumFrees; fSizeFreed = t->fSizeFreed; fId = t->fId; fMaxAllocated = t->fMaxAllocated; } MemTracker::~MemTracker() { delete fpName; } void MemTracker::SetId(long id) { fId = id; } void MemTracker::TrackAlloc(MemoryHeader *mh) { fAllocated += mh->fSize; ++fNumAllocs; fSizeAllocated += mh->fSize; fMaxAllocated = itoMAX(fMaxAllocated, fAllocated); #if defined(TRACK_USED_MEMORYBLOCKS) fUsedList.push_front(mh); #endif } void MemTracker::TrackFree(MemoryHeader *mh) { fAllocated -= mh->fSize; ++fNumFrees; fSizeFreed += mh->fSize; #if defined(TRACK_USED_MEMORYBLOCKS) UsedListType::iterator aUsedIterator; for ( aUsedIterator = fUsedList.begin(); aUsedIterator != fUsedList.end(); ++aUsedIterator ) { if ( *aUsedIterator == mh ) { fUsedList.erase(aUsedIterator); break; } } #endif } void MemTracker::DumpUsedBlocks() { if ( fUsedList.size() ) { SysLog::Error("Following memory blocks are still in use:"); UsedListType::const_iterator aUsedIterator; long lIdx = 0; for ( aUsedIterator = fUsedList.begin(); aUsedIterator != fUsedList.end(); ++lIdx, ++aUsedIterator) { MemoryHeader *pMH = *aUsedIterator; String strBuf((void *)pMH, ( pMH->fSize + MemoryHeader::AlignedSize() ), Storage::Global()); SysLog::WriteToStderr(String(Storage::Global()).Append("Block ").Append(lIdx).Append('\n')); SysLog::WriteToStderr(strBuf.DumpAsHex()); SysLog::WriteToStderr("\n"); } } } void MemTracker::PrintStatistic(long lLevel) { if ( lLevel >= 2 ) { char buf[2048] = { 0 }; // safety margin for bytes snprintf(buf, sizeof(buf), "\nAllocator [%02ld] [%s]\n" #if defined(WIN32) "Peek Allocated %20I64d bytes\n" "Total Allocated %20I64d bytes in %15I64d runs (%ld/run)\n" "Total Freed %20I64d bytes in %15I64d runs (%ld/run)\n" "------------------------------------------\n" "Difference %20I64d bytes\n", #else "Peek Allocated %20lld bytes\n" "Total Allocated %20lld bytes in %15lld runs (%ld/run)\n" "Total Freed %20lld bytes in %15lld runs (%ld/run)\n" "------------------------------------------\n" "Difference %20lld bytes\n", #endif fId, fpName, fMaxAllocated, fSizeAllocated , fNumAllocs, (long)(fSizeAllocated / ((fNumAllocs) ? fNumAllocs : 1)), fSizeFreed, fNumFrees, (long)(fSizeFreed / ((fNumFrees) ? fNumFrees : 1)), fAllocated ); SysLog::WriteToStderr(buf, strlen(buf)); } } MemTracker *Storage::DoMakeMemTracker(const char *name) { return new MemTracker(name); } MemTracker *Storage::MakeMemTracker(const char *name, bool bThreadSafe) { if (fgHooks && !fgForceGlobal) { return fgHooks->MakeMemTracker(name, bThreadSafe); } return Storage::DoMakeMemTracker(name); } #if (defined(__GNUG__) && __GNUC__ < 3)|| defined (__370__) #include <new.h> #elif (defined(__GNUG__) && __GNUC__ >=3) || (defined(__SUNPRO_CC) && __SUNPRO_CC >= 0x500) || (defined(WIN32) && defined(ONLY_STD_IOSTREAM)) #include <new> #else void *operator new(size_t size, void *vp) { Assert(size > 0); if (vp == 0) { return ::calloc(size, sizeof(char)); } return vp; } #endif #if defined(WIN32) && (_MSC_VER >= 1200) && !defined(ONLY_STD_IOSTREAM)// VC6 or greater void operator delete(void *ptr, void *vp) { if (ptr) { ::free(ptr); } } #endif #if !defined (WIN32) void operator delete(void *ptr) { if (ptr) { ::free(ptr); } } #endif //---- Storage ------------------------------------------ Allocator *Storage::fgGlobalPool = 0; StorageHooks *Storage::fgHooks = 0; // exchange this object when MT_Storage is used bool Storage::fgForceGlobal = false; long Storage::fglStatisticLevel = 0L; class EXPORTDECL_FOUNDATION StorageInitializer : public InitFinisManagerFoundation { public: StorageInitializer(unsigned int uiPriority) : InitFinisManagerFoundation(uiPriority) { IFMTrace("StorageInitializer created\n"); } ~StorageInitializer() {} virtual void DoInit() { IFMTrace("Storage::Initialize\n"); Storage::Initialize(); } virtual void DoFinis() { IFMTrace("Storage::Finalize\n"); Storage::Finalize(); } }; static StorageInitializer *psgStorageInitializer = new StorageInitializer(0); Allocator *Storage::Current() { if (fgHooks && !fgForceGlobal) { return fgHooks->Current(); } return Storage::DoGlobal(); } Allocator *Storage::Global() { if (fgHooks && !fgForceGlobal) { return fgHooks->Global(); } return Storage::DoGlobal(); } void Storage::Initialize() { Storage::DoInitialize(); if (fgHooks && !fgForceGlobal) { fgHooks->Initialize(); } } void Storage::Finalize() { if (fgHooks && !fgForceGlobal) { fgHooks->Finalize(); } Storage::DoFinalize(); } void Storage::DoInitialize() { static bool once = true; if (once) { const char *pEnvVar = getenv("TRACE_STORAGE"); long lLevel = ( ( pEnvVar != 0 ) ? atol(pEnvVar) : 0 ); fglStatisticLevel = lLevel; once = false; } } void Storage::DoFinalize() { // terminate global allocator and force printing statistics above level 1 if ( fglStatisticLevel >= 1 ) { Storage::DoGlobal()->PrintStatistic(2); } } void Storage::PrintStatistic(long lLevel) { DoGlobal()->PrintStatistic(lLevel); } Allocator *Storage::DoGlobal() { if (!Storage::fgGlobalPool) { Storage::fgGlobalPool = new GlobalAllocator(); } return Storage::fgGlobalPool; } StorageHooks *Storage::SetHooks(StorageHooks *h) { StorageHooks *pOldHook = fgHooks; if ( fgHooks ) { fgHooks->Finalize(); } if ( h == NULL && fgHooks ) { fgHooks = fgHooks->GetOldHook(); pOldHook = fgHooks; } else { fgHooks = h; if ( fgHooks != NULL ) { fgHooks->Initialize(); fgHooks->SetOldHook(pOldHook); } } return pOldHook; } //--- Allocator ------------------------------------------------- Allocator::Allocator(long allocatorid) : fAllocatorId(allocatorid) , fRefCnt(0) { } Allocator::~Allocator() { Assert(0 == fRefCnt); } void *Allocator::Calloc(int n, size_t size) { void *ret = Alloc(AllocSize(n, size)); if (ret && n * size > 0) { memset(ret, 0, n * size); } return ret; } void *Allocator::Malloc(size_t size) { return Alloc(AllocSize(size, 1)); } void Allocator::Refresh() { // give the allocator opportunity to reorganize } u_long Allocator::AllocSize(u_long n, size_t size) { return (n * size) + MemoryHeader::AlignedSize(); } void *Allocator::ExtMemStart(void *vp) { if (vp) { Assert(((MemoryHeader *)vp)->fMagic == MemoryHeader::gcMagic); void *s = (((char *)(vp)) + MemoryHeader::AlignedSize()); // fSize does *not* include header // superfluous, Calloc takes care: memset(s, '\0', mh->fSize); return s; } return 0; } MemoryHeader *Allocator::RealMemStart(void *vp) { if ( vp ) { MemoryHeader *mh = (MemoryHeader *) (((char *)(vp)) - MemoryHeader::AlignedSize()); if (mh->fMagic == MemoryHeader::gcMagic) { return mh; } } return 0; } //---- GlobalAllocator ------------------------------------------ GlobalAllocator::GlobalAllocator() : Allocator(11223344L) { fTracker = Storage::MakeMemTracker("GlobalAllocator", false); fTracker->SetId(fAllocatorId); } GlobalAllocator::~GlobalAllocator() { if ( fTracker ) { delete fTracker; } } MemTracker *GlobalAllocator::ReplaceMemTracker(MemTracker *t) { MemTracker *pOld = fTracker; if ( fTracker ) { fTracker = t; } return pOld; } l_long GlobalAllocator::CurrentlyAllocated() { return fTracker->CurrentlyAllocated(); } void GlobalAllocator::PrintStatistic(long lLevel) { fTracker->PrintStatistic(lLevel); } void *GlobalAllocator::Alloc(u_long allocSize) { void *vp = ::malloc(allocSize); if (vp) { MemoryHeader *mh = new(vp) MemoryHeader(allocSize - MemoryHeader::AlignedSize(), MemoryHeader::eUsedNotPooled); fTracker->TrackAlloc(mh); return ExtMemStart(mh); } else { static const char crashmsg[] = "FATAL: GlobalAllocator::Alloc malloc failed. I will crash :-(\n"; SysLog::WriteToStderr(crashmsg, sizeof(crashmsg)); } return NULL; } void GlobalAllocator::Free(void *vp) { if ( vp ) { MemoryHeader *header = RealMemStart(vp); if (header && header->fMagic == MemoryHeader::gcMagic) { Assert(header->fMagic == MemoryHeader::gcMagic); // should combine magic with state Assert(header->fState & MemoryHeader::eUsed); fTracker->TrackFree(header); vp = header; } ::free(vp); } } #ifdef __370__ // need a C-function as the linker cannot resolve C++ here void finalize() { Storage::Finalize(); } #endif Allocator *TestStorageHooks::Global() { return Storage::DoGlobal(); } Allocator *TestStorageHooks::Current() { if (fAllocator) { return fAllocator; } return Storage::DoGlobal(); } void TestStorageHooks::Initialize() { } void TestStorageHooks::Finalize() { } TestStorageHooks::TestStorageHooks(Allocator *wdallocator) : fAllocator(wdallocator) , fpOldHook(NULL) { fpOldHook = Storage::SetHooks(this); } TestStorageHooks::~TestStorageHooks() { StorageHooks *pHook = Storage::SetHooks(NULL); Assert( pHook == fpOldHook && "another Storage::SetHook() was called without restoring old Hook!"); } MemTracker *TestStorageHooks::MakeMemTracker(const char *name, bool) { return new MemTracker(name); } <commit_msg>MemChecker will only print out when memory was consumed and not freed MemTracker will only get created when TRACE_STORAGE >=1 added Storage::Initialize() before creating GlobalAllocator to have a correct value in GetStatisticLevel()<commit_after>/* * Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland * All rights reserved. * * This library/application is free software; you can redistribute and/or modify it under the terms of * the license that is included with this library/application in the file license.txt. */ //--- interface include -------------------------------------------------------- #include "ITOStorage.h" //--- standard modules used ---------------------------------------------------- #include "SysLog.h" #include "System.h" #include "MemHeader.h" #include "InitFinisManagerFoundation.h" //--- c-library modules used --------------------------------------------------- #include <string.h> #ifdef __370__ extern "C" void finalize(); #endif #include <stdio.h> #if defined(WIN32) #define snprintf _snprintf #endif //#define TRACK_USED_MEMORYBLOCKS 1 MemChecker::MemChecker(const char *scope, Allocator *a) : fAllocator(a) , fSizeAllocated(fAllocator->CurrentlyAllocated()) , fScope(scope) { } MemChecker::~MemChecker() { TraceDelta("MemChecker.~MemChecker: "); } void MemChecker::TraceDelta(const char *message) { l_long delta = CheckDelta(); if ( delta > 0 ) { char msgbuf[1024] = {'\0'}; if (message) { SysLog::WriteToStderr( message, strlen(message)); } int bufsz = snprintf(msgbuf, sizeof(msgbuf), "\nMem Usage change by %.0f bytes in %s\n", (double)delta, fScope); SysLog::WriteToStderr( msgbuf, bufsz ); } } l_long MemChecker::CheckDelta() { return fAllocator->CurrentlyAllocated() - fSizeAllocated; } //------------- Utilities for Memory Tracking -------------- MemTracker::MemTracker(const char *name) : fAllocated(0) , fMaxAllocated(0) , fNumAllocs(0) , fSizeAllocated(0) , fNumFrees(0) , fSizeFreed(0) , fId(-1) , fpName(strdup(name)) // copy string to be more flexible when using temporary param objects like Strings { } void *MemTracker::operator new(size_t size) { // never allocate on allocator, because we are tracking exactly the one... void *vp = ::calloc(1, sizeof(MemTracker)); return vp; } void *MemTracker::operator new(size_t size, Allocator *) { // never allocate on allocator, because we are tracking exactly the one... void *vp = ::calloc(1, sizeof(MemTracker)); return vp; } void MemTracker::operator delete(void *vp) { if (vp) { ::operator delete(vp); } } void MemTracker::Init(MemTracker *t) { fAllocated = t->fAllocated; fNumAllocs = t->fNumAllocs; fSizeAllocated = t->fSizeAllocated; fNumFrees = t->fNumFrees; fSizeFreed = t->fSizeFreed; fId = t->fId; fMaxAllocated = t->fMaxAllocated; } MemTracker::~MemTracker() { delete fpName; } void MemTracker::SetId(long id) { fId = id; } void MemTracker::TrackAlloc(MemoryHeader *mh) { fAllocated += mh->fSize; ++fNumAllocs; fSizeAllocated += mh->fSize; fMaxAllocated = itoMAX(fMaxAllocated, fAllocated); #if defined(TRACK_USED_MEMORYBLOCKS) fUsedList.push_front(mh); #endif } void MemTracker::TrackFree(MemoryHeader *mh) { fAllocated -= mh->fSize; ++fNumFrees; fSizeFreed += mh->fSize; #if defined(TRACK_USED_MEMORYBLOCKS) UsedListType::iterator aUsedIterator; for ( aUsedIterator = fUsedList.begin(); aUsedIterator != fUsedList.end(); ++aUsedIterator ) { if ( *aUsedIterator == mh ) { fUsedList.erase(aUsedIterator); break; } } #endif } void MemTracker::DumpUsedBlocks() { if ( fUsedList.size() ) { SysLog::Error("Following memory blocks are still in use:"); UsedListType::const_iterator aUsedIterator; long lIdx = 0; for ( aUsedIterator = fUsedList.begin(); aUsedIterator != fUsedList.end(); ++lIdx, ++aUsedIterator) { MemoryHeader *pMH = *aUsedIterator; String strBuf((void *)pMH, ( pMH->fSize + MemoryHeader::AlignedSize() ), Storage::Global()); SysLog::WriteToStderr(String(Storage::Global()).Append("Block ").Append(lIdx).Append('\n')); SysLog::WriteToStderr(strBuf.DumpAsHex()); SysLog::WriteToStderr("\n"); } } } void MemTracker::PrintStatistic(long lLevel) { if ( lLevel >= 2 ) { char buf[2048] = { 0 }; // safety margin for bytes snprintf(buf, sizeof(buf), "\nAllocator [%02ld] [%s]\n" #if defined(WIN32) "Peek Allocated %20I64d bytes\n" "Total Allocated %20I64d bytes in %15I64d runs (%ld/run)\n" "Total Freed %20I64d bytes in %15I64d runs (%ld/run)\n" "------------------------------------------\n" "Difference %20I64d bytes\n", #else "Peek Allocated %20lld bytes\n" "Total Allocated %20lld bytes in %15lld runs (%ld/run)\n" "Total Freed %20lld bytes in %15lld runs (%ld/run)\n" "------------------------------------------\n" "Difference %20lld bytes\n", #endif fId, fpName, fMaxAllocated, fSizeAllocated , fNumAllocs, (long)(fSizeAllocated / ((fNumAllocs) ? fNumAllocs : 1)), fSizeFreed, fNumFrees, (long)(fSizeFreed / ((fNumFrees) ? fNumFrees : 1)), fAllocated ); SysLog::WriteToStderr(buf, strlen(buf)); } } MemTracker *Storage::DoMakeMemTracker(const char *name) { return new MemTracker(name); } MemTracker *Storage::MakeMemTracker(const char *name, bool bThreadSafe) { if (fgHooks && !fgForceGlobal) { return fgHooks->MakeMemTracker(name, bThreadSafe); } return Storage::DoMakeMemTracker(name); } #if (defined(__GNUG__) && __GNUC__ < 3)|| defined (__370__) #include <new.h> #elif (defined(__GNUG__) && __GNUC__ >=3) || (defined(__SUNPRO_CC) && __SUNPRO_CC >= 0x500) || (defined(WIN32) && defined(ONLY_STD_IOSTREAM)) #include <new> #else void *operator new(size_t size, void *vp) { Assert(size > 0); if (vp == 0) { return ::calloc(size, sizeof(char)); } return vp; } #endif #if defined(WIN32) && (_MSC_VER >= 1200) && !defined(ONLY_STD_IOSTREAM)// VC6 or greater void operator delete(void *ptr, void *vp) { if (ptr) { ::free(ptr); } } #endif #if !defined (WIN32) void operator delete(void *ptr) { if (ptr) { ::free(ptr); } } #endif //---- Storage ------------------------------------------ Allocator *Storage::fgGlobalPool = 0; StorageHooks *Storage::fgHooks = 0; // exchange this object when MT_Storage is used bool Storage::fgForceGlobal = false; long Storage::fglStatisticLevel = 0L; class EXPORTDECL_FOUNDATION StorageInitializer : public InitFinisManagerFoundation { public: StorageInitializer(unsigned int uiPriority) : InitFinisManagerFoundation(uiPriority) { IFMTrace("StorageInitializer created\n"); } ~StorageInitializer() {} virtual void DoInit() { IFMTrace("Storage::Initialize\n"); Storage::Initialize(); } virtual void DoFinis() { IFMTrace("Storage::Finalize\n"); Storage::Finalize(); } }; static StorageInitializer *psgStorageInitializer = new StorageInitializer(0); Allocator *Storage::Current() { if (fgHooks && !fgForceGlobal) { return fgHooks->Current(); } return Storage::DoGlobal(); } Allocator *Storage::Global() { if (fgHooks && !fgForceGlobal) { return fgHooks->Global(); } return Storage::DoGlobal(); } void Storage::Initialize() { Storage::DoInitialize(); if ( fgHooks && !fgForceGlobal ) { fgHooks->Initialize(); } } void Storage::Finalize() { if (fgHooks && !fgForceGlobal) { fgHooks->Finalize(); } Storage::DoFinalize(); } void Storage::DoInitialize() { static bool once = true; if (once) { const char *pEnvVar = getenv("TRACE_STORAGE"); long lLevel = ( ( pEnvVar != 0 ) ? atol(pEnvVar) : 0 ); fglStatisticLevel = lLevel; once = false; } } void Storage::DoFinalize() { // terminate global allocator and force printing statistics above level 1 if ( GetStatisticLevel() >= 1 ) { Storage::DoGlobal()->PrintStatistic(2); } } void Storage::PrintStatistic(long lLevel) { DoGlobal()->PrintStatistic(lLevel); } Allocator *Storage::DoGlobal() { if ( !Storage::fgGlobalPool ) { Storage::Initialize(); Storage::fgGlobalPool = new GlobalAllocator(); } return Storage::fgGlobalPool; } StorageHooks *Storage::SetHooks(StorageHooks *h) { StorageHooks *pOldHook = fgHooks; if ( fgHooks ) { fgHooks->Finalize(); } if ( h == NULL && fgHooks ) { fgHooks = fgHooks->GetOldHook(); pOldHook = fgHooks; } else { fgHooks = h; if ( fgHooks != NULL ) { fgHooks->Initialize(); fgHooks->SetOldHook(pOldHook); } } return pOldHook; } //--- Allocator ------------------------------------------------- Allocator::Allocator(long allocatorid) : fAllocatorId(allocatorid) , fRefCnt(0) { } Allocator::~Allocator() { Assert(0 == fRefCnt); } void *Allocator::Calloc(int n, size_t size) { void *ret = Alloc(AllocSize(n, size)); if (ret && n * size > 0) { memset(ret, 0, n * size); } return ret; } void *Allocator::Malloc(size_t size) { return Alloc(AllocSize(size, 1)); } void Allocator::Refresh() { // give the allocator opportunity to reorganize } u_long Allocator::AllocSize(u_long n, size_t size) { return (n * size) + MemoryHeader::AlignedSize(); } void *Allocator::ExtMemStart(void *vp) { if (vp) { Assert(((MemoryHeader *)vp)->fMagic == MemoryHeader::gcMagic); void *s = (((char *)(vp)) + MemoryHeader::AlignedSize()); // fSize does *not* include header // superfluous, Calloc takes care: memset(s, '\0', mh->fSize); return s; } return 0; } MemoryHeader *Allocator::RealMemStart(void *vp) { if ( vp ) { MemoryHeader *mh = (MemoryHeader *) (((char *)(vp)) - MemoryHeader::AlignedSize()); if (mh->fMagic == MemoryHeader::gcMagic) { return mh; } } return 0; } //---- GlobalAllocator ------------------------------------------ GlobalAllocator::GlobalAllocator() : Allocator(11223344L) , fTracker(NULL) { if ( Storage::GetStatisticLevel() >= 1 ) { fTracker = Storage::MakeMemTracker("GlobalAllocator", false); fTracker->SetId(fAllocatorId); } } GlobalAllocator::~GlobalAllocator() { if ( fTracker ) { delete fTracker; fTracker = NULL; } } MemTracker *GlobalAllocator::ReplaceMemTracker(MemTracker *t) { MemTracker *pOld = fTracker; if ( fTracker ) { fTracker = t; } return pOld; } l_long GlobalAllocator::CurrentlyAllocated() { if ( fTracker ) { return fTracker->CurrentlyAllocated(); } return 0LL; } void GlobalAllocator::PrintStatistic(long lLevel) { if ( fTracker ) { fTracker->PrintStatistic(lLevel); } } void *GlobalAllocator::Alloc(u_long allocSize) { void *vp = ::malloc(allocSize); if (vp) { MemoryHeader *mh = new(vp) MemoryHeader(allocSize - MemoryHeader::AlignedSize(), MemoryHeader::eUsedNotPooled); if ( fTracker ) { fTracker->TrackAlloc(mh); } return ExtMemStart(mh); } else { static const char crashmsg[] = "FATAL: GlobalAllocator::Alloc malloc failed. I will crash :-(\n"; SysLog::WriteToStderr(crashmsg, sizeof(crashmsg)); } return NULL; } void GlobalAllocator::Free(void *vp) { if ( vp ) { MemoryHeader *header = RealMemStart(vp); if (header && header->fMagic == MemoryHeader::gcMagic) { Assert(header->fMagic == MemoryHeader::gcMagic); // should combine magic with state Assert(header->fState & MemoryHeader::eUsed); if ( fTracker ) { fTracker->TrackFree(header); } vp = header; } ::free(vp); } } #ifdef __370__ // need a C-function as the linker cannot resolve C++ here void finalize() { Storage::Finalize(); } #endif Allocator *TestStorageHooks::Global() { return Storage::DoGlobal(); } Allocator *TestStorageHooks::Current() { if (fAllocator) { return fAllocator; } return Storage::DoGlobal(); } void TestStorageHooks::Initialize() { } void TestStorageHooks::Finalize() { } TestStorageHooks::TestStorageHooks(Allocator *wdallocator) : fAllocator(wdallocator) , fpOldHook(NULL) { fpOldHook = Storage::SetHooks(this); } TestStorageHooks::~TestStorageHooks() { StorageHooks *pHook = Storage::SetHooks(NULL); Assert( pHook == fpOldHook && "another Storage::SetHook() was called without restoring old Hook!"); } MemTracker *TestStorageHooks::MakeMemTracker(const char *name, bool) { return new MemTracker(name); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: svborder.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: obo $ $Date: 2005-04-13 12:11:31 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include <svborder.hxx> #include <osl/diagnose.h> SvBorder::SvBorder( const Rectangle & rOuter, const Rectangle & rInner ) { Rectangle aOuter( rOuter ); aOuter.Justify(); Rectangle aInner( rInner ); if( aInner.IsEmpty() ) aInner = Rectangle( aOuter.Center(), aOuter.Center() ); else aInner.Justify(); OSL_ENSURE( aOuter.IsInside( aInner ), "SvBorder::SvBorder: FALSE == aOuter.IsInside( aInner )" ); nTop = aInner.Top() - aOuter.Top(); nRight = aOuter.Right() - aInner.Right(); nBottom = aOuter.Bottom() - aInner.Bottom(); nLeft = aInner.Left() - aOuter.Left(); } Rectangle & operator += ( Rectangle & rRect, const SvBorder & rBorder ) { // wegen Empty-Rect, GetSize muss als erstes gerufen werden Size aS( rRect.GetSize() ); aS.Width() += rBorder.Left() + rBorder.Right(); aS.Height() += rBorder.Top() + rBorder.Bottom(); rRect.Left() -= rBorder.Left(); rRect.Top() -= rBorder.Top(); rRect.SetSize( aS ); return rRect; } Rectangle & operator -= ( Rectangle & rRect, const SvBorder & rBorder ) { // wegen Empty-Rect, GetSize muss als erstes gerufen werden Size aS( rRect.GetSize() ); aS.Width() -= rBorder.Left() + rBorder.Right(); aS.Height() -= rBorder.Top() + rBorder.Bottom(); rRect.Left() += rBorder.Left(); rRect.Top() += rBorder.Top(); rRect.SetSize( aS ); return rRect; } <commit_msg>INTEGRATION: CWS ooo19126 (1.2.44); FILE MERGED 2005/09/05 13:59:20 rt 1.2.44.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: svborder.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-09 14:22:28 $ * * 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 <svborder.hxx> #include <osl/diagnose.h> SvBorder::SvBorder( const Rectangle & rOuter, const Rectangle & rInner ) { Rectangle aOuter( rOuter ); aOuter.Justify(); Rectangle aInner( rInner ); if( aInner.IsEmpty() ) aInner = Rectangle( aOuter.Center(), aOuter.Center() ); else aInner.Justify(); OSL_ENSURE( aOuter.IsInside( aInner ), "SvBorder::SvBorder: FALSE == aOuter.IsInside( aInner )" ); nTop = aInner.Top() - aOuter.Top(); nRight = aOuter.Right() - aInner.Right(); nBottom = aOuter.Bottom() - aInner.Bottom(); nLeft = aInner.Left() - aOuter.Left(); } Rectangle & operator += ( Rectangle & rRect, const SvBorder & rBorder ) { // wegen Empty-Rect, GetSize muss als erstes gerufen werden Size aS( rRect.GetSize() ); aS.Width() += rBorder.Left() + rBorder.Right(); aS.Height() += rBorder.Top() + rBorder.Bottom(); rRect.Left() -= rBorder.Left(); rRect.Top() -= rBorder.Top(); rRect.SetSize( aS ); return rRect; } Rectangle & operator -= ( Rectangle & rRect, const SvBorder & rBorder ) { // wegen Empty-Rect, GetSize muss als erstes gerufen werden Size aS( rRect.GetSize() ); aS.Width() -= rBorder.Left() + rBorder.Right(); aS.Height() -= rBorder.Top() + rBorder.Bottom(); rRect.Left() += rBorder.Left(); rRect.Top() += rBorder.Top(); rRect.SetSize( aS ); return rRect; } <|endoftext|>
<commit_before>// $Id: Hash_test.C,v 1.1 2000/06/03 20:11:59 amoll Exp $ #include <BALL/CONCEPT/classTest.h> /////////////////////////// #include <BALL/COMMON/hash.h> /////////////////////////// START_TEST(class_name, "$Id: Hash_test.C,v 1.1 2000/06/03 20:11:59 amoll Exp $") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace BALL; char* c = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; string s1 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; String s2 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; CHECK(hashString(const char* str)) TEST_EQUAL(hashString(c), 140) RESULT CHECK(hashString2(const char* str)) TEST_EQUAL(hashString2(c), 248) RESULT CHECK(hashString3(const char* str)) TEST_EQUAL(hashString3(c), 3780768363) RESULT CHECK(hashPJWString(const char* str)) TEST_EQUAL(hashPJWString(c), 1450744505) RESULT CHECK(hashElfString(const char* str)) TEST_EQUAL(hashElfString(c), 19269177) RESULT CHECK(Hash(const T& key)) TEST_EQUAL(Hash(1), 1) RESULT CHECK(Hash(const string& s)) TEST_EQUAL(Hash(s1), 140) RESULT CHECK(Hash(const String& s)) TEST_EQUAL(Hash(s2), 140) RESULT CHECK(Hash(void *const& ptr)) //TEST_EQUAL(Hash(c), 248) RESULT CHECK(getNextPrime(HashIndex l)) TEST_EQUAL(getNextPrime(4), 248) RESULT ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST <commit_msg>fixed: test for hashString3, getNextPrime changed: test for broken function hashString3 commented out<commit_after>// $Id: Hash_test.C,v 1.2 2000/06/06 09:46:02 oliver Exp $ #include <BALL/CONCEPT/classTest.h> /////////////////////////// #include <BALL/COMMON/hash.h> /////////////////////////// START_TEST(class_name, "$Id: Hash_test.C,v 1.2 2000/06/06 09:46:02 oliver Exp $") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace BALL; char* c = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; string s1 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; String s2 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; CHECK(hashString(const char* str)) TEST_EQUAL(hashString(c), 140) RESULT CHECK(hashString2(const char* str)) //TEST_EQUAL(hashString2(c), 248) RESULT CHECK(hashString3(const char* str)) TEST_EQUAL(hashString3(c), 3780768363U) RESULT CHECK(hashPJWString(const char* str)) TEST_EQUAL(hashPJWString(c), 1450744505U) RESULT CHECK(hashElfString(const char* str)) TEST_EQUAL(hashElfString(c), 19269177) RESULT CHECK(Hash(const T& key)) TEST_EQUAL(Hash(1), 1) RESULT CHECK(Hash(const string& s)) TEST_EQUAL(Hash(s1), 140) RESULT CHECK(Hash(const String& s)) TEST_EQUAL(Hash(s2), 140) RESULT CHECK(Hash(void *const& ptr)) //TEST_EQUAL(Hash(c), 248) RESULT CHECK(getNextPrime(HashIndex l)) TEST_EQUAL(getNextPrime(0), 3) TEST_EQUAL(getNextPrime(1), 3) TEST_EQUAL(getNextPrime(4), 5) RESULT ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST <|endoftext|>
<commit_before>// RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDelete,unix.Malloc -std=c++11 -fblocks -verify %s // RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDelete,cplusplus.NewDeleteLeaks,unix.Malloc -std=c++11 -DLEAKS=1 -fblocks -verify %s // RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDelete,unix.Malloc -std=c++11 -analyzer-config c++-allocator-inlining=true -DALLOCATOR_INLINING=1 -fblocks -verify %s // RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDelete,cplusplus.NewDeleteLeaks,unix.Malloc -std=c++11 -analyzer-config c++-allocator-inlining=true -DLEAKS=1 -DALLOCATOR_INLINING=1 -fblocks -verify %s #include "Inputs/system-header-simulator-cxx.h" #if !LEAKS // expected-no-diagnostics #endif void *allocator(std::size_t size); void *operator new[](std::size_t size) throw() { return allocator(size); } void *operator new(std::size_t size) throw() { return allocator(size); } void *operator new(std::size_t size, const std::nothrow_t &nothrow) throw() { return allocator(size); } void *operator new(std::size_t, double d); class C { public: void *operator new(std::size_t); }; void testNewMethod() { void *p1 = C::operator new(0); // no warn C *p2 = new C; // no warn C *c3 = ::new C; } #if LEAKS && !ALLOCATOR_INLINING // expected-warning@-2{{Potential leak of memory pointed to by 'c3'}} #endif void testOpNewArray() { void *p = operator new[](0); // call is inlined, no warn } void testNewExprArray() { int *p = new int[0]; } #if LEAKS && !ALLOCATOR_INLINING // expected-warning@-2{{Potential leak of memory pointed to by 'p'}} #endif //----- Custom non-placement operators void testOpNew() { void *p = operator new(0); // call is inlined, no warn } void testNewExpr() { int *p = new int; } #if LEAKS && !ALLOCATOR_INLINING // expected-warning@-2{{Potential leak of memory pointed to by 'p'}} #endif //----- Custom NoThrow placement operators void testOpNewNoThrow() { void *p = operator new(0, std::nothrow); // call is inlined, no warn } #if LEAKS // expected-warning@-2{{Potential leak of memory pointed to by 'p'}} #endif void testNewExprNoThrow() { int *p = new(std::nothrow) int; } #if LEAKS // expected-warning@-2{{Potential leak of memory pointed to by 'p'}} #endif //----- Custom placement operators void testOpNewPlacement() { void *p = operator new(0, 0.1); // no warn } void testNewExprPlacement() { int *p = new(0.1) int; // no warn } <commit_msg>[analyzer] NFC: operator new: Fix new(nothrow) definition in tests.<commit_after>// RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDelete,unix.Malloc -std=c++11 -fblocks -verify %s // RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDelete,cplusplus.NewDeleteLeaks,unix.Malloc -std=c++11 -DLEAKS=1 -fblocks -verify %s // RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDelete,unix.Malloc -std=c++11 -analyzer-config c++-allocator-inlining=true -DALLOCATOR_INLINING=1 -fblocks -verify %s // RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDelete,cplusplus.NewDeleteLeaks,unix.Malloc -std=c++11 -analyzer-config c++-allocator-inlining=true -DLEAKS=1 -DALLOCATOR_INLINING=1 -fblocks -verify %s #include "Inputs/system-header-simulator-cxx.h" #if !(LEAKS && !ALLOCATOR_INLINING) // expected-no-diagnostics #endif void *allocator(std::size_t size); void *operator new[](std::size_t size) throw() { return allocator(size); } void *operator new(std::size_t size) throw() { return allocator(size); } void *operator new(std::size_t size, const std::nothrow_t &nothrow) throw() { return allocator(size); } void *operator new(std::size_t, double d); class C { public: void *operator new(std::size_t); }; void testNewMethod() { void *p1 = C::operator new(0); // no warn C *p2 = new C; // no warn C *c3 = ::new C; } #if LEAKS && !ALLOCATOR_INLINING // expected-warning@-2{{Potential leak of memory pointed to by 'c3'}} #endif void testOpNewArray() { void *p = operator new[](0); // call is inlined, no warn } void testNewExprArray() { int *p = new int[0]; } #if LEAKS && !ALLOCATOR_INLINING // expected-warning@-2{{Potential leak of memory pointed to by 'p'}} #endif //----- Custom non-placement operators void testOpNew() { void *p = operator new(0); // call is inlined, no warn } void testNewExpr() { int *p = new int; } #if LEAKS && !ALLOCATOR_INLINING // expected-warning@-2{{Potential leak of memory pointed to by 'p'}} #endif //----- Custom NoThrow placement operators void testOpNewNoThrow() { void *p = operator new(0, std::nothrow); // call is inlined, no warn } void testNewExprNoThrow() { int *p = new(std::nothrow) int; } #if LEAKS && !ALLOCATOR_INLINING // expected-warning@-2{{Potential leak of memory pointed to by 'p'}} #endif //----- Custom placement operators void testOpNewPlacement() { void *p = operator new(0, 0.1); // no warn } void testNewExprPlacement() { int *p = new(0.1) int; // no warn } <|endoftext|>
<commit_before>#ifndef RESOURCE_MANAGER_HPP #define RESOURCE_MANAGER_HPP #include <iostream> #include <SDL2/SDL.h> #include <string> #include <map> #include <iostream> #include <SDL2/SDL_image.h> #ifdef __EMSCRIPTEN__ #include <SDL/SDL_mixer.h> #else #include <SDL2/SDL_mixer.h> #endif class ResourceManager { public: /***/ ~ResourceManager() { for(auto e : m_textures) { SDL_DestroyTexture(e.second); } for(auto e : m_sounds) { Mix_FreeChunk(e.second); } } /***/ bool load_texture(const std::string &key, const std::string &path, SDL_Renderer *ren) { SDL_Texture *texture; texture = IMG_LoadTexture(ren, path.c_str()); if (!texture) { std::cerr << "IMG_Load:" << IMG_GetError() << std::endl; return false; } m_textures[key] = texture; return true; } /***/ bool load_sound(std::string key, std::string &path) { Mix_Chunk *new_sound = Mix_LoadWAV(path.c_str()); if (new_sound == NULL) { std::cerr << "Error: could not load sound from" << path << std::endl; return false; } m_sounds[key] = new_sound; return true; } /***/ bool load_music(std::string key, std::string &path) { Mix_Music *new_music = Mix_LoadMUS(path.c_str()); if (new_music == NULL) { std::cerr << "Error: could not load sound from " << path << ": "<< Mix_GetError() << std::endl; return false; } m_music[key] = new_music; return true; } /***/ SDL_Texture* get_texture(std::string texture_key) { return m_textures.at(texture_key); } /***/ Mix_Chunk* get_sound(std::string sound_key) { return m_sounds.at(sound_key); } /***/ Mix_Music* get_music(std::string music_key) { return m_music.at(music_key); } private: std::map<std::string, SDL_Texture*> m_textures; std::map<std::string, Mix_Chunk*> m_sounds; std::map<std::string, Mix_Music*> m_music; }; #endif <commit_msg>ResourceManager: Fix string passing<commit_after>#ifndef RESOURCE_MANAGER_HPP #define RESOURCE_MANAGER_HPP #include <iostream> #include <SDL2/SDL.h> #include <string> #include <map> #include <iostream> #include <SDL2/SDL_image.h> #ifdef __EMSCRIPTEN__ #include <SDL/SDL_mixer.h> #else #include <SDL2/SDL_mixer.h> #endif class ResourceManager { public: /***/ ~ResourceManager() { for(auto e : m_textures) { SDL_DestroyTexture(e.second); } for(auto e : m_sounds) { Mix_FreeChunk(e.second); } } /***/ bool load_texture(const std::string &key, const std::string &path, SDL_Renderer *ren) { SDL_Texture *texture; texture = IMG_LoadTexture(ren, path.c_str()); if (!texture) { std::cerr << "IMG_Load:" << IMG_GetError() << std::endl; return false; } m_textures[key] = texture; return true; } /***/ bool load_sound(const std::string &key, const std::string &path) { Mix_Chunk *new_sound = Mix_LoadWAV(path.c_str()); if (new_sound == NULL) { std::cerr << "Error: could not load sound from" << path << std::endl; return false; } m_sounds[key] = new_sound; return true; } /***/ bool load_music(const std::string &key, const std::string &path) { Mix_Music *new_music = Mix_LoadMUS(path.c_str()); if (new_music == NULL) { std::cerr << "Error: could not load sound from " << path << ": "<< Mix_GetError() << std::endl; return false; } m_music[key] = new_music; return true; } /***/ SDL_Texture* get_texture(std::string texture_key) { return m_textures.at(texture_key); } /***/ Mix_Chunk* get_sound(std::string sound_key) { return m_sounds.at(sound_key); } /***/ Mix_Music* get_music(std::string music_key) { return m_music.at(music_key); } private: std::map<std::string, SDL_Texture*> m_textures; std::map<std::string, Mix_Chunk*> m_sounds; std::map<std::string, Mix_Music*> m_music; }; #endif <|endoftext|>
<commit_before>#include <b5m-manager/product_matcher.h> #include <common/ScdWriter.h> #include <common/ScdTypeWriter.h> #include <boost/program_options.hpp> using namespace sf1r; namespace po = boost::program_options; int main(int ac, char** av) { po::options_description desc("Allowed options"); desc.add_options() ("help", "produce help message") ("knowledge-dir,K", po::value<std::string>(), "specify knowledge dir") ("scd-path,S", po::value<std::string>(), "specify scd path") ("discover", po::value<std::string>(), "specify whether do the new spu discover and the output directory") ; po::variables_map vm; po::store(po::parse_command_line(ac, av, desc), vm); po::notify(vm); if (vm.count("help")) { std::cout << desc << std::endl; return 1; } std::string scd_path; std::string knowledge_dir; if (vm.count("scd-path")) { scd_path = vm["scd-path"].as<std::string>(); std::cout << "scd-path: " << scd_path <<std::endl; } if (vm.count("knowledge-dir")) { knowledge_dir = vm["knowledge-dir"].as<std::string>(); std::cout << "knowledge-dir: " << knowledge_dir <<std::endl; } std::string discover; if(vm.count("discover")) { discover = vm["discover"].as<std::string>(); std::cout << "discover: " << discover <<std::endl; } if( knowledge_dir.empty()||scd_path.empty()) { return EXIT_FAILURE; } ProductMatcher matcher; //matcher.SetCmaPath(cma_path); if(!matcher.Open(knowledge_dir)) { LOG(ERROR)<<"matcher open failed"<<std::endl; return EXIT_FAILURE; } std::vector<std::string> scd_list; ScdParser::getScdList(scd_path, scd_list); izenelib::util::ClockTimer clocker; uint32_t all_count = 0; uint32_t match_count = 0; boost::shared_ptr<ScdTypeWriter> discover_writer; if(!discover.empty()) { boost::filesystem::remove_all(discover); boost::filesystem::create_directories(discover); discover_writer.reset(new ScdTypeWriter(discover)); } for(uint32_t i=0;i<scd_list.size();i++) { std::string scd_file = scd_list[i]; LOG(INFO)<<"Processing "<<scd_file<<std::endl; ScdParser parser(izenelib::util::UString::UTF_8); parser.load(scd_file); uint32_t n=0; for( ScdParser::iterator doc_iter = parser.begin(); doc_iter!= parser.end(); ++doc_iter, ++n) { SCDDoc& scddoc = *(*doc_iter); SCDDoc::iterator p = scddoc.begin(); Document doc; for(; p!=scddoc.end(); ++p) { const std::string& property_name = p->first; doc.property(property_name) = p->second; } UString e_dattrib; UString e_fattrib; doc.getProperty("DisplayAttribute", e_dattrib); doc.getProperty("FilterAttribute", e_fattrib); std::string stitle; doc.getString("Title", stitle); ProductMatcher::Product result_product; matcher.Process(doc, result_product, true); all_count++; bool spu_match = false; if(!result_product.stitle.empty()) { spu_match = true; match_count++; } if(!spu_match) { LOG(ERROR)<<"unmatch for "<<stitle<<std::endl; if(discover_writer) { discover_writer->Append(doc, INSERT_SCD); } //return EXIT_FAILURE; } else { LOG(INFO)<<"spumatch for "<<stitle<<" to "<<result_product.stitle<<std::endl; if( discover_writer && (!e_dattrib.empty()||!e_fattrib.empty()) && (result_product.display_attributes.empty()&&result_product.filter_attributes.empty())) { Document sdoc; sdoc.property("DOCID") = UString(result_product.spid, UString::UTF_8); sdoc.property("Title") = UString(result_product.stitle, UString::UTF_8); if(!e_dattrib.empty()) { sdoc.property("DisplayAttribute") = e_dattrib; } if(!e_fattrib.empty()) { sdoc.property("FilterAttribute") = e_fattrib; } discover_writer->Append(sdoc, UPDATE_SCD); } } } } if(discover_writer) { discover_writer->Close(); } std::cerr<<"clocker used "<<clocker.elapsed()<<std::endl; std::cerr<<"stat "<<all_count<<","<<match_count<<","<<all_count-match_count<<std::endl; return EXIT_SUCCESS; } <commit_msg>use the propstr interface for propterty value<commit_after>#include <b5m-manager/product_matcher.h> #include <common/ScdWriter.h> #include <common/ScdTypeWriter.h> #include <boost/program_options.hpp> using namespace sf1r; namespace po = boost::program_options; int main(int ac, char** av) { po::options_description desc("Allowed options"); desc.add_options() ("help", "produce help message") ("knowledge-dir,K", po::value<std::string>(), "specify knowledge dir") ("scd-path,S", po::value<std::string>(), "specify scd path") ("discover", po::value<std::string>(), "specify whether do the new spu discover and the output directory") ; po::variables_map vm; po::store(po::parse_command_line(ac, av, desc), vm); po::notify(vm); if (vm.count("help")) { std::cout << desc << std::endl; return 1; } std::string scd_path; std::string knowledge_dir; if (vm.count("scd-path")) { scd_path = vm["scd-path"].as<std::string>(); std::cout << "scd-path: " << scd_path <<std::endl; } if (vm.count("knowledge-dir")) { knowledge_dir = vm["knowledge-dir"].as<std::string>(); std::cout << "knowledge-dir: " << knowledge_dir <<std::endl; } std::string discover; if(vm.count("discover")) { discover = vm["discover"].as<std::string>(); std::cout << "discover: " << discover <<std::endl; } if( knowledge_dir.empty()||scd_path.empty()) { return EXIT_FAILURE; } ProductMatcher matcher; //matcher.SetCmaPath(cma_path); if(!matcher.Open(knowledge_dir)) { LOG(ERROR)<<"matcher open failed"<<std::endl; return EXIT_FAILURE; } std::vector<std::string> scd_list; ScdParser::getScdList(scd_path, scd_list); izenelib::util::ClockTimer clocker; uint32_t all_count = 0; uint32_t match_count = 0; boost::shared_ptr<ScdTypeWriter> discover_writer; if(!discover.empty()) { boost::filesystem::remove_all(discover); boost::filesystem::create_directories(discover); discover_writer.reset(new ScdTypeWriter(discover)); } for(uint32_t i=0;i<scd_list.size();i++) { std::string scd_file = scd_list[i]; LOG(INFO)<<"Processing "<<scd_file<<std::endl; ScdParser parser(izenelib::util::UString::UTF_8); parser.load(scd_file); uint32_t n=0; for( ScdParser::iterator doc_iter = parser.begin(); doc_iter!= parser.end(); ++doc_iter, ++n) { SCDDoc& scddoc = *(*doc_iter); SCDDoc::iterator p = scddoc.begin(); Document doc; for(; p!=scddoc.end(); ++p) { const std::string& property_name = p->first; doc.property(property_name) = p->second; } Document::doc_prop_value_strtype e_dattrib; Document::doc_prop_value_strtype e_fattrib; doc.getProperty("DisplayAttribute", e_dattrib); doc.getProperty("FilterAttribute", e_fattrib); std::string stitle; doc.getString("Title", stitle); ProductMatcher::Product result_product; matcher.Process(doc, result_product, true); all_count++; bool spu_match = false; if(!result_product.stitle.empty()) { spu_match = true; match_count++; } if(!spu_match) { LOG(ERROR)<<"unmatch for "<<stitle<<std::endl; if(discover_writer) { discover_writer->Append(doc, INSERT_SCD); } //return EXIT_FAILURE; } else { LOG(INFO)<<"spumatch for "<<stitle<<" to "<<result_product.stitle<<std::endl; if( discover_writer && (!e_dattrib.empty()||!e_fattrib.empty()) && (result_product.display_attributes.empty()&&result_product.filter_attributes.empty())) { Document sdoc; sdoc.property("DOCID") = str_to_propstr(result_product.spid, UString::UTF_8); sdoc.property("Title") = str_to_propstr(result_product.stitle, UString::UTF_8); if(!e_dattrib.empty()) { sdoc.property("DisplayAttribute") = e_dattrib; } if(!e_fattrib.empty()) { sdoc.property("FilterAttribute") = e_fattrib; } discover_writer->Append(sdoc, UPDATE_SCD); } } } } if(discover_writer) { discover_writer->Close(); } std::cerr<<"clocker used "<<clocker.elapsed()<<std::endl; std::cerr<<"stat "<<all_count<<","<<match_count<<","<<all_count-match_count<<std::endl; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: sdrmasterpagedescriptor.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: vg $ $Date: 2005-03-07 17:33:24 $ * * 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 _SDR_MASTERPAGEDESCRIPTOR_HXX #include <sdrmasterpagedescriptor.hxx> #endif #ifndef _SDR_CONTACT_VIEWCONTACTOFMASTERPAGEDESCRIPTOR_HXX #include <svx/sdr/contact/viewcontactofmasterpagedescriptor.hxx> #endif #ifndef _SVDPAGE_HXX #include <svdpage.hxx> #endif // #i42075# #ifndef _SVDOBJ_HXX #include <svdobj.hxx> #endif ////////////////////////////////////////////////////////////////////////////// namespace sdr { // ViewContact part sdr::contact::ViewContact* MasterPageDescriptor::CreateObjectSpecificViewContact() { return new sdr::contact::ViewContactOfMasterPageDescriptor(*this); } MasterPageDescriptor::MasterPageDescriptor(SdrPage& aOwnerPage, SdrPage& aUsedPage) : maOwnerPage(aOwnerPage), maUsedPage(aUsedPage), mpViewContact(0L) { // all layers visible maVisibleLayers.SetAll(); // register at used page maUsedPage.AddPageUser(*this); } MasterPageDescriptor::~MasterPageDescriptor() { // de-register at used page maUsedPage.RemovePageUser(*this); if(mpViewContact) { mpViewContact->PrepareDelete(); delete mpViewContact; mpViewContact = 0L; } } // ViewContact part sdr::contact::ViewContact& MasterPageDescriptor::GetViewContact() const { if(!mpViewContact) { ((MasterPageDescriptor*)this)->mpViewContact = ((MasterPageDescriptor*)this)->CreateObjectSpecificViewContact(); } return *mpViewContact; } // this method is called form the destructor of the referenced page. // do all necessary action to forget the page. It is not necessary to call // RemovePageUser(), that is done form the destructor. void MasterPageDescriptor::PageInDestruction(const SdrPage& rPage) { maOwnerPage.TRG_ClearMasterPage(); } void MasterPageDescriptor::SetVisibleLayers(const SetOfByte& rNew) { if(rNew != maVisibleLayers) { maVisibleLayers = rNew; GetViewContact().ActionChanged(); // #i42075# For AFs convenience, do a change notify at the MasterPageBackgroundObject, too SdrObject* pObject = GetBackgroundObject(); if(pObject) { pObject->BroadcastObjectChange(); } } } // operators sal_Bool MasterPageDescriptor::operator==(const MasterPageDescriptor& rCandidate) const { return (&maOwnerPage == &rCandidate.maOwnerPage && &maUsedPage == &rCandidate.maUsedPage && maVisibleLayers == rCandidate.maVisibleLayers); } sal_Bool MasterPageDescriptor::operator!=(const MasterPageDescriptor& rCandidate) const { return (&maOwnerPage != &rCandidate.maOwnerPage || &maUsedPage != &rCandidate.maUsedPage || maVisibleLayers != rCandidate.maVisibleLayers); } // #i42075# Get the correct BackgroundObject SdrObject* MasterPageDescriptor::GetBackgroundObject() const { SdrObject* pRetval = 0L; const SdrPage& rMasterPage = GetUsedPage(); // Here i will rely on old knowledge about the 0'st element of a masterpage // being the PageBackgroundObject. This will be removed again when that definition // will be changed. const sal_uInt32 nMasterPageObjectCount(rMasterPage.GetObjCount()); DBG_ASSERT(1 <= nMasterPageObjectCount, "MasterPageDescriptor::GetBackgroundObject(): MasterPageBackgroundObject missing (!)"); pRetval = rMasterPage.GetObj(0L); // Test if it's really what we need. There are known problems where // the 0th object is not the MasterPageBackgroundObject at all. if(!pRetval->IsMasterPageBackgroundObject()) { pRetval = 0L; } // Get the evtl. existing page background object from the using page and use it // preferred to the MasterPageBackgroundObject const SdrPage& rOwnerPage = GetOwnerPage(); SdrObject* pCandidate = rOwnerPage.GetBackgroundObj(); if(pCandidate) { pRetval = pCandidate; } return pRetval; } } // end of namespace sdr ////////////////////////////////////////////////////////////////////////////// // eof <commit_msg>INTEGRATION: CWS ooo19126 (1.4.294); FILE MERGED 2005/09/05 14:27:01 rt 1.4.294.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: sdrmasterpagedescriptor.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-09-09 00:23:12 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SDR_MASTERPAGEDESCRIPTOR_HXX #include <sdrmasterpagedescriptor.hxx> #endif #ifndef _SDR_CONTACT_VIEWCONTACTOFMASTERPAGEDESCRIPTOR_HXX #include <svx/sdr/contact/viewcontactofmasterpagedescriptor.hxx> #endif #ifndef _SVDPAGE_HXX #include <svdpage.hxx> #endif // #i42075# #ifndef _SVDOBJ_HXX #include <svdobj.hxx> #endif ////////////////////////////////////////////////////////////////////////////// namespace sdr { // ViewContact part sdr::contact::ViewContact* MasterPageDescriptor::CreateObjectSpecificViewContact() { return new sdr::contact::ViewContactOfMasterPageDescriptor(*this); } MasterPageDescriptor::MasterPageDescriptor(SdrPage& aOwnerPage, SdrPage& aUsedPage) : maOwnerPage(aOwnerPage), maUsedPage(aUsedPage), mpViewContact(0L) { // all layers visible maVisibleLayers.SetAll(); // register at used page maUsedPage.AddPageUser(*this); } MasterPageDescriptor::~MasterPageDescriptor() { // de-register at used page maUsedPage.RemovePageUser(*this); if(mpViewContact) { mpViewContact->PrepareDelete(); delete mpViewContact; mpViewContact = 0L; } } // ViewContact part sdr::contact::ViewContact& MasterPageDescriptor::GetViewContact() const { if(!mpViewContact) { ((MasterPageDescriptor*)this)->mpViewContact = ((MasterPageDescriptor*)this)->CreateObjectSpecificViewContact(); } return *mpViewContact; } // this method is called form the destructor of the referenced page. // do all necessary action to forget the page. It is not necessary to call // RemovePageUser(), that is done form the destructor. void MasterPageDescriptor::PageInDestruction(const SdrPage& rPage) { maOwnerPage.TRG_ClearMasterPage(); } void MasterPageDescriptor::SetVisibleLayers(const SetOfByte& rNew) { if(rNew != maVisibleLayers) { maVisibleLayers = rNew; GetViewContact().ActionChanged(); // #i42075# For AFs convenience, do a change notify at the MasterPageBackgroundObject, too SdrObject* pObject = GetBackgroundObject(); if(pObject) { pObject->BroadcastObjectChange(); } } } // operators sal_Bool MasterPageDescriptor::operator==(const MasterPageDescriptor& rCandidate) const { return (&maOwnerPage == &rCandidate.maOwnerPage && &maUsedPage == &rCandidate.maUsedPage && maVisibleLayers == rCandidate.maVisibleLayers); } sal_Bool MasterPageDescriptor::operator!=(const MasterPageDescriptor& rCandidate) const { return (&maOwnerPage != &rCandidate.maOwnerPage || &maUsedPage != &rCandidate.maUsedPage || maVisibleLayers != rCandidate.maVisibleLayers); } // #i42075# Get the correct BackgroundObject SdrObject* MasterPageDescriptor::GetBackgroundObject() const { SdrObject* pRetval = 0L; const SdrPage& rMasterPage = GetUsedPage(); // Here i will rely on old knowledge about the 0'st element of a masterpage // being the PageBackgroundObject. This will be removed again when that definition // will be changed. const sal_uInt32 nMasterPageObjectCount(rMasterPage.GetObjCount()); DBG_ASSERT(1 <= nMasterPageObjectCount, "MasterPageDescriptor::GetBackgroundObject(): MasterPageBackgroundObject missing (!)"); pRetval = rMasterPage.GetObj(0L); // Test if it's really what we need. There are known problems where // the 0th object is not the MasterPageBackgroundObject at all. if(!pRetval->IsMasterPageBackgroundObject()) { pRetval = 0L; } // Get the evtl. existing page background object from the using page and use it // preferred to the MasterPageBackgroundObject const SdrPage& rOwnerPage = GetOwnerPage(); SdrObject* pCandidate = rOwnerPage.GetBackgroundObj(); if(pCandidate) { pRetval = pCandidate; } return pRetval; } } // end of namespace sdr ////////////////////////////////////////////////////////////////////////////// // eof <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: sdrmasterpagedescriptor.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: hr $ $Date: 2004-10-12 10:09:56 $ * * 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 _SDR_MASTERPAGEDESCRIPTOR_HXX #include <sdrmasterpagedescriptor.hxx> #endif #ifndef _SDR_CONTACT_VIEWCONTACTOFMASTERPAGEDESCRIPTOR_HXX #include <svx/sdr/contact/viewcontactofmasterpagedescriptor.hxx> #endif #ifndef _SVDPAGE_HXX #include <svdpage.hxx> #endif ////////////////////////////////////////////////////////////////////////////// namespace sdr { // ViewContact part sdr::contact::ViewContact* MasterPageDescriptor::CreateObjectSpecificViewContact() { return new sdr::contact::ViewContactOfMasterPageDescriptor(*this); } MasterPageDescriptor::MasterPageDescriptor(SdrPage& aOwnerPage, SdrPage& aUsedPage) : maOwnerPage(aOwnerPage), maUsedPage(aUsedPage), mpViewContact(0L) { // all layers visible maVisibleLayers.SetAll(); // register at used page maUsedPage.AddPageUser(*this); } MasterPageDescriptor::~MasterPageDescriptor() { // de-register at used page maUsedPage.RemovePageUser(*this); if(mpViewContact) { mpViewContact->PrepareDelete(); delete mpViewContact; mpViewContact = 0L; } } // ViewContact part sdr::contact::ViewContact& MasterPageDescriptor::GetViewContact() const { if(!mpViewContact) { ((MasterPageDescriptor*)this)->mpViewContact = ((MasterPageDescriptor*)this)->CreateObjectSpecificViewContact(); } return *mpViewContact; } // this method is called form the destructor of the referenced page. // do all necessary action to forget the page. It is not necessary to call // RemovePageUser(), that is done form the destructor. void MasterPageDescriptor::PageInDestruction(const SdrPage& rPage) { maOwnerPage.TRG_ClearMasterPage(); } void MasterPageDescriptor::SetVisibleLayers(const SetOfByte& rNew) { if(rNew != maVisibleLayers) { maVisibleLayers = rNew; GetViewContact().ActionChanged(); } } // operators sal_Bool MasterPageDescriptor::operator==(const MasterPageDescriptor& rCandidate) const { return (&maOwnerPage == &rCandidate.maOwnerPage && &maUsedPage == &rCandidate.maUsedPage && maVisibleLayers == rCandidate.maVisibleLayers); } sal_Bool MasterPageDescriptor::operator!=(const MasterPageDescriptor& rCandidate) const { return (&maOwnerPage != &rCandidate.maOwnerPage || &maUsedPage != &rCandidate.maUsedPage || maVisibleLayers != rCandidate.maVisibleLayers); } } // end of namespace sdr ////////////////////////////////////////////////////////////////////////////// // eof <commit_msg>INTEGRATION: CWS aw028 (1.3.334); FILE MERGED 2005/03/02 19:52:56 aw 1.3.334.1: #i42075#<commit_after>/************************************************************************* * * $RCSfile: sdrmasterpagedescriptor.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: vg $ $Date: 2005-03-07 17:33:24 $ * * 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 _SDR_MASTERPAGEDESCRIPTOR_HXX #include <sdrmasterpagedescriptor.hxx> #endif #ifndef _SDR_CONTACT_VIEWCONTACTOFMASTERPAGEDESCRIPTOR_HXX #include <svx/sdr/contact/viewcontactofmasterpagedescriptor.hxx> #endif #ifndef _SVDPAGE_HXX #include <svdpage.hxx> #endif // #i42075# #ifndef _SVDOBJ_HXX #include <svdobj.hxx> #endif ////////////////////////////////////////////////////////////////////////////// namespace sdr { // ViewContact part sdr::contact::ViewContact* MasterPageDescriptor::CreateObjectSpecificViewContact() { return new sdr::contact::ViewContactOfMasterPageDescriptor(*this); } MasterPageDescriptor::MasterPageDescriptor(SdrPage& aOwnerPage, SdrPage& aUsedPage) : maOwnerPage(aOwnerPage), maUsedPage(aUsedPage), mpViewContact(0L) { // all layers visible maVisibleLayers.SetAll(); // register at used page maUsedPage.AddPageUser(*this); } MasterPageDescriptor::~MasterPageDescriptor() { // de-register at used page maUsedPage.RemovePageUser(*this); if(mpViewContact) { mpViewContact->PrepareDelete(); delete mpViewContact; mpViewContact = 0L; } } // ViewContact part sdr::contact::ViewContact& MasterPageDescriptor::GetViewContact() const { if(!mpViewContact) { ((MasterPageDescriptor*)this)->mpViewContact = ((MasterPageDescriptor*)this)->CreateObjectSpecificViewContact(); } return *mpViewContact; } // this method is called form the destructor of the referenced page. // do all necessary action to forget the page. It is not necessary to call // RemovePageUser(), that is done form the destructor. void MasterPageDescriptor::PageInDestruction(const SdrPage& rPage) { maOwnerPage.TRG_ClearMasterPage(); } void MasterPageDescriptor::SetVisibleLayers(const SetOfByte& rNew) { if(rNew != maVisibleLayers) { maVisibleLayers = rNew; GetViewContact().ActionChanged(); // #i42075# For AFs convenience, do a change notify at the MasterPageBackgroundObject, too SdrObject* pObject = GetBackgroundObject(); if(pObject) { pObject->BroadcastObjectChange(); } } } // operators sal_Bool MasterPageDescriptor::operator==(const MasterPageDescriptor& rCandidate) const { return (&maOwnerPage == &rCandidate.maOwnerPage && &maUsedPage == &rCandidate.maUsedPage && maVisibleLayers == rCandidate.maVisibleLayers); } sal_Bool MasterPageDescriptor::operator!=(const MasterPageDescriptor& rCandidate) const { return (&maOwnerPage != &rCandidate.maOwnerPage || &maUsedPage != &rCandidate.maUsedPage || maVisibleLayers != rCandidate.maVisibleLayers); } // #i42075# Get the correct BackgroundObject SdrObject* MasterPageDescriptor::GetBackgroundObject() const { SdrObject* pRetval = 0L; const SdrPage& rMasterPage = GetUsedPage(); // Here i will rely on old knowledge about the 0'st element of a masterpage // being the PageBackgroundObject. This will be removed again when that definition // will be changed. const sal_uInt32 nMasterPageObjectCount(rMasterPage.GetObjCount()); DBG_ASSERT(1 <= nMasterPageObjectCount, "MasterPageDescriptor::GetBackgroundObject(): MasterPageBackgroundObject missing (!)"); pRetval = rMasterPage.GetObj(0L); // Test if it's really what we need. There are known problems where // the 0th object is not the MasterPageBackgroundObject at all. if(!pRetval->IsMasterPageBackgroundObject()) { pRetval = 0L; } // Get the evtl. existing page background object from the using page and use it // preferred to the MasterPageBackgroundObject const SdrPage& rOwnerPage = GetOwnerPage(); SdrObject* pCandidate = rOwnerPage.GetBackgroundObj(); if(pCandidate) { pRetval = pCandidate; } return pRetval; } } // end of namespace sdr ////////////////////////////////////////////////////////////////////////////// // eof <|endoftext|>
<commit_before>#include <OpenGLTexture.h> #include <TextureRef.h> #include <Image.h> #include <Surface.h> #define GL_GLEXT_PROTOTYPES #if defined __APPLE__ #include <OpenGLES/ES3/gl.h> #include <OpenGLES/ES3/glext.h> #elif (defined GL_ES) #include <GLES3/gl3.h> #include <EGL/egl.h> #include <EGL/eglext.h> #else #define GL_GLEXT_PROTOTYPES #ifdef _WIN32 #include <GL/glew.h> #include <windows.h> #endif #ifdef ANDROID #include <GLES3/gl3.h> #include <GLES3/gl3ext.h> #else #include <GL/gl.h> #ifdef _WIN32 #include "glext.h" #else #include <GL/glext.h> #endif #endif #endif #if defined __APPLE__ || defined ANDROID #ifndef GL_COMPRESSED_RGB_S3TC_DXT1_EXT #define GL_COMPRESSED_RGB_S3TC_DXT1_EXT 0 #endif #ifndef GL_COMPRESSED_RGBA_S3TC_DXT5_EXT #define GL_COMPRESSED_RGBA_S3TC_DXT5_EXT 0 #endif #ifndef GL_COMPRESSED_RED_RGTC1 #define GL_COMPRESSED_RED_RGTC1 0x8DBB #endif #ifndef GL_COMPRESSED_RG_RGTC2 #define GL_COMPRESSED_RG_RGTC2 0x8DBD #endif #endif #include <cassert> #include <iostream> using namespace std; using namespace canvas; size_t OpenGLTexture::total_textures = 0; vector<unsigned int> OpenGLTexture::freed_textures; bool OpenGLTexture::global_init = false; OpenGLTexture::OpenGLTexture(Surface & surface) : Texture(surface.getLogicalWidth(), surface.getLogicalHeight(), surface.getActualWidth(), surface.getActualHeight(), surface.getMinFilter(), surface.getMagFilter(), surface.getTargetFormat(), 1) { assert(getInternalFormat()); auto image = surface.createImage(); updateData(*image, 0, 0); } static GLenum getOpenGLInternalFormat(InternalFormat internal_format) { switch (internal_format) { case NO_FORMAT: return 0; case R8: return GL_R8; case RG8: return GL_RG8; case RGB565: return GL_RGB565; case RGBA4: return GL_RGBA4; case RGBA8: return GL_RGBA8; case RGB8: return GL_RGB8; case RGB8_24: return GL_RGBA8; case RED_RGTC1: return GL_COMPRESSED_RED_RGTC1; case RG_RGTC2: return GL_COMPRESSED_RG_RGTC2; case RGB_ETC1: return GL_COMPRESSED_RGB8_ETC2; case RGB_DXT1: return GL_COMPRESSED_RGB_S3TC_DXT1_EXT; case RGBA_DXT5: return GL_COMPRESSED_RGBA_S3TC_DXT5_EXT; case LUMINANCE_ALPHA: return GL_RG8; case LA44: return GL_R8; // pack luminance and alpha to single byte case R32F: return GL_R32F; } assert(0); return 0; } static GLenum getOpenGLFilterType(FilterMode mode) { switch (mode) { case NEAREST: return GL_NEAREST; case LINEAR: return GL_LINEAR; case LINEAR_MIPMAP_LINEAR: return GL_LINEAR_MIPMAP_LINEAR; } return 0; } void OpenGLTexture::updateCompressedData(const Image & image, unsigned int x, unsigned int y) { unsigned int offset = 0; unsigned int current_width = image.getWidth(), current_height = image.getHeight(); GLenum format = getOpenGLInternalFormat(getInternalFormat()); for (unsigned int level = 0; level < image.getLevels(); level++) { size_t size = image.calculateOffset(level + 1) - image.calculateOffset(level); // cerr << "compressed tex: x = " << x << ", y = " << y << ", l = " << (level+1) << "/" << image.getLevels() << ", w = " << current_width << ", h = " << current_height << ", offset = " << offset << ", size = " << size << endl; glCompressedTexSubImage2D(GL_TEXTURE_2D, level, x, y, current_width, current_height, format, size, image.getData() + offset); offset += size; current_width /= 2; current_height /= 2; x /= 2; y /= 2; } } void OpenGLTexture::updatePlainData(const Image & image, unsigned int x, unsigned int y) { unsigned int offset = 0; unsigned int current_width = image.getWidth(), current_height = image.getHeight(); GLenum format = getOpenGLInternalFormat(getInternalFormat()); for (unsigned int level = 0; level < image.getLevels(); level++) { size_t size = image.calculateOffset(level + 1) - image.calculateOffset(level); // cerr << "plain tex: x = " << x << ", y = " << y << ", l = " << (level+1) << "/" << image.getLevels() << ", w = " << current_width << ", h = " << current_height << ", size = " << size << ", offset = " << offset << endl; if (getInternalFormat() == RGBA8) { assert(image.getData()); #if defined __APPLE__ || defined ANDROID glTexSubImage2D(GL_TEXTURE_2D, level, x, y, current_width, current_height, GL_RGBA, GL_UNSIGNED_BYTE, image.getData() + offset); #else glTexSubImage2D(GL_TEXTURE_2D, level, x, y, current_width, current_height, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, image.getData() + offset); // glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, tmp_image.getWidth(), height, GL_BGRA_EXT, GL_UNSIGNED_BYTE, image.getData()); #endif } else if (getInternalFormat() == LA44) { glTexSubImage2D(GL_TEXTURE_2D, level, x, y, current_width, current_height, GL_RED, GL_UNSIGNED_BYTE, image.getData() + offset); } else if (getInternalFormat() == RGB565) { glTexSubImage2D(GL_TEXTURE_2D, level, x, y, current_width, current_height, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, image.getData() + offset); } else if (getInternalFormat() == R32F) { glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, current_width, current_height, GL_RED, GL_FLOAT, image.getData() + offset); } else { cerr << "unhandled format " << int(getInternalFormat()) << endl; assert(0); } // glTexSubImage2D(GL_TEXTURE_2D, level, x, y, current_width, current_height, getOpenGLInternalFormat(getInternalFormat()), size, image.getData() + offset); offset += size; current_width /= 2; current_height /= 2; x /= 2; y /= 2; } } void OpenGLTexture::updateData(const Image & image, unsigned int x, unsigned int y) { if (!global_init) { global_init = true; glPixelStorei(GL_UNPACK_ALIGNMENT, 1); } bool initialize = false; if (!texture_id) { initialize = true; glGenTextures(1, &texture_id); // cerr << "created texture id " << texture_id << " (total = " << total_textures << ")" << endl; if (texture_id >= 1) total_textures++; } assert(texture_id >= 1); glBindTexture(GL_TEXTURE_2D, texture_id); bool has_mipmaps = getMinFilter() == LINEAR_MIPMAP_LINEAR; if (initialize) { glTexStorage2D(GL_TEXTURE_2D, has_mipmaps ? getMipmapLevels() : 1, getOpenGLInternalFormat(getInternalFormat()), getActualWidth(), getActualHeight()); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, getOpenGLFilterType(getMinFilter())); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, getOpenGLFilterType(getMagFilter())); if (x != 0 || y != 0 || image.getWidth() != getActualWidth() || image.getHeight() != getActualHeight()) { int levels = has_mipmaps ? getMipmapLevels() : 1; if (getInternalFormat() == RGB_ETC1 || getInternalFormat() == RGB_DXT1 || getInternalFormat() == RED_RGTC1 ) { Image img(getInternalFormat(), getActualWidth(), getActualHeight(), levels); updateCompressedData(img, 0, 0); } else if (getInternalFormat() == RGBA8 || getInternalFormat() == LA44 || getInternalFormat() == RGB565 || getInternalFormat() == R32F) { Image img(getInternalFormat(), getActualWidth(), getActualHeight(), levels); updatePlainData(img, 0, 0); } else { assert(0); } } } if (getInternalFormat() == R32F) { glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, image.getWidth(), image.getHeight(), GL_RED, GL_FLOAT, image.getData()); } else if (getInternalFormat() == R8) { glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, image.getWidth(), image.getHeight(), GL_RED, GL_UNSIGNED_BYTE, image.getData()); } else if (getInternalFormat() == LA44) { auto tmp_image = image.convert(LA44); glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, tmp_image->getWidth(), tmp_image->getHeight(), GL_RED, GL_UNSIGNED_BYTE, tmp_image->getData()); } else if (getInternalFormat() == LUMINANCE_ALPHA) { if (image.getInternalFormat() == LUMINANCE_ALPHA) { glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, image.getWidth(), image.getHeight(), GL_RG, GL_UNSIGNED_BYTE, image.getData()); } else { auto tmp_image = image.convert(LUMINANCE_ALPHA); glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, tmp_image->getWidth(), tmp_image->getHeight(), GL_RG, GL_UNSIGNED_BYTE, tmp_image->getData()); } } else if (getInternalFormat() == RGB565) { auto tmp_image = image.convert(RGB565); updatePlainData(*tmp_image, x, y); // glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, tmp_image->getWidth(), tmp_image->getHeight(), GL_RGB, GL_UNSIGNED_SHORT_5_6_5, tmp_image->getData()); } else if (getInternalFormat() == RGBA4) { auto tmp_image = image.convert(RGBA4); glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, tmp_image->getWidth(), tmp_image->getHeight(), GL_RGBA4, GL_UNSIGNED_SHORT_4_4_4_4, tmp_image->getData()); } else if (getInternalFormat() == RGB_ETC1) { if (image.getInternalFormat() == RGB_ETC1) { updateCompressedData(image, x, y); } else { auto fd = image.getImageFormat(); cerr << "WARNING: compression should be done in thread (bpp = " << fd.getBytesPerPixel() << ", c = " << int(fd.getCompression()) << ", ch = " << fd.getNumChannels() << ")\n"; auto tmp_image = image.convert(RGB_ETC1); updateCompressedData(*tmp_image, x, y); } } else if (getInternalFormat() == RGB_DXT1) { if (image.getInternalFormat() == RGB_DXT1) { updateCompressedData(image, x, y); } else { cerr << "WARNING: compression should be done in thread\n"; auto tmp_image = image.convert(RGB_DXT1); updateCompressedData(*tmp_image, x, y); } } else if (getInternalFormat() == RED_RGTC1) { if (image.getInternalFormat() == RED_RGTC1) { updateCompressedData(image, x, y); } else { cerr << "WARNING: compression should be done in thread\n"; auto tmp_image = image.convert(RED_RGTC1); updateCompressedData(*tmp_image, x, y); } } else if (getInternalFormat() == RG_RGTC2) { if (image.getInternalFormat() == RG_RGTC2) { updateCompressedData(image, x, y); } else { cerr << "WARNING: compression should be done in thread\n"; auto tmp_image = image.convert(RG_RGTC2); updateCompressedData(*tmp_image, x, y); } } else { updatePlainData(image, x, y); } if (has_mipmaps && image.getLevels() == 1) { need_mipmaps = true; } glBindTexture(GL_TEXTURE_2D, 0); } void OpenGLTexture::generateMipmaps() { if (need_mipmaps) { if (getInternalFormat() != RGB_DXT1 && getInternalFormat() != RGB_ETC1 && getInternalFormat() != LA44 && getInternalFormat() != RED_RGTC1 && getInternalFormat() != RG_RGTC2) { glGenerateMipmap(GL_TEXTURE_2D); } else { cerr << "unable to generate mipmaps for compressed texture!\n"; } need_mipmaps = false; } } void OpenGLTexture::releaseTextures() { if (!freed_textures.empty()) { // cerr << "DELETING TEXTURES: " << OpenGLTexture::getFreedTextures().size() << "/" << OpenGLTexture::getNumTextures() << endl; for (vector<unsigned int>::const_iterator it = freed_textures.begin(); it != freed_textures.end(); it++) { GLuint texid = *it; glDeleteTextures(1, &texid); } freed_textures.clear(); } } TextureRef OpenGLTexture::createTexture(unsigned int _logical_width, unsigned int _logical_height, unsigned int _actual_width, unsigned int _actual_height, FilterMode min_filter, FilterMode mag_filter, InternalFormat _internal_format, unsigned int mipmap_levels) { assert(_internal_format); return TextureRef(_logical_width, _logical_height, _actual_width, _actual_height, new OpenGLTexture(_logical_width, _logical_height, _actual_width, _actual_height, min_filter, mag_filter, _internal_format, mipmap_levels)); } TextureRef OpenGLTexture::createTexture(Surface & surface) { return TextureRef( surface.getLogicalWidth(), surface.getLogicalHeight(), surface.getActualWidth(), surface.getActualHeight(), new OpenGLTexture(surface) ); } <commit_msg>cast size to hide warning<commit_after>#include <OpenGLTexture.h> #include <TextureRef.h> #include <Image.h> #include <Surface.h> #define GL_GLEXT_PROTOTYPES #if defined __APPLE__ #include <OpenGLES/ES3/gl.h> #include <OpenGLES/ES3/glext.h> #elif (defined GL_ES) #include <GLES3/gl3.h> #include <EGL/egl.h> #include <EGL/eglext.h> #else #define GL_GLEXT_PROTOTYPES #ifdef _WIN32 #include <GL/glew.h> #include <windows.h> #endif #ifdef ANDROID #include <GLES3/gl3.h> #include <GLES3/gl3ext.h> #else #include <GL/gl.h> #ifdef _WIN32 #include "glext.h" #else #include <GL/glext.h> #endif #endif #endif #if defined __APPLE__ || defined ANDROID #ifndef GL_COMPRESSED_RGB_S3TC_DXT1_EXT #define GL_COMPRESSED_RGB_S3TC_DXT1_EXT 0 #endif #ifndef GL_COMPRESSED_RGBA_S3TC_DXT5_EXT #define GL_COMPRESSED_RGBA_S3TC_DXT5_EXT 0 #endif #ifndef GL_COMPRESSED_RED_RGTC1 #define GL_COMPRESSED_RED_RGTC1 0x8DBB #endif #ifndef GL_COMPRESSED_RG_RGTC2 #define GL_COMPRESSED_RG_RGTC2 0x8DBD #endif #endif #include <cassert> #include <iostream> using namespace std; using namespace canvas; size_t OpenGLTexture::total_textures = 0; vector<unsigned int> OpenGLTexture::freed_textures; bool OpenGLTexture::global_init = false; OpenGLTexture::OpenGLTexture(Surface & surface) : Texture(surface.getLogicalWidth(), surface.getLogicalHeight(), surface.getActualWidth(), surface.getActualHeight(), surface.getMinFilter(), surface.getMagFilter(), surface.getTargetFormat(), 1) { assert(getInternalFormat()); auto image = surface.createImage(); updateData(*image, 0, 0); } static GLenum getOpenGLInternalFormat(InternalFormat internal_format) { switch (internal_format) { case NO_FORMAT: return 0; case R8: return GL_R8; case RG8: return GL_RG8; case RGB565: return GL_RGB565; case RGBA4: return GL_RGBA4; case RGBA8: return GL_RGBA8; case RGB8: return GL_RGB8; case RGB8_24: return GL_RGBA8; case RED_RGTC1: return GL_COMPRESSED_RED_RGTC1; case RG_RGTC2: return GL_COMPRESSED_RG_RGTC2; case RGB_ETC1: return GL_COMPRESSED_RGB8_ETC2; case RGB_DXT1: return GL_COMPRESSED_RGB_S3TC_DXT1_EXT; case RGBA_DXT5: return GL_COMPRESSED_RGBA_S3TC_DXT5_EXT; case LUMINANCE_ALPHA: return GL_RG8; case LA44: return GL_R8; // pack luminance and alpha to single byte case R32F: return GL_R32F; } assert(0); return 0; } static GLenum getOpenGLFilterType(FilterMode mode) { switch (mode) { case NEAREST: return GL_NEAREST; case LINEAR: return GL_LINEAR; case LINEAR_MIPMAP_LINEAR: return GL_LINEAR_MIPMAP_LINEAR; } return 0; } void OpenGLTexture::updateCompressedData(const Image & image, unsigned int x, unsigned int y) { unsigned int offset = 0; unsigned int current_width = image.getWidth(), current_height = image.getHeight(); GLenum format = getOpenGLInternalFormat(getInternalFormat()); for (unsigned int level = 0; level < image.getLevels(); level++) { size_t size = image.calculateOffset(level + 1) - image.calculateOffset(level); // cerr << "compressed tex: x = " << x << ", y = " << y << ", l = " << (level+1) << "/" << image.getLevels() << ", w = " << current_width << ", h = " << current_height << ", offset = " << offset << ", size = " << size << endl; glCompressedTexSubImage2D(GL_TEXTURE_2D, level, x, y, current_width, current_height, format, (GLsizei)size, image.getData() + offset); offset += size; current_width /= 2; current_height /= 2; x /= 2; y /= 2; } } void OpenGLTexture::updatePlainData(const Image & image, unsigned int x, unsigned int y) { unsigned int offset = 0; unsigned int current_width = image.getWidth(), current_height = image.getHeight(); GLenum format = getOpenGLInternalFormat(getInternalFormat()); for (unsigned int level = 0; level < image.getLevels(); level++) { size_t size = image.calculateOffset(level + 1) - image.calculateOffset(level); // cerr << "plain tex: x = " << x << ", y = " << y << ", l = " << (level+1) << "/" << image.getLevels() << ", w = " << current_width << ", h = " << current_height << ", size = " << size << ", offset = " << offset << endl; if (getInternalFormat() == RGBA8) { assert(image.getData()); #if defined __APPLE__ || defined ANDROID glTexSubImage2D(GL_TEXTURE_2D, level, x, y, current_width, current_height, GL_RGBA, GL_UNSIGNED_BYTE, image.getData() + offset); #else glTexSubImage2D(GL_TEXTURE_2D, level, x, y, current_width, current_height, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, image.getData() + offset); // glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, tmp_image.getWidth(), height, GL_BGRA_EXT, GL_UNSIGNED_BYTE, image.getData()); #endif } else if (getInternalFormat() == LA44) { glTexSubImage2D(GL_TEXTURE_2D, level, x, y, current_width, current_height, GL_RED, GL_UNSIGNED_BYTE, image.getData() + offset); } else if (getInternalFormat() == RGB565) { glTexSubImage2D(GL_TEXTURE_2D, level, x, y, current_width, current_height, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, image.getData() + offset); } else if (getInternalFormat() == R32F) { glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, current_width, current_height, GL_RED, GL_FLOAT, image.getData() + offset); } else { cerr << "unhandled format " << int(getInternalFormat()) << endl; assert(0); } // glTexSubImage2D(GL_TEXTURE_2D, level, x, y, current_width, current_height, getOpenGLInternalFormat(getInternalFormat()), size, image.getData() + offset); offset += size; current_width /= 2; current_height /= 2; x /= 2; y /= 2; } } void OpenGLTexture::updateData(const Image & image, unsigned int x, unsigned int y) { if (!global_init) { global_init = true; glPixelStorei(GL_UNPACK_ALIGNMENT, 1); } bool initialize = false; if (!texture_id) { initialize = true; glGenTextures(1, &texture_id); // cerr << "created texture id " << texture_id << " (total = " << total_textures << ")" << endl; if (texture_id >= 1) total_textures++; } assert(texture_id >= 1); glBindTexture(GL_TEXTURE_2D, texture_id); bool has_mipmaps = getMinFilter() == LINEAR_MIPMAP_LINEAR; if (initialize) { glTexStorage2D(GL_TEXTURE_2D, has_mipmaps ? getMipmapLevels() : 1, getOpenGLInternalFormat(getInternalFormat()), getActualWidth(), getActualHeight()); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, getOpenGLFilterType(getMinFilter())); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, getOpenGLFilterType(getMagFilter())); if (x != 0 || y != 0 || image.getWidth() != getActualWidth() || image.getHeight() != getActualHeight()) { int levels = has_mipmaps ? getMipmapLevels() : 1; if (getInternalFormat() == RGB_ETC1 || getInternalFormat() == RGB_DXT1 || getInternalFormat() == RED_RGTC1 ) { Image img(getInternalFormat(), getActualWidth(), getActualHeight(), levels); updateCompressedData(img, 0, 0); } else if (getInternalFormat() == RGBA8 || getInternalFormat() == LA44 || getInternalFormat() == RGB565 || getInternalFormat() == R32F) { Image img(getInternalFormat(), getActualWidth(), getActualHeight(), levels); updatePlainData(img, 0, 0); } else { assert(0); } } } if (getInternalFormat() == R32F) { glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, image.getWidth(), image.getHeight(), GL_RED, GL_FLOAT, image.getData()); } else if (getInternalFormat() == R8) { glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, image.getWidth(), image.getHeight(), GL_RED, GL_UNSIGNED_BYTE, image.getData()); } else if (getInternalFormat() == LA44) { auto tmp_image = image.convert(LA44); glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, tmp_image->getWidth(), tmp_image->getHeight(), GL_RED, GL_UNSIGNED_BYTE, tmp_image->getData()); } else if (getInternalFormat() == LUMINANCE_ALPHA) { if (image.getInternalFormat() == LUMINANCE_ALPHA) { glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, image.getWidth(), image.getHeight(), GL_RG, GL_UNSIGNED_BYTE, image.getData()); } else { auto tmp_image = image.convert(LUMINANCE_ALPHA); glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, tmp_image->getWidth(), tmp_image->getHeight(), GL_RG, GL_UNSIGNED_BYTE, tmp_image->getData()); } } else if (getInternalFormat() == RGB565) { auto tmp_image = image.convert(RGB565); updatePlainData(*tmp_image, x, y); // glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, tmp_image->getWidth(), tmp_image->getHeight(), GL_RGB, GL_UNSIGNED_SHORT_5_6_5, tmp_image->getData()); } else if (getInternalFormat() == RGBA4) { auto tmp_image = image.convert(RGBA4); glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, tmp_image->getWidth(), tmp_image->getHeight(), GL_RGBA4, GL_UNSIGNED_SHORT_4_4_4_4, tmp_image->getData()); } else if (getInternalFormat() == RGB_ETC1) { if (image.getInternalFormat() == RGB_ETC1) { updateCompressedData(image, x, y); } else { auto fd = image.getImageFormat(); cerr << "WARNING: compression should be done in thread (bpp = " << fd.getBytesPerPixel() << ", c = " << int(fd.getCompression()) << ", ch = " << fd.getNumChannels() << ")\n"; auto tmp_image = image.convert(RGB_ETC1); updateCompressedData(*tmp_image, x, y); } } else if (getInternalFormat() == RGB_DXT1) { if (image.getInternalFormat() == RGB_DXT1) { updateCompressedData(image, x, y); } else { cerr << "WARNING: compression should be done in thread\n"; auto tmp_image = image.convert(RGB_DXT1); updateCompressedData(*tmp_image, x, y); } } else if (getInternalFormat() == RED_RGTC1) { if (image.getInternalFormat() == RED_RGTC1) { updateCompressedData(image, x, y); } else { cerr << "WARNING: compression should be done in thread\n"; auto tmp_image = image.convert(RED_RGTC1); updateCompressedData(*tmp_image, x, y); } } else if (getInternalFormat() == RG_RGTC2) { if (image.getInternalFormat() == RG_RGTC2) { updateCompressedData(image, x, y); } else { cerr << "WARNING: compression should be done in thread\n"; auto tmp_image = image.convert(RG_RGTC2); updateCompressedData(*tmp_image, x, y); } } else { updatePlainData(image, x, y); } if (has_mipmaps && image.getLevels() == 1) { need_mipmaps = true; } glBindTexture(GL_TEXTURE_2D, 0); } void OpenGLTexture::generateMipmaps() { if (need_mipmaps) { if (getInternalFormat() != RGB_DXT1 && getInternalFormat() != RGB_ETC1 && getInternalFormat() != LA44 && getInternalFormat() != RED_RGTC1 && getInternalFormat() != RG_RGTC2) { glGenerateMipmap(GL_TEXTURE_2D); } else { cerr << "unable to generate mipmaps for compressed texture!\n"; } need_mipmaps = false; } } void OpenGLTexture::releaseTextures() { if (!freed_textures.empty()) { // cerr << "DELETING TEXTURES: " << OpenGLTexture::getFreedTextures().size() << "/" << OpenGLTexture::getNumTextures() << endl; for (vector<unsigned int>::const_iterator it = freed_textures.begin(); it != freed_textures.end(); it++) { GLuint texid = *it; glDeleteTextures(1, &texid); } freed_textures.clear(); } } TextureRef OpenGLTexture::createTexture(unsigned int _logical_width, unsigned int _logical_height, unsigned int _actual_width, unsigned int _actual_height, FilterMode min_filter, FilterMode mag_filter, InternalFormat _internal_format, unsigned int mipmap_levels) { assert(_internal_format); return TextureRef(_logical_width, _logical_height, _actual_width, _actual_height, new OpenGLTexture(_logical_width, _logical_height, _actual_width, _actual_height, min_filter, mag_filter, _internal_format, mipmap_levels)); } TextureRef OpenGLTexture::createTexture(Surface & surface) { return TextureRef( surface.getLogicalWidth(), surface.getLogicalHeight(), surface.getActualWidth(), surface.getActualHeight(), new OpenGLTexture(surface) ); } <|endoftext|>
<commit_before>1d58a59a-2e4e-11e5-9284-b827eb9e62be<commit_msg>1d5dad1a-2e4e-11e5-9284-b827eb9e62be<commit_after>1d5dad1a-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>/* $Id: GammaSrc.C,v 1.7 2001-12-06 23:19:58 wilsonp Exp $ */ #include "GammaSrc.h" #include "DataLib/DataLib.h" #include "Input/Mixture.h" /*************************** ********* Service ********* **************************/ GammaSrc::GammaSrc(istream& input, int inGammaType) { char libType[9]; gammaType = inGammaType; strcpy(libType,"gammalib"); nGroups = 0; contactDose = 0; grpBnds = NULL; dataLib = NULL; gammaAttenCoef = NULL; /* get gamma library filename */ dataLib = DataLib::newLib(libType,input); switch(gammaType) { case GAMMASRC_RAW_SRC: initRawSrc(input); break; case GAMMASRC_CONTACT: initContactDose(input); break; case GAMMASRC_ADJOINT: error (6000,"Adjoint Dose it not yet supported!"); break; } } void GammaSrc::initRawSrc(istream& input) { char token[64]; int gNum; /* get gamma source output filename */ clearComment(input); input >> token; fileName = new char[strlen(token)+1]; strcpy(fileName,token); gSrcFile.open(fileName); if (!gSrcFile) error(250,"Unable to open file for gamma source output: %s\n", fileName); /* get number of gamma groups to use */ clearComment(input); input >> nGroups; /* error checking */ grpBnds = new double[nGroups+1]; /* memcheck */ grpBnds[0] = 0; /* read gamma group bounds */ clearComment(input); for (gNum=1;gNum<nGroups+1;gNum++) input >> grpBnds[gNum]; } void GammaSrc::initContactDose(istream& input) { char token[64]; int gNum; /* get gamma attenuation data file */ clearComment(input); input >> token; fileName = new char[strlen(token)+1]; strcpy(fileName,token); gAttenData.open(fileName); if (!gAttenData) error(250, "Unable to open file for gamma attenuation data input (contact dose): %s\n", fileName); /* get number of data points used for this data */ clearComment(gAttenData); gAttenData >> nGroups; grpBnds = new double[nGroups+1]; grpBnds[0] = 0.0; /* read gamma energy points */ for (gNum=1;gNum<nGroups+1;gNum++) { gAttenData >> grpBnds[gNum]; grpBnds[gNum] *= 1.0E6; } } GammaSrc::~GammaSrc() { /* empty VectorCache */ /* foreach entry in cache... */ /* delete vector pointed to by entry */ delete dataLib; delete grpBnds; } void GammaSrc::setGammaAttenCoef(Mixture* mixList) { mixList->setGammaAttenCoef(nGroups,gAttenData); } /* routine to determine which energy group a particular gamma ray is in */ int GammaSrc::findGroup(float E) { int gNum, gMin = 0, gMax = nGroups-1; if (E < grpBnds[gMin]) { /* ERROR - energy < 0 */ } if (E > grpBnds[gMax]) return gMax; while (1) { gNum = (gMin+gMax)/2; if (E < grpBnds[gNum]) gMax = gNum; else if (E > grpBnds[gNum+1]) gMin = gNum+1; else return gNum; } } double GammaSrc::subIntegral(int pntNum, int intTyp, float* x, float* y, double xlo, double xhi) { double m,I=0; double x1 = x[pntNum]; double x2 = x[pntNum+1]; double y1 = y[pntNum]; double y2 = y[pntNum+1]; /* based on interpolation type */ switch (intTyp) { case 1: /* type 1: histogram */ /* y = y1 */ /* I = y1*x @ dx */ I = (xhi-xlo)*y1; break; case 2: /* type 2: linear */ /* y = m*x + (y1-m*x1) */ /* I = 0.5*m*x^2 + (y1-m*x1)*x @ dx */ /* find m */ m =(y2-y1)/(x2-x1); /* area of trapezoid */ I = (xhi-xlo)*(0.5*(xhi + xlo)*m + y1); break; case 3: /* type 3: linear-log */ /* y = m*ln(x) + y1 -m*ln(x1) */ /* I = m*(x*ln(x)-x) + (y1 - m*ln(x1))*x @ dx */ m = (y2-y1)/(log(x2)-log(x1)); I = m*( (xhi*log(xhi)-xhi) - (xlo*log(xlo)-xlo) ) + ( y1-m*log(x1) ) * (xhi-xlo); break; case 4: /* type 4: log-linesr */ /* y = y1*exp( m*(x-x1)) */ /* I = y1*exp( m*(x-x1))/m @ dx*/ m = (log(y2)-log(y1))/(x2-x1); I = expm1( m*(xhi-x1) ) - expm1( m*(xlo-x1) ); I *= y1/m; break; case 5:/* type 5: log-log */ /* y = y1 * (x/x1)^m */ /* I = y1 * (x/x1)^m*x/(m+1) @ dx for m != -1 */ /* = y1 * x1*ln(x) @ dx for m == -1 */ m = ( log(y2) - log(y1) )/( log(x2) - log(x1) ); if (m != -1) I = y1*( pow(xhi/x1,m)*xhi - pow(xlo/x1,m)*xlo )/(m+1); else I = y1*x1*log(xhi/xlo); break; default: I = 0; } return I; } void GammaSrc::setData(int kza, int numSpec, int *numDisc, int *numIntReg, int *nPts, int **intRegB, int **intRegT, float **discGammaE, float **discGammaI, float **contX, float **contY) { int specNum, gammaNum, gNum, pntNum, regNum; double *gammaMult = NULL; double Elo, Ehi, interpFrac; if (numSpec > 0) { gammaMult = new double[nGroups]; for (gNum=0;gNum<nGroups;gNum++) gammaMult[gNum] = 0.0; contactDose = 0.0; for (specNum=0;specNum<numSpec;specNum++) { /* foreach discrete gamma */ for (gammaNum=0;gammaNum<numDisc[specNum];gammaNum++) { /* determine energy bin */ gNum = findGroup(discGammaE[specNum][gammaNum]); switch (gammaType) { case GAMMASRC_RAW_SRC: /* increment bin */ gammaMult[gNum] += discGammaI[specNum][gammaNum]; break; case GAMMASRC_CONTACT: /* increment total contact dose */ /* if this is the "last group" we are extrapolating */ if (gNum == nGroups-1) gNum = nGroups-2; interpFrac = (discGammaE[specNum][gammaNum] - grpBnds[gNum])/ (grpBnds[gNum+1] - grpBnds[gNum]); contactDose += discGammaI[specNum][gammaNum] * discGammaE[specNum][gammaNum] * (gammaAttenCoef[gNum]*(1.0 - interpFrac) + gammaAttenCoef[gNum+1] * interpFrac); break; } } /* CONTINUOUS ENERGY SPECTRUM */ regNum = 0; pntNum = 0; gNum = 0; while (numIntReg[specNum] > regNum && nPts[specNum] > pntNum) { Elo = max(double(contX[specNum][pntNum]),grpBnds[gNum]); Ehi = min(double(contX[specNum][pntNum+1]),grpBnds[gNum+1]); switch (gammaType) { case GAMMASRC_RAW_SRC: gammaMult[gNum] += subIntegral(pntNum,intRegT[specNum][regNum], contX[specNum],contY[specNum], Elo,Ehi); break; case GAMMASRC_CONTACT: case GAMMASRC_ADJOINT: /* ignore continuous spectrum for now */ break; } if (Ehi == grpBnds[gNum+1]) gNum++; else { pntNum++; if (pntNum > intRegB[specNum][regNum]) regNum++; } } } gammaMultCache[kza] = gammaMult; } } double* GammaSrc::getGammaMult(int kza) { if (!gammaMultCache.count(kza)) { gammaMultCache[kza] = NULL; dataLib->readGammaData(kza,this); } return gammaMultCache[kza]; } void GammaSrc::writeTotal(double *photonSrc,int nResults) { int gNum, resNum; gSrcFile << "TOTAL" << endl; for (resNum=0;resNum<nResults;resNum++) { for (gNum=0;gNum<nGroups;gNum++) { gSrcFile << photonSrc[resNum*nGroups+gNum]; if (gNum%6 == 5) gSrcFile << endl; else gSrcFile << "\t"; } gSrcFile << endl; } } void GammaSrc::writeIsotope(double *photonSrc, double N) { int gNum; if (photonSrc == NULL) return; gSrcFile << "\t"; for (gNum=0;gNum<nGroups;gNum++) { gSrcFile << photonSrc[gNum]*N; if (gNum%6 == 5) gSrcFile << endl; gSrcFile << "\t"; } gSrcFile << endl; } double GammaSrc::calcDoseConv(int kza, double *mixGammaAttenCoef) { /* reset contact dose in case there is no gamma data for this isotope */ contactDose = 0; gammaAttenCoef = mixGammaAttenCoef; dataLib->readGammaData(kza,this); gammaAttenCoef = NULL; return contactDose; }; <commit_msg>Fixed bug in interpretation of groups/group boundaries for contact dose.<commit_after>/* $Id: GammaSrc.C,v 1.8 2002-01-07 21:53:07 wilsonp Exp $ */ #include "GammaSrc.h" #include "DataLib/DataLib.h" #include "Input/Mixture.h" /*************************** ********* Service ********* **************************/ GammaSrc::GammaSrc(istream& input, int inGammaType) { char libType[9]; gammaType = inGammaType; strcpy(libType,"gammalib"); nGroups = 0; contactDose = 0; grpBnds = NULL; dataLib = NULL; gammaAttenCoef = NULL; /* get gamma library filename */ dataLib = DataLib::newLib(libType,input); switch(gammaType) { case GAMMASRC_RAW_SRC: initRawSrc(input); break; case GAMMASRC_CONTACT: initContactDose(input); break; case GAMMASRC_ADJOINT: error (6000,"Adjoint Dose it not yet supported!"); break; } } void GammaSrc::initRawSrc(istream& input) { char token[64]; int gNum; /* get gamma source output filename */ clearComment(input); input >> token; fileName = new char[strlen(token)+1]; strcpy(fileName,token); gSrcFile.open(fileName); if (!gSrcFile) error(250,"Unable to open file for gamma source output: %s\n", fileName); /* get number of gamma groups to use */ clearComment(input); input >> nGroups; /* error checking */ grpBnds = new double[nGroups+1]; /* memcheck */ grpBnds[0] = 0; /* read gamma group bounds */ clearComment(input); for (gNum=1;gNum<nGroups+1;gNum++) input >> grpBnds[gNum]; } void GammaSrc::initContactDose(istream& input) { char token[64]; int gNum; /* get gamma attenuation data file */ clearComment(input); input >> token; fileName = new char[strlen(token)+1]; strcpy(fileName,token); gAttenData.open(fileName); if (!gAttenData) error(250, "Unable to open file for gamma attenuation data input (contact dose): %s\n", fileName); /* get number of data points used for this data */ clearComment(gAttenData); gAttenData >> nGroups; grpBnds = new double[nGroups+1]; grpBnds[0] = 0.0; /* read gamma energy points */ for (gNum=1;gNum<nGroups+1;gNum++) { gAttenData >> grpBnds[gNum]; grpBnds[gNum] *= 1.0E6; } } GammaSrc::~GammaSrc() { /* empty VectorCache */ /* foreach entry in cache... */ /* delete vector pointed to by entry */ delete dataLib; delete grpBnds; } void GammaSrc::setGammaAttenCoef(Mixture* mixList) { mixList->setGammaAttenCoef(nGroups,gAttenData); } /* routine to determine which energy group a particular gamma ray is in */ int GammaSrc::findGroup(float E) { int gNum, gMin = 0, gMax = nGroups-1; if (E < grpBnds[gMin]) { /* ERROR - energy < 0 */ } if (E > grpBnds[gMax]) return gMax; while (1) { gNum = (gMin+gMax)/2; if (E < grpBnds[gNum]) gMax = gNum; else if (E > grpBnds[gNum+1]) gMin = gNum+1; else return gNum; } } double GammaSrc::subIntegral(int pntNum, int intTyp, float* x, float* y, double xlo, double xhi) { double m,I=0; double x1 = x[pntNum]; double x2 = x[pntNum+1]; double y1 = y[pntNum]; double y2 = y[pntNum+1]; /* based on interpolation type */ switch (intTyp) { case 1: /* type 1: histogram */ /* y = y1 */ /* I = y1*x @ dx */ I = (xhi-xlo)*y1; break; case 2: /* type 2: linear */ /* y = m*x + (y1-m*x1) */ /* I = 0.5*m*x^2 + (y1-m*x1)*x @ dx */ /* find m */ m =(y2-y1)/(x2-x1); /* area of trapezoid */ I = (xhi-xlo)*(0.5*(xhi + xlo)*m + y1); break; case 3: /* type 3: linear-log */ /* y = m*ln(x) + y1 -m*ln(x1) */ /* I = m*(x*ln(x)-x) + (y1 - m*ln(x1))*x @ dx */ m = (y2-y1)/(log(x2)-log(x1)); I = m*( (xhi*log(xhi)-xhi) - (xlo*log(xlo)-xlo) ) + ( y1-m*log(x1) ) * (xhi-xlo); break; case 4: /* type 4: log-linesr */ /* y = y1*exp( m*(x-x1)) */ /* I = y1*exp( m*(x-x1))/m @ dx*/ m = (log(y2)-log(y1))/(x2-x1); I = expm1( m*(xhi-x1) ) - expm1( m*(xlo-x1) ); I *= y1/m; break; case 5:/* type 5: log-log */ /* y = y1 * (x/x1)^m */ /* I = y1 * (x/x1)^m*x/(m+1) @ dx for m != -1 */ /* = y1 * x1*ln(x) @ dx for m == -1 */ m = ( log(y2) - log(y1) )/( log(x2) - log(x1) ); if (m != -1) I = y1*( pow(xhi/x1,m)*xhi - pow(xlo/x1,m)*xlo )/(m+1); else I = y1*x1*log(xhi/xlo); break; default: I = 0; } return I; } void GammaSrc::setData(int kza, int numSpec, int *numDisc, int *numIntReg, int *nPts, int **intRegB, int **intRegT, float **discGammaE, float **discGammaI, float **contX, float **contY) { int specNum, gammaNum, gNum, pntNum, regNum; double *gammaMult = NULL; double Elo, Ehi, interpFrac; if (numSpec > 0) { gammaMult = new double[nGroups]; for (gNum=0;gNum<nGroups;gNum++) gammaMult[gNum] = 0.0; contactDose = 0.0; for (specNum=0;specNum<numSpec;specNum++) { /* foreach discrete gamma */ for (gammaNum=0;gammaNum<numDisc[specNum];gammaNum++) { /* determine energy bin */ gNum = findGroup(discGammaE[specNum][gammaNum]); switch (gammaType) { case GAMMASRC_RAW_SRC: /* increment bin */ gammaMult[gNum] += discGammaI[specNum][gammaNum]; break; case GAMMASRC_CONTACT: /* increment total contact dose */ /* if this is the first group, we are extrapolating */ if (gNum == 0) gNum++; /* if this is the "last group" we may be extrapolating */ interpFrac = (discGammaE[specNum][gammaNum] - grpBnds[gNum])/ (grpBnds[gNum+1] - grpBnds[gNum]); /* Note: FISPACT Contact dose formula calls for gamma source in units of MeV/kg.s */ /* Note: gammaAttenCoef is really point data for the upper bound of a given group */ contactDose += discGammaI[specNum][gammaNum] * discGammaE[specNum][gammaNum]*1e-6 * (gammaAttenCoef[gNum-1]*(1.0 - interpFrac) + gammaAttenCoef[gNum] * interpFrac); break; } } /* CONTINUOUS ENERGY SPECTRUM */ regNum = 0; pntNum = 0; gNum = 0; while (numIntReg[specNum] > regNum && nPts[specNum] > pntNum) { Elo = max(double(contX[specNum][pntNum]),grpBnds[gNum]); Ehi = min(double(contX[specNum][pntNum+1]),grpBnds[gNum+1]); switch (gammaType) { case GAMMASRC_RAW_SRC: gammaMult[gNum] += subIntegral(pntNum,intRegT[specNum][regNum], contX[specNum],contY[specNum], Elo,Ehi); break; case GAMMASRC_CONTACT: case GAMMASRC_ADJOINT: /* ignore continuous spectrum for now */ break; } if (Ehi == grpBnds[gNum+1]) gNum++; else { pntNum++; if (pntNum > intRegB[specNum][regNum]) regNum++; } } } gammaMultCache[kza] = gammaMult; } } double* GammaSrc::getGammaMult(int kza) { if (!gammaMultCache.count(kza)) { gammaMultCache[kza] = NULL; dataLib->readGammaData(kza,this); } return gammaMultCache[kza]; } void GammaSrc::writeTotal(double *photonSrc,int nResults) { int gNum, resNum; gSrcFile << "TOTAL" << endl; for (resNum=0;resNum<nResults;resNum++) { for (gNum=0;gNum<nGroups;gNum++) { gSrcFile << photonSrc[resNum*nGroups+gNum]; if (gNum%6 == 5) gSrcFile << endl; else gSrcFile << "\t"; } gSrcFile << endl; } } void GammaSrc::writeIsotope(double *photonSrc, double N) { int gNum; if (photonSrc == NULL) return; gSrcFile << "\t"; for (gNum=0;gNum<nGroups;gNum++) { gSrcFile << photonSrc[gNum]*N; if (gNum%6 == 5) gSrcFile << endl; gSrcFile << "\t"; } gSrcFile << endl; } double GammaSrc::calcDoseConv(int kza, double *mixGammaAttenCoef) { /* reset contact dose in case there is no gamma data for this isotope */ contactDose = 0; gammaAttenCoef = mixGammaAttenCoef; dataLib->readGammaData(kza,this); gammaAttenCoef = NULL; return contactDose; }; <|endoftext|>
<commit_before>fd40b2ce-2e4e-11e5-9284-b827eb9e62be<commit_msg>fd45a77a-2e4e-11e5-9284-b827eb9e62be<commit_after>fd45a77a-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>03a89fd8-2e4e-11e5-9284-b827eb9e62be<commit_msg>03ad9880-2e4e-11e5-9284-b827eb9e62be<commit_after>03ad9880-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>b0d4b1a8-2e4c-11e5-9284-b827eb9e62be<commit_msg>b0d9a672-2e4c-11e5-9284-b827eb9e62be<commit_after>b0d9a672-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>0ea4d068-2e4f-11e5-9284-b827eb9e62be<commit_msg>0ea9dc34-2e4f-11e5-9284-b827eb9e62be<commit_after>0ea9dc34-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>b1e24806-2e4e-11e5-9284-b827eb9e62be<commit_msg>b1e7907c-2e4e-11e5-9284-b827eb9e62be<commit_after>b1e7907c-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>eae588f8-2e4d-11e5-9284-b827eb9e62be<commit_msg>eaea7f20-2e4d-11e5-9284-b827eb9e62be<commit_after>eaea7f20-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>7145da20-2e4d-11e5-9284-b827eb9e62be<commit_msg>714af7f8-2e4d-11e5-9284-b827eb9e62be<commit_after>714af7f8-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>5e4aff6c-2e4e-11e5-9284-b827eb9e62be<commit_msg>5e4ff648-2e4e-11e5-9284-b827eb9e62be<commit_after>5e4ff648-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>c2d0cd5e-2e4e-11e5-9284-b827eb9e62be<commit_msg>c2d5bd96-2e4e-11e5-9284-b827eb9e62be<commit_after>c2d5bd96-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>eacff578-2e4e-11e5-9284-b827eb9e62be<commit_msg>ead54672-2e4e-11e5-9284-b827eb9e62be<commit_after>ead54672-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>f4a5908a-2e4e-11e5-9284-b827eb9e62be<commit_msg>f4aa89a0-2e4e-11e5-9284-b827eb9e62be<commit_after>f4aa89a0-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>3a5c6786-2e4d-11e5-9284-b827eb9e62be<commit_msg>3a616ccc-2e4d-11e5-9284-b827eb9e62be<commit_after>3a616ccc-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>26d2475c-2e4e-11e5-9284-b827eb9e62be<commit_msg>26d75742-2e4e-11e5-9284-b827eb9e62be<commit_after>26d75742-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>34987036-2e4f-11e5-9284-b827eb9e62be<commit_msg>349d694c-2e4f-11e5-9284-b827eb9e62be<commit_after>349d694c-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>aaac2fae-2e4c-11e5-9284-b827eb9e62be<commit_msg>aab11b4a-2e4c-11e5-9284-b827eb9e62be<commit_after>aab11b4a-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>ffcd3364-2e4e-11e5-9284-b827eb9e62be<commit_msg>ffd22cc0-2e4e-11e5-9284-b827eb9e62be<commit_after>ffd22cc0-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>f94284c4-2e4c-11e5-9284-b827eb9e62be<commit_msg>f9477ae2-2e4c-11e5-9284-b827eb9e62be<commit_after>f9477ae2-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>4b77e968-2e4e-11e5-9284-b827eb9e62be<commit_msg>4b7d043e-2e4e-11e5-9284-b827eb9e62be<commit_after>4b7d043e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>#include "res_settings.h" #include "dlg_controls.h" #include "registry.h" namespace App { using namespace Intl; bool SetControls::PerformOnInitPage() { Caption(SIDSettingsControls); ControlText(IDC_GROUP_CLICK, SIDSettingsControlsClick); ControlText(IDC_TEXT_CTRL_LMOUSECLICK, SIDSettingsControlsLeftMouse); ControlText(IDC_TEXT_CTRL_MMOUSECLICK, SIDSettingsControlsMiddleMouse); ControlText(IDC_TEXT_CTRL_RMOUSECLICK, SIDSettingsControlsRightMouse); ControlText(IDC_TEXT_CTRL_XMOUSE1CLICK, SIDSettingsControlsExtra1Mouse); ControlText(IDC_TEXT_CTRL_XMOUSE2CLICK, SIDSettingsControlsExtra2Mouse); ControlText(IDC_GROUP_DOUBLECLICK, SIDSettingsControlsDoubleClick); ControlText(IDC_TEXT_CTRL_LMOUSEDOUBLECLICK, SIDSettingsControlsLeftMouse); ControlText(IDC_TEXT_CTRL_MMOUSEDOUBLECLICK, SIDSettingsControlsMiddleMouse); ControlText(IDC_TEXT_CTRL_RMOUSEDOUBLECLICK, SIDSettingsControlsRightMouse); ControlText(IDC_TEXT_CTRL_XMOUSE1DOUBLECLICK, SIDSettingsControlsExtra1Mouse); ControlText(IDC_TEXT_CTRL_XMOUSE2DOUBLECLICK, SIDSettingsControlsExtra2Mouse); ControlText(IDC_GROUP_MWHEEL, SIDSettingsControlsScrollWheel); ControlText(IDC_TEXT_CTRL_MWHEELUP, SIDSettingsControlsWheelUp); ControlText(IDC_TEXT_CTRL_MWHEELDOWN, SIDSettingsControlsWheelDown); m_cbLeftMouse = CreateComboBox(IDC_COMBO_CTRL_LMOUSE); m_cbMiddleMouse = CreateComboBox(IDC_COMBO_CTRL_MMOUSE); m_cbRightMouse = CreateComboBox(IDC_COMBO_CTRL_RMOUSE); m_cbExtra1Mouse = CreateComboBox(IDC_COMBO_CTRL_XMOUSE1); m_cbExtra2Mouse = CreateComboBox(IDC_COMBO_CTRL_XMOUSE2); m_cbLeftMouseDoubleClick = CreateComboBox(IDC_COMBO_CTRL_LMOUSEDBL); m_cbMiddleMouseDoubleClick = CreateComboBox(IDC_COMBO_CTRL_MMOUSEDBL); m_cbRightMouseDoubleClick = CreateComboBox(IDC_COMBO_CTRL_RMOUSEDBL); m_cbExtra1MouseDoubleClick = CreateComboBox(IDC_COMBO_CTRL_XMOUSE1DBL); m_cbExtra2MouseDoubleClick = CreateComboBox(IDC_COMBO_CTRL_XMOUSE2DBL); m_cbWheelDown = CreateComboBox(IDC_COMBO_CTRL_MWHEELDOWN); m_cbWheelUp = CreateComboBox(IDC_COMBO_CTRL_MWHEELUP); initMouseButtonList(m_cbLeftMouse); initMouseButtonList(m_cbMiddleMouse); initMouseButtonList(m_cbRightMouse); initMouseButtonList(m_cbExtra1Mouse); initMouseButtonList(m_cbExtra2Mouse); initMouseDblList(m_cbLeftMouseDoubleClick); initMouseDblList(m_cbMiddleMouseDoubleClick); initMouseDblList(m_cbRightMouseDoubleClick); initMouseDblList(m_cbExtra1MouseDoubleClick); initMouseDblList(m_cbExtra2MouseDoubleClick); initMouseWheelList(m_cbWheelUp); initMouseWheelList(m_cbWheelDown); return true; } void SetControls::PerformUpdateFromSettings(const Reg::Settings& settings) { m_cbLeftMouse->SetSelection(settings.Mouse.OnMouseLeft); m_cbMiddleMouse->SetSelection(settings.Mouse.OnMouseMiddle); m_cbRightMouse->SetSelection(settings.Mouse.OnMouseRight); m_cbExtra1Mouse->SetSelection(settings.Mouse.OnMouseExtra1); m_cbExtra2Mouse->SetSelection(settings.Mouse.OnMouseExtra2); m_cbLeftMouseDoubleClick->SetSelection(settings.Mouse.OnMouseLeftDbl); m_cbMiddleMouseDoubleClick->SetSelection(settings.Mouse.OnMouseMiddleDbl); m_cbRightMouseDoubleClick->SetSelection(settings.Mouse.OnMouseRightDbl); m_cbExtra1MouseDoubleClick->SetSelection(settings.Mouse.OnMouseExtra1Dbl); m_cbExtra2MouseDoubleClick->SetSelection(settings.Mouse.OnMouseExtra2Dbl); m_cbWheelUp->SetSelection(settings.Mouse.OnMouseWheelUp); m_cbWheelDown->SetSelection(settings.Mouse.OnMouseWheelDown); } void SetControls::onWriteSettings(Reg::Settings& settings) { settings.Mouse.OnMouseLeft = App::MouseAction(m_cbLeftMouse->GetSelectionData()); settings.Mouse.OnMouseMiddle = App::MouseAction(m_cbMiddleMouse->GetSelectionData()); settings.Mouse.OnMouseRight = App::MouseAction(m_cbRightMouse->GetSelectionData()); settings.Mouse.OnMouseExtra1 = App::MouseAction(m_cbExtra1Mouse->GetSelectionData()); settings.Mouse.OnMouseExtra2 = App::MouseAction(m_cbExtra2Mouse->GetSelectionData()); settings.Mouse.OnMouseLeftDbl = App::MouseAction(m_cbLeftMouseDoubleClick->GetSelectionData()); settings.Mouse.OnMouseMiddleDbl = App::MouseAction(m_cbMiddleMouseDoubleClick->GetSelectionData()); settings.Mouse.OnMouseRightDbl = App::MouseAction(m_cbRightMouseDoubleClick->GetSelectionData()); settings.Mouse.OnMouseExtra1Dbl = App::MouseAction(m_cbExtra1MouseDoubleClick->GetSelectionData()); settings.Mouse.OnMouseExtra2Dbl = App::MouseAction(m_cbExtra2MouseDoubleClick->GetSelectionData()); settings.Mouse.OnMouseWheelUp = App::MouseAction(m_cbWheelUp->GetSelectionData()); settings.Mouse.OnMouseWheelDown = App::MouseAction(m_cbWheelDown->GetSelectionData()); } SetControls::SetControls(): App::SettingsPage(IDD_SET_CTRL_MOUSE), m_cbLeftMouse{ nullptr }, m_cbMiddleMouse{ nullptr }, m_cbRightMouse{ nullptr }, m_cbExtra1Mouse{ nullptr }, m_cbExtra2Mouse{ nullptr }, m_cbLeftMouseDoubleClick{ nullptr }, m_cbMiddleMouseDoubleClick{ nullptr }, m_cbRightMouseDoubleClick{ nullptr }, m_cbExtra1MouseDoubleClick{ nullptr }, m_cbExtra2MouseDoubleClick{ nullptr }, m_cbWheelUp{ nullptr }, m_cbWheelDown{ nullptr } {} void SetControls::initMouseButtonList(Win::ComboBox* ctrl) { ctrl->Reset(); ctrl->AddItem(SIDActionDisable, MouseDisable); ctrl->AddItem(SIDActionPan, MousePan); ctrl->AddItem(SIDActionContextMenu, MouseContext); ctrl->AddItem(SIDActionToggleFullSizeDefaultZoom, MouseToggleFullSizeDefaultZoom); ctrl->AddItem(SIDActionFullscreen, MouseFullscreen); ctrl->AddItem(SIDActionNextImage, MouseNextImage); ctrl->AddItem(SIDActionPreviousImage, MousePrevImage); } void SetControls::initMouseDblList(Win::ComboBox* ctrl) { ctrl->Reset(); ctrl->AddItem(SIDActionDisable, MouseDisable); ctrl->AddItem(SIDActionToggleFullSizeDefaultZoom, MouseToggleFullSizeDefaultZoom); ctrl->AddItem(SIDActionFullscreen, MouseFullscreen); } void SetControls::initMouseWheelList(Win::ComboBox* ctrl) { ctrl->Reset(); ctrl->AddItem(SIDActionDisable, MouseDisable); ctrl->AddItem(SIDActionNextImage, MouseNextImage); ctrl->AddItem(SIDActionPreviousImage, MousePrevImage); ctrl->AddItem(SIDActionZoomIn, MouseZoomIn); ctrl->AddItem(SIDActionZoomOut, MouseZoomOut); } } <commit_msg>Add more mouse actions for clicks and doubleclicks<commit_after>#include "res_settings.h" #include "dlg_controls.h" #include "registry.h" namespace App { using namespace Intl; bool SetControls::PerformOnInitPage() { Caption(SIDSettingsControls); ControlText(IDC_GROUP_CLICK, SIDSettingsControlsClick); ControlText(IDC_TEXT_CTRL_LMOUSECLICK, SIDSettingsControlsLeftMouse); ControlText(IDC_TEXT_CTRL_MMOUSECLICK, SIDSettingsControlsMiddleMouse); ControlText(IDC_TEXT_CTRL_RMOUSECLICK, SIDSettingsControlsRightMouse); ControlText(IDC_TEXT_CTRL_XMOUSE1CLICK, SIDSettingsControlsExtra1Mouse); ControlText(IDC_TEXT_CTRL_XMOUSE2CLICK, SIDSettingsControlsExtra2Mouse); ControlText(IDC_GROUP_DOUBLECLICK, SIDSettingsControlsDoubleClick); ControlText(IDC_TEXT_CTRL_LMOUSEDOUBLECLICK, SIDSettingsControlsLeftMouse); ControlText(IDC_TEXT_CTRL_MMOUSEDOUBLECLICK, SIDSettingsControlsMiddleMouse); ControlText(IDC_TEXT_CTRL_RMOUSEDOUBLECLICK, SIDSettingsControlsRightMouse); ControlText(IDC_TEXT_CTRL_XMOUSE1DOUBLECLICK, SIDSettingsControlsExtra1Mouse); ControlText(IDC_TEXT_CTRL_XMOUSE2DOUBLECLICK, SIDSettingsControlsExtra2Mouse); ControlText(IDC_GROUP_MWHEEL, SIDSettingsControlsScrollWheel); ControlText(IDC_TEXT_CTRL_MWHEELUP, SIDSettingsControlsWheelUp); ControlText(IDC_TEXT_CTRL_MWHEELDOWN, SIDSettingsControlsWheelDown); m_cbLeftMouse = CreateComboBox(IDC_COMBO_CTRL_LMOUSE); m_cbMiddleMouse = CreateComboBox(IDC_COMBO_CTRL_MMOUSE); m_cbRightMouse = CreateComboBox(IDC_COMBO_CTRL_RMOUSE); m_cbExtra1Mouse = CreateComboBox(IDC_COMBO_CTRL_XMOUSE1); m_cbExtra2Mouse = CreateComboBox(IDC_COMBO_CTRL_XMOUSE2); m_cbLeftMouseDoubleClick = CreateComboBox(IDC_COMBO_CTRL_LMOUSEDBL); m_cbMiddleMouseDoubleClick = CreateComboBox(IDC_COMBO_CTRL_MMOUSEDBL); m_cbRightMouseDoubleClick = CreateComboBox(IDC_COMBO_CTRL_RMOUSEDBL); m_cbExtra1MouseDoubleClick = CreateComboBox(IDC_COMBO_CTRL_XMOUSE1DBL); m_cbExtra2MouseDoubleClick = CreateComboBox(IDC_COMBO_CTRL_XMOUSE2DBL); m_cbWheelDown = CreateComboBox(IDC_COMBO_CTRL_MWHEELDOWN); m_cbWheelUp = CreateComboBox(IDC_COMBO_CTRL_MWHEELUP); initMouseButtonList(m_cbLeftMouse); initMouseButtonList(m_cbMiddleMouse); initMouseButtonList(m_cbRightMouse); initMouseButtonList(m_cbExtra1Mouse); initMouseButtonList(m_cbExtra2Mouse); initMouseDblList(m_cbLeftMouseDoubleClick); initMouseDblList(m_cbMiddleMouseDoubleClick); initMouseDblList(m_cbRightMouseDoubleClick); initMouseDblList(m_cbExtra1MouseDoubleClick); initMouseDblList(m_cbExtra2MouseDoubleClick); initMouseWheelList(m_cbWheelUp); initMouseWheelList(m_cbWheelDown); return true; } void SetControls::PerformUpdateFromSettings(const Reg::Settings& settings) { m_cbLeftMouse->SetSelection(settings.Mouse.OnMouseLeft); m_cbMiddleMouse->SetSelection(settings.Mouse.OnMouseMiddle); m_cbRightMouse->SetSelection(settings.Mouse.OnMouseRight); m_cbExtra1Mouse->SetSelection(settings.Mouse.OnMouseExtra1); m_cbExtra2Mouse->SetSelection(settings.Mouse.OnMouseExtra2); m_cbLeftMouseDoubleClick->SetSelection(settings.Mouse.OnMouseLeftDbl); m_cbMiddleMouseDoubleClick->SetSelection(settings.Mouse.OnMouseMiddleDbl); m_cbRightMouseDoubleClick->SetSelection(settings.Mouse.OnMouseRightDbl); m_cbExtra1MouseDoubleClick->SetSelection(settings.Mouse.OnMouseExtra1Dbl); m_cbExtra2MouseDoubleClick->SetSelection(settings.Mouse.OnMouseExtra2Dbl); m_cbWheelUp->SetSelection(settings.Mouse.OnMouseWheelUp); m_cbWheelDown->SetSelection(settings.Mouse.OnMouseWheelDown); } void SetControls::onWriteSettings(Reg::Settings& settings) { settings.Mouse.OnMouseLeft = App::MouseAction(m_cbLeftMouse->GetSelectionData()); settings.Mouse.OnMouseMiddle = App::MouseAction(m_cbMiddleMouse->GetSelectionData()); settings.Mouse.OnMouseRight = App::MouseAction(m_cbRightMouse->GetSelectionData()); settings.Mouse.OnMouseExtra1 = App::MouseAction(m_cbExtra1Mouse->GetSelectionData()); settings.Mouse.OnMouseExtra2 = App::MouseAction(m_cbExtra2Mouse->GetSelectionData()); settings.Mouse.OnMouseLeftDbl = App::MouseAction(m_cbLeftMouseDoubleClick->GetSelectionData()); settings.Mouse.OnMouseMiddleDbl = App::MouseAction(m_cbMiddleMouseDoubleClick->GetSelectionData()); settings.Mouse.OnMouseRightDbl = App::MouseAction(m_cbRightMouseDoubleClick->GetSelectionData()); settings.Mouse.OnMouseExtra1Dbl = App::MouseAction(m_cbExtra1MouseDoubleClick->GetSelectionData()); settings.Mouse.OnMouseExtra2Dbl = App::MouseAction(m_cbExtra2MouseDoubleClick->GetSelectionData()); settings.Mouse.OnMouseWheelUp = App::MouseAction(m_cbWheelUp->GetSelectionData()); settings.Mouse.OnMouseWheelDown = App::MouseAction(m_cbWheelDown->GetSelectionData()); } SetControls::SetControls(): App::SettingsPage(IDD_SET_CTRL_MOUSE), m_cbLeftMouse{ nullptr }, m_cbMiddleMouse{ nullptr }, m_cbRightMouse{ nullptr }, m_cbExtra1Mouse{ nullptr }, m_cbExtra2Mouse{ nullptr }, m_cbLeftMouseDoubleClick{ nullptr }, m_cbMiddleMouseDoubleClick{ nullptr }, m_cbRightMouseDoubleClick{ nullptr }, m_cbExtra1MouseDoubleClick{ nullptr }, m_cbExtra2MouseDoubleClick{ nullptr }, m_cbWheelUp{ nullptr }, m_cbWheelDown{ nullptr } {} void SetControls::initMouseButtonList(Win::ComboBox* ctrl) { ctrl->Reset(); ctrl->AddItem(SIDActionDisable, MouseDisable); ctrl->AddItem(SIDActionPan, MousePan); ctrl->AddItem(SIDActionContextMenu, MouseContext); ctrl->AddItem(SIDActionToggleFullSizeDefaultZoom, MouseToggleFullSizeDefaultZoom); ctrl->AddItem(SIDActionFullscreen, MouseFullscreen); ctrl->AddItem(SIDActionNextImage, MouseNextImage); ctrl->AddItem(SIDActionPreviousImage, MousePrevImage); ctrl->AddItem(SIDActionZoomIn, MouseZoomIn); ctrl->AddItem(SIDActionZoomOut, MouseZoomOut); } void SetControls::initMouseDblList(Win::ComboBox* ctrl) { ctrl->Reset(); ctrl->AddItem(SIDActionDisable, MouseDisable); ctrl->AddItem(SIDActionContextMenu, MouseContext); ctrl->AddItem(SIDActionToggleFullSizeDefaultZoom, MouseToggleFullSizeDefaultZoom); ctrl->AddItem(SIDActionFullscreen, MouseFullscreen); ctrl->AddItem(SIDActionNextImage, MouseNextImage); ctrl->AddItem(SIDActionPreviousImage, MousePrevImage); ctrl->AddItem(SIDActionZoomIn, MouseZoomIn); ctrl->AddItem(SIDActionZoomOut, MouseZoomOut); } void SetControls::initMouseWheelList(Win::ComboBox* ctrl) { ctrl->Reset(); ctrl->AddItem(SIDActionDisable, MouseDisable); ctrl->AddItem(SIDActionNextImage, MouseNextImage); ctrl->AddItem(SIDActionPreviousImage, MousePrevImage); ctrl->AddItem(SIDActionZoomIn, MouseZoomIn); ctrl->AddItem(SIDActionZoomOut, MouseZoomOut); } } <|endoftext|>
<commit_before><commit_msg>crs wants tabs=4<commit_after><|endoftext|>
<commit_before>// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: lineModel.C,v 1.8 2003/12/12 17:51:51 amoll Exp $ #include <BALL/VIEW/MODELS/lineModel.h> #include <BALL/KERNEL/atom.h> #include <BALL/KERNEL/bond.h> #include <BALL/VIEW/PRIMITIVES/point.h> #include <BALL/VIEW/PRIMITIVES/twoColoredLine.h> using namespace std; namespace BALL { namespace VIEW { AddLineModel::AddLineModel() throw() : AtomBondModelBaseProcessor() { } AddLineModel::AddLineModel(const AddLineModel& model) throw() : AtomBondModelBaseProcessor(model) { } AddLineModel::~AddLineModel() throw() { #ifdef BALL_VIEW_DEBUG Log.error() << "Destructing object " << (void *)this << " of class " << RTTI::getName<AddLineModel>() << std::endl; #endif } Processor::Result AddLineModel::operator() (Composite &composite) { if (!RTTI::isKindOf<Atom>(composite)) { return Processor::CONTINUE; } Atom *atom = RTTI::castTo<Atom>(composite); Point *point_ptr = new Point; if (point_ptr == 0) throw Exception::OutOfMemory(__FILE__, __LINE__, sizeof(Point)); point_ptr->setVertex(atom->getPosition()); point_ptr->setComposite(atom); // append line in Atom geometric_objects_.push_back(point_ptr); // collect used atoms insertAtom_(atom); return Processor::CONTINUE; } void AddLineModel::dump(ostream& s, Size depth) const throw() { BALL_DUMP_STREAM_PREFIX(s); BALL_DUMP_DEPTH(s, depth); BALL_DUMP_HEADER(s, this, this); AtomBondModelBaseProcessor::dump(s, depth + 1); BALL_DUMP_STREAM_SUFFIX(s); } void AddLineModel::visualiseBond_(const Bond& bond) throw() { // generate two colored tube TwoColoredLine *line = new TwoColoredLine; if (line == 0) throw Exception::OutOfMemory(__FILE__, __LINE__, sizeof(TwoColoredLine)); if (bond.getFirstAtom() == 0 || bond.getSecondAtom() == 0) { throw Exception::NullPointer(__FILE__, __LINE__); } line->setVertex1Address(bond.getFirstAtom()->getPosition()); line->setVertex2Address(bond.getSecondAtom()->getPosition()); line->setComposite(&bond); geometric_objects_.push_back(line); } } // namespace VIEW } // namespace BALL <commit_msg>fixed: now using pointer for vertex in point<commit_after>// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: lineModel.C,v 1.9 2003/12/16 21:16:34 amoll Exp $ #include <BALL/VIEW/MODELS/lineModel.h> #include <BALL/KERNEL/atom.h> #include <BALL/KERNEL/bond.h> #include <BALL/VIEW/PRIMITIVES/point.h> #include <BALL/VIEW/PRIMITIVES/twoColoredLine.h> using namespace std; namespace BALL { namespace VIEW { AddLineModel::AddLineModel() throw() : AtomBondModelBaseProcessor() { } AddLineModel::AddLineModel(const AddLineModel& model) throw() : AtomBondModelBaseProcessor(model) { } AddLineModel::~AddLineModel() throw() { #ifdef BALL_VIEW_DEBUG Log.error() << "Destructing object " << (void *)this << " of class " << RTTI::getName<AddLineModel>() << std::endl; #endif } Processor::Result AddLineModel::operator() (Composite &composite) { if (!RTTI::isKindOf<Atom>(composite)) { return Processor::CONTINUE; } Atom *atom = RTTI::castTo<Atom>(composite); Point *point_ptr = new Point; if (point_ptr == 0) throw Exception::OutOfMemory(__FILE__, __LINE__, sizeof(Point)); point_ptr->setVertexAddress(atom->getPosition()); point_ptr->setComposite(atom); // append line in Atom geometric_objects_.push_back(point_ptr); // collect used atoms insertAtom_(atom); return Processor::CONTINUE; } void AddLineModel::dump(ostream& s, Size depth) const throw() { BALL_DUMP_STREAM_PREFIX(s); BALL_DUMP_DEPTH(s, depth); BALL_DUMP_HEADER(s, this, this); AtomBondModelBaseProcessor::dump(s, depth + 1); BALL_DUMP_STREAM_SUFFIX(s); } void AddLineModel::visualiseBond_(const Bond& bond) throw() { // generate two colored tube TwoColoredLine *line = new TwoColoredLine; if (line == 0) throw Exception::OutOfMemory(__FILE__, __LINE__, sizeof(TwoColoredLine)); if (bond.getFirstAtom() == 0 || bond.getSecondAtom() == 0) { throw Exception::NullPointer(__FILE__, __LINE__); } line->setVertex1Address(bond.getFirstAtom()->getPosition()); line->setVertex2Address(bond.getSecondAtom()->getPosition()); line->setComposite(&bond); geometric_objects_.push_back(line); } } // namespace VIEW } // namespace BALL <|endoftext|>
<commit_before>#include <stdio.h> #include "Halide.h" #include <fstream> #include <cassert> #include <iostream> #include "test/common/halide_test_dirs.h" using namespace Halide; int main(int argc, char **argv) { Var x("x"), y("y"); Func f("f"); f(x, y) = 42; std::string bitcode_file = Internal::get_test_tmp_dir() + "extern.bc"; f.compile_to_bitcode(bitcode_file, {}, "extern"); std::vector<uint8_t> bitcode; std::ifstream bitcode_stream(bitcode_file, std::ios::in | std::ios::binary); bitcode_stream.seekg(0, std::ios::end); bitcode.resize(bitcode_stream.tellg()); bitcode_stream.seekg(0, std::ios::beg); bitcode_stream.read(reinterpret_cast<char *>(&bitcode[0]), bitcode.size()); ExternalCode external_code = ExternalCode::bitcode_wrapper(get_target_from_environment(), bitcode, "extern"); Func f_extern; f_extern.define_extern("extern", { }, type_of<int32_t>(), 2); Func result; result(x, y) = f_extern(x, y); Module module = result.compile_to_module({}, "forty_two"); module.append(external_code); auto forty_two = module.get_function_by_name("forty_two"); Internal::JITModule jit_module(module, forty_two, {}); auto main_function = (int (*)(halide_buffer_t *buf))jit_module.main_function(); Buffer<int32_t> buf(16, 16); int ret_code = main_function(buf.raw_buffer()); assert(ret_code == 0); for (int i = 0; i < 16; i++) { for (int j = 0; j < 16; j++) { assert(buf(i, j) == 42); } } printf("Success!\n"); return 0; } <commit_msg>Attempt to fix MinGW test failure.<commit_after>#include <stdio.h> #include "Halide.h" #include <fstream> #include <cassert> #include <iostream> #include "test/common/halide_test_dirs.h" using namespace Halide; int main(int argc, char **argv) { Var x("x"), y("y"); Func f("f"); f(x, y) = 42; std::string bitcode_file = Internal::get_test_tmp_dir() + "extern.bc"; f.compile_to_bitcode(bitcode_file, {}, "extern"); std::vector<uint8_t> bitcode; std::ifstream bitcode_stream(bitcode_file, std::ios::in | std::ios::binary); bitcode_stream.seekg(0, std::ios::end); bitcode.resize(bitcode_stream.tellg()); bitcode_stream.seekg(0, std::ios::beg); bitcode_stream.read(reinterpret_cast<char *>(&bitcode[0]), bitcode.size()); ExternalCode external_code = ExternalCode::bitcode_wrapper(get_jit_target_from_environment(), bitcode, "extern"); Func f_extern; f_extern.define_extern("extern", { }, type_of<int32_t>(), 2); Func result; result(x, y) = f_extern(x, y); Module module = result.compile_to_module({}, "forty_two"); module.append(external_code); auto forty_two = module.get_function_by_name("forty_two"); Internal::JITModule jit_module(module, forty_two, {}); auto main_function = (int (*)(halide_buffer_t *buf))jit_module.main_function(); Buffer<int32_t> buf(16, 16); int ret_code = main_function(buf.raw_buffer()); assert(ret_code == 0); for (int i = 0; i < 16; i++) { for (int j = 0; j < 16; j++) { assert(buf(i, j) == 42); } } printf("Success!\n"); return 0; } <|endoftext|>
<commit_before> #include <time.h> #include "core/EpsilonManager.h" #include <SFML/Window/Event.hpp> #include <SFML/System/Clock.hpp> #include "render/MeshFactory.h" #include "math/Defines.h" namespace epsilon { EpsilonManager::EpsilonManager(void) { } EpsilonManager::~EpsilonManager(void) { //if ( sceneManager ) { delete sceneManager; } if ( uiManager ) { delete uiManager; } if ( renderManager ) { delete renderManager; } if ( scriptManager ) { delete scriptManager; } } void EpsilonManager::Setup(void) { Log("Initialising Epsilon Manager"); scriptManager = new ScriptManager(); scriptManager->Setup(); renderManager = new RenderManager(); renderManager->Setup(); uiManager = new UIManager(); uiManager->Setup(); ConsoleWindow::Ptr consoleWindow = ConsoleWindow::Create(); consoleWindow->Setup(); uiManager->AddUIWindow(consoleWindow); //sceneManager = new SceneManager(); sceneManager = &SceneManager::GetInstance(); sceneManager->Setup(); renderManager->SetSceneManager(sceneManager); renderManager->SetUIManager(uiManager); MeshTest(); Log("Finished Setup"); cycle.SetFrequency(100); camera = sceneManager->CurrentScene()->GetActiveCamera(); camera->GetComponent<Transform>()->SetPosition(0.0f, 1.0f, -8.f); camera->LookAt(Vector3()); } void EpsilonManager::MeshTest(void) { //Node::Ptr triangle2 = sceneManager->CurrentScene()->Root()->CreateChildNode(); //triangle2->SetName("triangle"); //triangle2->AddComponent(Renderer::Create()); //triangle2->GetComponent<Renderer>() // ->SetMesh(MeshFactory::GenerateTriangle()); //triangleTrans = triangle2->GetComponent<Transform>(); //triangleTrans->SetPosition(0.f, 0.f, 0.f); // //// Add a sub child Node::Ptr tChild = sceneManager->CurrentScene()->Root()->CreateChildNode(); tChild->SetName("sphere"); tChild->AddComponent(Renderer::Create()); tChild->GetComponent<Renderer>() ->SetMesh(MeshFactory::GenerateSphere()); tChild->GetComponent<Transform>() ->SetPosition(1.0f, 1.0f, 0.0f); // Node::Ptr plane = sceneManager->CurrentScene()->Root()->CreateChildNode(); plane->SetName("plane"); plane->AddComponent(Renderer::Create()); plane->GetComponent<Renderer>() ->SetMesh(MeshFactory::GeneratePlane(4, 4)); float angle = Math::DegreesToRadians(1.0f); plane->GetComponent<Transform>() //->SetPosition(0.0f, -0.0f, 0.0f) //.Yaw(angle) ->SetScale(Vector3(2.0f)); plane->AddComponent(scriptManager->CreateBehaviour("MyBehaviour.py")); // Create a Grid if ( true ) { Node::Ptr grid = sceneManager->CurrentScene()->Root()->CreateChildNode(); grid->SetName("grid"); grid->AddComponent(Renderer::Create()); grid->GetComponent<Renderer>() ->SetMesh(MeshFactory::GenerateGrid(10, 1)); } } //void EpsilonManager::OnUpdate(sf::Time el) void EpsilonManager::OnUpdate(float el) { scriptManager->Update(el); uiManager->OnUpdate(el); sceneManager->Cull(); renderManager->Draw(el); } void EpsilonManager::Run(void) { // Run Loop // Handle events here until event manager is implemented. sf::Event event; //sf::Clock clock; clock_t lastTime = clock(); float el = 0.0f; while ( renderManager->WindowOpen() ) { //clock.restart(); //sleep(Time(milliseconds(1))); while ( renderManager->PollEvent( event ) ) { uiManager->ProcessEvent(event); if ( event.type == sf::Event::Closed ) { renderManager->CloseWindow(); } if ( event.type == sf::Event::KeyPressed ) { if ( event.key.code == sf::Keyboard::Escape ) { renderManager->CloseWindow(); } } if ( event.type == sf::Event::KeyReleased ) { Transform::Ptr camTrans = camera->GetComponent<Transform>(); float amount = 1.0f;// * el; Vector3 trans; switch ( event.key.code ) { case sf::Keyboard::A: trans.x = -amount; break; case sf::Keyboard::D: trans.x = amount; break; case sf::Keyboard::W: trans.z = amount; break; case sf::Keyboard::S: trans.z = -amount; break; case sf::Keyboard::R: trans.y = amount; break; case sf::Keyboard::F: trans.y = -amount; break; } camTrans->Translate(trans); //triangleTrans->Translate(trans); //aLog(std::to_string(triangleTrans->GetPosition().z)); Vector3 la = camTrans->GetPosition() + (Vector3(0, 0, 5.0f)); camera->LookAt(Vector3()); } } //OnUpdate(clock.getElapsedTime()); clock_t currTime = clock(); el = (float)diffclock(currTime, lastTime) / 1000.0f; OnUpdate(el); lastTime = currTime; } } }<commit_msg>M Fixed elapsed time calculation M Made changes as to how managers are handled as they become Singletons.<commit_after> #include <time.h> #include "core/EpsilonManager.h" #include <SFML/Window/Event.hpp> #include <SFML/System/Clock.hpp> #include "render/MeshFactory.h" #include "math/Defines.h" namespace epsilon { EpsilonManager::EpsilonManager(void) { } EpsilonManager::~EpsilonManager(void) { if ( uiManager ) { delete uiManager; } //if ( renderManager ) { delete renderManager; } } void EpsilonManager::Setup(void) { Log("Initialising Epsilon Manager"); scriptManager = &ScriptManager::GetInstance(); scriptManager->Setup(); renderManager = &RenderManager::GetInstance(); renderManager->Setup(); uiManager = new UIManager(); uiManager->Setup(); ConsoleWindow::Ptr consoleWindow = ConsoleWindow::Create(); consoleWindow->Setup(); uiManager->AddUIWindow(consoleWindow); sceneManager = &SceneManager::GetInstance(); sceneManager->Setup(); renderManager->SetSceneManager(sceneManager); renderManager->SetUIManager(uiManager); MeshTest(); Log("Finished Setup"); cycle.SetFrequency(100); camera = sceneManager->CurrentScene()->GetActiveCamera(); camera->GetComponent<Transform>()->SetPosition(0.0f, 1.0f, -8.f); camera->LookAt(Vector3()); } void EpsilonManager::MeshTest(void) { //Node::Ptr triangle2 = sceneManager->CurrentScene()->Root()->CreateChildNode(); //triangle2->SetName("triangle"); //triangle2->AddComponent(Renderer::Create()); //triangle2->GetComponent<Renderer>() // ->SetMesh(MeshFactory::GenerateTriangle()); //triangleTrans = triangle2->GetComponent<Transform>(); //triangleTrans->SetPosition(0.f, 0.f, 0.f); // //// Add a sub child Node::Ptr tChild = sceneManager->CurrentScene()->Root()->CreateChildNode(); tChild->SetName("sphere"); tChild->AddComponent(Renderer::Create()); tChild->GetComponent<Renderer>() ->SetMesh(MeshFactory::GenerateSphere()); tChild->GetComponent<Transform>() ->SetPosition(1.0f, 1.0f, 0.0f); tChild->AddComponent(scriptManager->CreateBehaviour("MyBehaviourClass.py")); // Node::Ptr plane = sceneManager->CurrentScene()->Root()->CreateChildNode(); plane->SetName("plane"); plane->AddComponent(Renderer::Create()); plane->GetComponent<Renderer>() ->SetMesh(MeshFactory::GeneratePlane(4, 4)); Node::Ptr scriptsRoot = sceneManager->CurrentScene()->Root()->CreateChildNode(); scriptsRoot->SetName("scriptRoot"); Node::Ptr script2 = scriptsRoot->CreateChildNode(); script2->AddComponent(scriptManager->CreateBehaviour("TestingFeatures.py")); // Create a Grid if ( true ) { Node::Ptr grid = sceneManager->CurrentScene()->Root()->CreateChildNode(); grid->SetName("grid"); grid->AddComponent(Renderer::Create()); grid->GetComponent<Renderer>() ->SetMesh(MeshFactory::GenerateGrid(10, 1)); } } //void EpsilonManager::OnUpdate(sf::Time el) void EpsilonManager::OnUpdate(float el) { scriptManager->Update(el); uiManager->OnUpdate(el); sceneManager->Cull(); renderManager->Draw(el); } void EpsilonManager::Run(void) { // Run Loop // Handle events here until event manager is implemented. sf::Event event; sf::Clock clock; while ( renderManager->WindowOpen() ) { while ( renderManager->PollEvent( event ) ) { uiManager->ProcessEvent(event); if ( event.type == sf::Event::Closed ) { renderManager->CloseWindow(); } if ( event.type == sf::Event::KeyPressed ) { if ( event.key.code == sf::Keyboard::Escape ) { renderManager->CloseWindow(); } } if ( event.type == sf::Event::KeyReleased ) { Transform::Ptr camTrans = camera->GetComponent<Transform>(); float amount = 1.0f;// * el; Vector3 trans; switch ( event.key.code ) { case sf::Keyboard::A: trans.x = -amount; break; case sf::Keyboard::D: trans.x = amount; break; case sf::Keyboard::W: trans.z = amount; break; case sf::Keyboard::S: trans.z = -amount; break; case sf::Keyboard::R: trans.y = amount; break; case sf::Keyboard::F: trans.y = -amount; break; } camTrans->Translate(trans); Vector3 la = camTrans->GetPosition() + (Vector3(0, 0, 5.0f)); camera->LookAt(Vector3()); } } float el = clock.getElapsedTime().asMicroseconds() / 1000000.0f; // Restart timing for next sequence clock.restart(); OnUpdate(el); } } }<|endoftext|>
<commit_before>/* This code is subject to the terms of the Mozilla Public License, v.2.0. http://mozilla.org/MPL/2.0/. */ #include "unittest.h" #include "FileStore.h" #include "readstream.h" #include "writestream.h" #include "common/MyMemberId.h" #include "file/File.h" #include "serialize/str_join.h" #include <boost/filesystem.hpp> #include <memory> #include <string> #include <vector> using std::shared_ptr; using std::string; using std::vector; namespace { string _test_dir = "/tmp/turbo_fs_test"; class DirectoryCleaner { public: ~DirectoryCleaner() { boost::filesystem::remove_all(_test_dir); } protected: }; class TestableFileStore : public FileStore { public: using FileStore::FileStore; using FileStore::bestVersion; using FileStore::dirpath; using FileStore::filepath; }; void write_file(FileStore& store, const std::string& name, const std::string& contents) { writestream writer = store.write(name); assert( writer.good() ); writer.write(contents.data(), contents.size()); writer.close(); } } TEST_CASE( "FileStoreTest/testPaths", "[unit]" ) { DirectoryCleaner cleaner; TestableFileStore store(_test_dir); assertEquals( "/tmp/turbo_fs_test/myfile", store.dirpath("myfile") ); assertEquals( "/tmp/turbo_fs_test/myfile/v1", store.filepath("myfile", "v1") ); } TEST_CASE( "FileStoreTest/testWrite", "[unit]" ) { MyMemberId("1"); DirectoryCleaner cleaner; FileStore store(_test_dir); writestream writer = store.write("myfile"); assertTrue( writer.good() ); string bytes = "0123456789"; assertEquals( 10, writer.write(bytes.data(), bytes.size()) ); // won't be in the right place while the write is in progress. vector<string> versions = store.versions("myfile"); assertEquals( "", turbo::str::join(versions) ); // but if we ask for in progress writes, we should see it. versions = store.versions("myfile", true); assertEquals( "1,1:1", turbo::str::join(versions) ); readstream reader = store.read("myfile", "1,1:1"); assertFalse( reader.good() ); // close/commit, and all is well. assertTrue( writer.close() ); versions = store.versions("myfile"); assertEquals( "1,1:1", turbo::str::join(versions) ); reader = store.read("myfile", "1,1:1"); assertTrue( reader.good() ); assertEquals( 10, reader.size() ); } TEST_CASE( "FileStoreTest/testReadNewest", "[unit]" ) { MyMemberId("1"); DirectoryCleaner cleaner; FileStore store(_test_dir); { writestream writer = store.write("myfile"); assertTrue( writer.good() ); string bytes = "0123456789"; assertEquals( 10, writer.write(bytes.data(), bytes.size()) ); assertTrue( writer.close() ); } { readstream reader = store.read("myfile"); assertTrue( reader.good() ); assertEquals( "1,1:1", reader.version() ); assertEquals( 10, reader.size() ); } { writestream writer = store.write("myfile"); assertTrue( writer.good() ); string bytes = "abcdef"; assertEquals( 6, writer.write(bytes.data(), bytes.size()) ); assertTrue( writer.close() ); } { readstream reader = store.read("myfile"); assertTrue( reader ); assertEquals( "1,1:2", reader.version() ); assertEquals( 6, reader.size() ); } } TEST_CASE( "FileStoreTest/testReadAll", "[unit]" ) { MyMemberId("1"); DirectoryCleaner cleaner; FileStore store(_test_dir); { VectorClock version; version.increment("foo"); writestream writer = store.write("myfile", version.toString()); assertTrue( writer.good() ); string bytes = "0123456789"; assertEquals( 10, writer.write(bytes.data(), bytes.size()) ); assertTrue( writer.close() ); } { readstream reader = store.read("myfile"); assertTrue( reader.good() ); assertEquals( "1,foo:1", reader.version() ); assertEquals( 10, reader.size() ); } { VectorClock version; version.increment("bar"); writestream writer = store.write("myfile", version.toString()); assertTrue( writer.good() ); string bytes = "abcdef"; assertEquals( 6, writer.write(bytes.data(), bytes.size()) ); assertTrue( writer.close() ); readstream reader = store.read("myfile", version.toString()); assertTrue( reader ); assertEquals( "1,bar:1", reader.version() ); assertEquals( 6, reader.size() ); } std::vector<readstream> readers = store.readAll("myfile"); assertEquals( 2, readers.size() ); assertTrue( readers[0] ); assertEquals( "1,foo:1", readers[0].version() ); assertEquals( 10, readers[0].size() ); assertTrue( readers[1] ); assertEquals( "1,bar:1", readers[1].version() ); assertEquals( 6, readers[1].size() ); } TEST_CASE( "FileStoreTest/testEnumerate", "[unit]" ) { MyMemberId("1"); DirectoryCleaner cleaner; FileStore store(_test_dir); write_file(store, "foo", "0123456789"); write_file(store, "bar", "abcde"); write_file(store, "oof", "lmno"); std::vector<string> files; auto fun = [&files] (const std::string& name) { files.push_back(name); return true; }; store.enumerate(fun, 100); assertEquals( "foo oof bar", turbo::str::join(files) ); } <commit_msg>sort plz k thx.<commit_after>/* This code is subject to the terms of the Mozilla Public License, v.2.0. http://mozilla.org/MPL/2.0/. */ #include "unittest.h" #include "FileStore.h" #include "readstream.h" #include "writestream.h" #include "common/MyMemberId.h" #include "file/File.h" #include "serialize/str_join.h" #include <boost/filesystem.hpp> #include <algorithm> #include <memory> #include <string> #include <vector> using std::shared_ptr; using std::string; using std::vector; namespace { string _test_dir = "/tmp/turbo_fs_test"; class DirectoryCleaner { public: ~DirectoryCleaner() { boost::filesystem::remove_all(_test_dir); } protected: }; class TestableFileStore : public FileStore { public: using FileStore::FileStore; using FileStore::bestVersion; using FileStore::dirpath; using FileStore::filepath; }; void write_file(FileStore& store, const std::string& name, const std::string& contents) { writestream writer = store.write(name); assert( writer.good() ); writer.write(contents.data(), contents.size()); writer.close(); } } TEST_CASE( "FileStoreTest/testPaths", "[unit]" ) { DirectoryCleaner cleaner; TestableFileStore store(_test_dir); assertEquals( "/tmp/turbo_fs_test/myfile", store.dirpath("myfile") ); assertEquals( "/tmp/turbo_fs_test/myfile/v1", store.filepath("myfile", "v1") ); } TEST_CASE( "FileStoreTest/testWrite", "[unit]" ) { MyMemberId("1"); DirectoryCleaner cleaner; FileStore store(_test_dir); writestream writer = store.write("myfile"); assertTrue( writer.good() ); string bytes = "0123456789"; assertEquals( 10, writer.write(bytes.data(), bytes.size()) ); // won't be in the right place while the write is in progress. vector<string> versions = store.versions("myfile"); assertEquals( "", turbo::str::join(versions) ); // but if we ask for in progress writes, we should see it. versions = store.versions("myfile", true); assertEquals( "1,1:1", turbo::str::join(versions) ); readstream reader = store.read("myfile", "1,1:1"); assertFalse( reader.good() ); // close/commit, and all is well. assertTrue( writer.close() ); versions = store.versions("myfile"); assertEquals( "1,1:1", turbo::str::join(versions) ); reader = store.read("myfile", "1,1:1"); assertTrue( reader.good() ); assertEquals( 10, reader.size() ); } TEST_CASE( "FileStoreTest/testReadNewest", "[unit]" ) { MyMemberId("1"); DirectoryCleaner cleaner; FileStore store(_test_dir); { writestream writer = store.write("myfile"); assertTrue( writer.good() ); string bytes = "0123456789"; assertEquals( 10, writer.write(bytes.data(), bytes.size()) ); assertTrue( writer.close() ); } { readstream reader = store.read("myfile"); assertTrue( reader.good() ); assertEquals( "1,1:1", reader.version() ); assertEquals( 10, reader.size() ); } { writestream writer = store.write("myfile"); assertTrue( writer.good() ); string bytes = "abcdef"; assertEquals( 6, writer.write(bytes.data(), bytes.size()) ); assertTrue( writer.close() ); } { readstream reader = store.read("myfile"); assertTrue( reader ); assertEquals( "1,1:2", reader.version() ); assertEquals( 6, reader.size() ); } } TEST_CASE( "FileStoreTest/testReadAll", "[unit]" ) { MyMemberId("1"); DirectoryCleaner cleaner; FileStore store(_test_dir); { VectorClock version; version.increment("foo"); writestream writer = store.write("myfile", version.toString()); assertTrue( writer.good() ); string bytes = "0123456789"; assertEquals( 10, writer.write(bytes.data(), bytes.size()) ); assertTrue( writer.close() ); } { readstream reader = store.read("myfile"); assertTrue( reader.good() ); assertEquals( "1,foo:1", reader.version() ); assertEquals( 10, reader.size() ); } { VectorClock version; version.increment("bar"); writestream writer = store.write("myfile", version.toString()); assertTrue( writer.good() ); string bytes = "abcdef"; assertEquals( 6, writer.write(bytes.data(), bytes.size()) ); assertTrue( writer.close() ); readstream reader = store.read("myfile", version.toString()); assertTrue( reader ); assertEquals( "1,bar:1", reader.version() ); assertEquals( 6, reader.size() ); } std::vector<readstream> readers = store.readAll("myfile"); assertEquals( 2, readers.size() ); assertTrue( readers[0] ); assertEquals( "1,foo:1", readers[0].version() ); assertEquals( 10, readers[0].size() ); assertTrue( readers[1] ); assertEquals( "1,bar:1", readers[1].version() ); assertEquals( 6, readers[1].size() ); } TEST_CASE( "FileStoreTest/testEnumerate", "[unit]" ) { MyMemberId("1"); DirectoryCleaner cleaner; FileStore store(_test_dir); write_file(store, "foo", "0123456789"); write_file(store, "bar", "abcde"); write_file(store, "oof", "lmno"); std::vector<string> files; auto fun = [&files] (const std::string& name) { files.push_back(name); return true; }; store.enumerate(fun, 100); std::sort(files.begin(), files.end()); assertEquals( "bar foo oof", turbo::str::join(files) ); } <|endoftext|>
<commit_before>#ifdef STAN_OPENCL #include <stan/math/prim/mat/fun/typedefs.hpp> #include <stan/math/opencl/copy.hpp> #include <stan/math/opencl/add.hpp> #include <gtest/gtest.h> #include <algorithm> TEST(MathMatrixGPU, add_v_exception_pass) { stan::math::vector_d d1, d2; d1.resize(3); d2.resize(3); stan::math::matrix_cl d11(d1); stan::math::matrix_cl d22(d2); stan::math::matrix_cl d33(3, 1); EXPECT_NO_THROW(d33 = d11 + d22); } TEST(MathMatrixGPU, add_v_exception_pass_zero) { stan::math::vector_d d1, d2; d1.resize(0); d2.resize(0); stan::math::matrix_cl d11(d1); stan::math::matrix_cl d22(d2); stan::math::matrix_cl d33(0, 1); EXPECT_NO_THROW(d33 = d11 + d22); } TEST(MathMatrixGPU, add_v_exception_pass_invalid_arg) { stan::math::row_vector_d d1, d2; d1.resize(2); d2.resize(3); stan::math::matrix_cl d11(d1); stan::math::matrix_cl d22(d2); stan::math::matrix_cl d33(3, 0); EXPECT_THROW(d33 = d11 + d22, std::invalid_argument); } TEST(MathMatrixGPU, add_rv_exception_pass) { stan::math::row_vector_d d1, d2; d1.resize(3); d2.resize(3); stan::math::matrix_cl d11(d1); stan::math::matrix_cl d22(d2); stan::math::matrix_cl d33(1, 3); EXPECT_NO_THROW(d33 = d11 + d22); } TEST(MathMatrixGPU, add_rv_exception_pass_zero) { stan::math::row_vector_d d1, d2; d1.resize(0); d2.resize(0); stan::math::matrix_cl d11(d1); stan::math::matrix_cl d22(d2); stan::math::matrix_cl d33(1, 0); EXPECT_NO_THROW(d33 = d11 + d22); } TEST(MathMatrixGPU, add_rv_exception_fail_invalid_arg) { stan::math::row_vector_d d1, d2; d1.resize(2); d2.resize(3); stan::math::matrix_cl d11(d1); stan::math::matrix_cl d22(d2); stan::math::matrix_cl d33(3, 1); EXPECT_THROW(d33 = d11 + d22, std::invalid_argument); } TEST(MathMatrixGPU, add_m_exception_pass_simple) { stan::math::matrix_d d1, d2; d1.resize(2, 3); d2.resize(2, 3); stan::math::matrix_cl d11(d1); stan::math::matrix_cl d22(d2); stan::math::matrix_cl d33(2, 3); EXPECT_NO_THROW(d33 = d11 + d22); } TEST(MathMatrixGPU, add_m_exception_pass_zero) { stan::math::matrix_d d1, d2; d1.resize(0, 0); d2.resize(0, 0); stan::math::matrix_cl d11(d1); stan::math::matrix_cl d22(d2); stan::math::matrix_cl d33(0, 0); EXPECT_NO_THROW(d33 = d11 + d22); } TEST(MathMatrixGPU, add_m_exception_fail_invalid_arg) { stan::math::matrix_d d1, d2; d1.resize(2, 3); d2.resize(3, 3); stan::math::matrix_cl d11(d1); stan::math::matrix_cl d22(d2); stan::math::matrix_cl d33(2, 3); EXPECT_THROW(d33 = d11 + d22, std::invalid_argument); } TEST(MathMatrixGPU, add_non_matching_sizes_exception) { stan::math::vector_d v1(2); v1 << 1, 2; stan::math::vector_d v2(3); v2 << 10, 100, 1000; stan::math::row_vector_d rv1(2); rv1 << 1, 2; stan::math::row_vector_d rv2(3); rv2 << 10, 100, 1000; stan::math::matrix_d m1(2, 3); m1 << 1, 2, 3, 4, 5, 6; stan::math::matrix_d m2(3, 2); m2 << 10, 100, 1000, 0, -10, -12; using stan::math::add; using stan::math::matrix_cl; matrix_cl v11(v1); matrix_cl v22(v2); matrix_cl v33(v1); matrix_cl rv11(rv1); matrix_cl rv22(rv2); matrix_cl rv33(rv1); matrix_cl m11(m1); matrix_cl m22(m2); matrix_cl m33(m1); EXPECT_THROW(v33 = v11 + v22, std::invalid_argument); EXPECT_THROW(rv33 = rv11 + rv22, std::invalid_argument); EXPECT_THROW(m33 = m11 + m22, std::invalid_argument); } TEST(MathMatrixGPU, add_value_check) { stan::math::vector_d v1(3); v1 << 1, 2, 3; stan::math::vector_d v2(3); v2 << 10, 100, 1000; stan::math::vector_d v3(3); stan::math::row_vector_d rv1(3); rv1 << 1, 2, 3; stan::math::row_vector_d rv2(3); rv2 << 10, 100, 1000; stan::math::row_vector_d rv3(3); stan::math::matrix_d m1(3, 3); m1 << 1, 2, 3, 4, 5, 6, 7, 8, 9; stan::math::matrix_d m2(3, 3); m2 << 10, 100, 1000, 0, -10, -12, 2, 4, 8; stan::math::matrix_d m3(3, 3); using stan::math::add; using stan::math::matrix_cl; matrix_cl v11(v1); matrix_cl v22(v2); matrix_cl v33(3, 1); matrix_cl rv11(rv1); matrix_cl rv22(rv2); matrix_cl rv33(1, 3); matrix_cl m11(m1); matrix_cl m22(m2); matrix_cl m33(3, 3); EXPECT_NO_THROW(v33 = v11 + v22); EXPECT_NO_THROW(rv33 = rv11 + rv22); EXPECT_NO_THROW(m33 = m11 + m22); stan::math::copy(v3, v33); EXPECT_EQ(11, v3(0)); EXPECT_EQ(102, v3(1)); EXPECT_EQ(1003, v3(2)); stan::math::copy(rv3, rv33); EXPECT_EQ(11, rv3(0)); EXPECT_EQ(102, rv3(1)); EXPECT_EQ(1003, rv3(2)); stan::math::copy(m3, m33); EXPECT_EQ(11, m3(0, 0)); EXPECT_EQ(102, m3(0, 1)); EXPECT_EQ(1003, m3(0, 2)); EXPECT_EQ(4, m3(1, 0)); EXPECT_EQ(-5, m3(1, 1)); EXPECT_EQ(-6, m3(1, 2)); EXPECT_EQ(9, m3(2, 0)); EXPECT_EQ(12, m3(2, 1)); EXPECT_EQ(17, m3(2, 2)); } TEST(MathMatrixGPU, add_batch) { // used to represent 5 matrices of size 10x10 const int batch_size = 11; const int size = 13; stan::math::matrix_d a(size, size * batch_size); stan::math::matrix_d a_res(size, size); for (int k = 0; k < batch_size; k++) { for (int i = 0; i < size; i++) for (int j = 0; j < size; j++) { a(i, k * size + j) = k; } } stan::math::matrix_cl a_cl(a); stan::math::matrix_cl a_cl_res(size, size); stan::math::opencl_kernels::add_batch(cl::NDRange(size, size), a_cl_res, a_cl, size, size, batch_size); copy(a_res, a_cl_res); for (int k = 0; k < batch_size; k++) { for (int i = 0; i < size; i++) for (int j = 0; j < size; j++) { a(i, j) += a(i, k * size + j); } } for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { EXPECT_EQ(a(i, j), a_res(i, j)); } } } #endif <commit_msg>[Jenkins] auto-formatting by clang-format version 5.0.2-svn328729-1~exp1~20180509124008.99 (branches/release_50)<commit_after>#ifdef STAN_OPENCL #include <stan/math/prim/mat/fun/typedefs.hpp> #include <stan/math/opencl/copy.hpp> #include <stan/math/opencl/add.hpp> #include <gtest/gtest.h> #include <algorithm> TEST(MathMatrixGPU, add_v_exception_pass) { stan::math::vector_d d1, d2; d1.resize(3); d2.resize(3); stan::math::matrix_cl d11(d1); stan::math::matrix_cl d22(d2); stan::math::matrix_cl d33(3, 1); EXPECT_NO_THROW(d33 = d11 + d22); } TEST(MathMatrixGPU, add_v_exception_pass_zero) { stan::math::vector_d d1, d2; d1.resize(0); d2.resize(0); stan::math::matrix_cl d11(d1); stan::math::matrix_cl d22(d2); stan::math::matrix_cl d33(0, 1); EXPECT_NO_THROW(d33 = d11 + d22); } TEST(MathMatrixGPU, add_v_exception_pass_invalid_arg) { stan::math::row_vector_d d1, d2; d1.resize(2); d2.resize(3); stan::math::matrix_cl d11(d1); stan::math::matrix_cl d22(d2); stan::math::matrix_cl d33(3, 0); EXPECT_THROW(d33 = d11 + d22, std::invalid_argument); } TEST(MathMatrixGPU, add_rv_exception_pass) { stan::math::row_vector_d d1, d2; d1.resize(3); d2.resize(3); stan::math::matrix_cl d11(d1); stan::math::matrix_cl d22(d2); stan::math::matrix_cl d33(1, 3); EXPECT_NO_THROW(d33 = d11 + d22); } TEST(MathMatrixGPU, add_rv_exception_pass_zero) { stan::math::row_vector_d d1, d2; d1.resize(0); d2.resize(0); stan::math::matrix_cl d11(d1); stan::math::matrix_cl d22(d2); stan::math::matrix_cl d33(1, 0); EXPECT_NO_THROW(d33 = d11 + d22); } TEST(MathMatrixGPU, add_rv_exception_fail_invalid_arg) { stan::math::row_vector_d d1, d2; d1.resize(2); d2.resize(3); stan::math::matrix_cl d11(d1); stan::math::matrix_cl d22(d2); stan::math::matrix_cl d33(3, 1); EXPECT_THROW(d33 = d11 + d22, std::invalid_argument); } TEST(MathMatrixGPU, add_m_exception_pass_simple) { stan::math::matrix_d d1, d2; d1.resize(2, 3); d2.resize(2, 3); stan::math::matrix_cl d11(d1); stan::math::matrix_cl d22(d2); stan::math::matrix_cl d33(2, 3); EXPECT_NO_THROW(d33 = d11 + d22); } TEST(MathMatrixGPU, add_m_exception_pass_zero) { stan::math::matrix_d d1, d2; d1.resize(0, 0); d2.resize(0, 0); stan::math::matrix_cl d11(d1); stan::math::matrix_cl d22(d2); stan::math::matrix_cl d33(0, 0); EXPECT_NO_THROW(d33 = d11 + d22); } TEST(MathMatrixGPU, add_m_exception_fail_invalid_arg) { stan::math::matrix_d d1, d2; d1.resize(2, 3); d2.resize(3, 3); stan::math::matrix_cl d11(d1); stan::math::matrix_cl d22(d2); stan::math::matrix_cl d33(2, 3); EXPECT_THROW(d33 = d11 + d22, std::invalid_argument); } TEST(MathMatrixGPU, add_non_matching_sizes_exception) { stan::math::vector_d v1(2); v1 << 1, 2; stan::math::vector_d v2(3); v2 << 10, 100, 1000; stan::math::row_vector_d rv1(2); rv1 << 1, 2; stan::math::row_vector_d rv2(3); rv2 << 10, 100, 1000; stan::math::matrix_d m1(2, 3); m1 << 1, 2, 3, 4, 5, 6; stan::math::matrix_d m2(3, 2); m2 << 10, 100, 1000, 0, -10, -12; using stan::math::add; using stan::math::matrix_cl; matrix_cl v11(v1); matrix_cl v22(v2); matrix_cl v33(v1); matrix_cl rv11(rv1); matrix_cl rv22(rv2); matrix_cl rv33(rv1); matrix_cl m11(m1); matrix_cl m22(m2); matrix_cl m33(m1); EXPECT_THROW(v33 = v11 + v22, std::invalid_argument); EXPECT_THROW(rv33 = rv11 + rv22, std::invalid_argument); EXPECT_THROW(m33 = m11 + m22, std::invalid_argument); } TEST(MathMatrixGPU, add_value_check) { stan::math::vector_d v1(3); v1 << 1, 2, 3; stan::math::vector_d v2(3); v2 << 10, 100, 1000; stan::math::vector_d v3(3); stan::math::row_vector_d rv1(3); rv1 << 1, 2, 3; stan::math::row_vector_d rv2(3); rv2 << 10, 100, 1000; stan::math::row_vector_d rv3(3); stan::math::matrix_d m1(3, 3); m1 << 1, 2, 3, 4, 5, 6, 7, 8, 9; stan::math::matrix_d m2(3, 3); m2 << 10, 100, 1000, 0, -10, -12, 2, 4, 8; stan::math::matrix_d m3(3, 3); using stan::math::add; using stan::math::matrix_cl; matrix_cl v11(v1); matrix_cl v22(v2); matrix_cl v33(3, 1); matrix_cl rv11(rv1); matrix_cl rv22(rv2); matrix_cl rv33(1, 3); matrix_cl m11(m1); matrix_cl m22(m2); matrix_cl m33(3, 3); EXPECT_NO_THROW(v33 = v11 + v22); EXPECT_NO_THROW(rv33 = rv11 + rv22); EXPECT_NO_THROW(m33 = m11 + m22); stan::math::copy(v3, v33); EXPECT_EQ(11, v3(0)); EXPECT_EQ(102, v3(1)); EXPECT_EQ(1003, v3(2)); stan::math::copy(rv3, rv33); EXPECT_EQ(11, rv3(0)); EXPECT_EQ(102, rv3(1)); EXPECT_EQ(1003, rv3(2)); stan::math::copy(m3, m33); EXPECT_EQ(11, m3(0, 0)); EXPECT_EQ(102, m3(0, 1)); EXPECT_EQ(1003, m3(0, 2)); EXPECT_EQ(4, m3(1, 0)); EXPECT_EQ(-5, m3(1, 1)); EXPECT_EQ(-6, m3(1, 2)); EXPECT_EQ(9, m3(2, 0)); EXPECT_EQ(12, m3(2, 1)); EXPECT_EQ(17, m3(2, 2)); } TEST(MathMatrixGPU, add_batch) { // used to represent 5 matrices of size 10x10 const int batch_size = 11; const int size = 13; stan::math::matrix_d a(size, size * batch_size); stan::math::matrix_d a_res(size, size); for (int k = 0; k < batch_size; k++) { for (int i = 0; i < size; i++) for (int j = 0; j < size; j++) { a(i, k * size + j) = k; } } stan::math::matrix_cl a_cl(a); stan::math::matrix_cl a_cl_res(size, size); stan::math::opencl_kernels::add_batch(cl::NDRange(size, size), a_cl_res, a_cl, size, size, batch_size); copy(a_res, a_cl_res); for (int k = 0; k < batch_size; k++) { for (int i = 0; i < size; i++) for (int j = 0; j < size; j++) { a(i, j) += a(i, k * size + j); } } for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { EXPECT_EQ(a(i, j), a_res(i, j)); } } } #endif <|endoftext|>
<commit_before>// This file is part of the dune-pymor project: // https://github.com/pyMor/dune-pymor // Copyright Holders: Felix Albrecht, Stephan Rave // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_PYMOR_OPERATORS_AFFINE_HH #define DUNE_PYMOR_OPERATORS_AFFINE_HH #include <dune/pymor/common/exceptions.hh> #include <dune/pymor/parameters/base.hh> #include <dune/pymor/parameters/functional.hh> #include "interfaces.hh" namespace Dune { namespace Pymor { class AffinelyDecomposedOperator : public OperatorInterface { public: AffinelyDecomposedOperator(const ParameterType& tt = ParameterType()) : OperatorInterface(tt) , linear_(true) , size_(0) , hasAffinePart_(false) , dim_source_(0) , dim_range_(0) , type_source_("") , type_range_("") {} ~AffinelyDecomposedOperator() { if (hasAffinePart_) delete affinePart_; for (auto& element : components_) delete element; for (auto& element : coefficients_) delete element; } /** * \attention This class takes ownership of aff! */ void register_component(const OperatorInterface* aff) throw (Exception::this_does_not_make_any_sense, Exception::sizes_do_not_match, Exception::types_are_not_compatible) { if (hasAffinePart_) DUNE_PYMOR_THROW(Exception::this_does_not_make_any_sense, "do not call register_component(affinePart) if hasAffinePart() == true!"); if (aff->parametric()) DUNE_PYMOR_THROW(Exception::this_does_not_make_any_sense, "the affinePart must not be parametric!"); if (size_ == 0) { dim_source_ = aff->dim_source(); dim_range_ = aff->dim_range(); type_source_ = aff->type_source(); type_range_ = aff->type_range(); linear_ = aff->linear(); } else { if (aff->dim_source() != dim_source_) DUNE_PYMOR_THROW(Exception::sizes_do_not_match, "the dim_source of aff (" << aff->dim_source() << ") does not match the dim_source of this (" << dim_source_ << ")!"); if (aff->dim_range() != dim_range_) DUNE_PYMOR_THROW(Exception::sizes_do_not_match, "the dim_range of aff (" << aff->dim_range() << ") does not match the dim_range of this (" << dim_range_ << ")!"); if (aff->type_source() != type_source_) DUNE_PYMOR_THROW(Exception::types_are_not_compatible, "the type_source of aff (" << aff->type_source() << ") does not match the type_source of this (" << type_source_ << ")!"); if (aff->type_range() != type_range_) DUNE_PYMOR_THROW(Exception::types_are_not_compatible, "the type_range of aff (" << aff->type_range() << ") does not match the type_range of this (" << type_range_ << ")!"); if (!aff->linear() != linear_) linear_ = false; } affinePart_ = aff; hasAffinePart_ = true; } // ... register_component(...) /** * \attention This class takes ownership of comp and coeff! */ void register_component(const OperatorInterface* comp, const ParameterFunctional* coeff) { if (comp->parametric()) DUNE_PYMOR_THROW(Exception::this_does_not_make_any_sense, "a component must not be parametric!"); if (size_ == 0 && !hasAffinePart_) { dim_source_ = comp->dim_source(); dim_range_ = comp->dim_range(); type_source_ = comp->type_source(); type_range_ = comp->type_range(); linear_ = comp->linear(); } else { if (comp->dim_source() != dim_source_) DUNE_PYMOR_THROW(Exception::sizes_do_not_match, "the dim_source of comp (" << comp->dim_source() << ") does not match the dim_source of this (" << dim_source_ << ")!"); if (comp->dim_range() != dim_range_) DUNE_PYMOR_THROW(Exception::sizes_do_not_match, "the dim_range of comp (" << comp->dim_range() << ") does not match the dim_range of this (" << dim_range_ << ")!"); if (comp->type_source() != type_source_) DUNE_PYMOR_THROW(Exception::types_are_not_compatible, "the type_source of comp (" << comp->type_source() << ") does not match the type_source of this (" << type_source_ << ")!"); if (comp->type_range() != type_range_) DUNE_PYMOR_THROW(Exception::types_are_not_compatible, "the type_range of comp (" << comp->type_range() << ") does not match the type_range of this (" << type_range_ << ")!"); } if (!comp->linear() != linear_) linear_ = false; if (coeff->parameter_type() != Parametric::parameter_type()) DUNE_PYMOR_THROW(Exception::wrong_parameter_type, "a different parameter type for coeff (" << coeff->parameter_type() << ") and this (" << Parametric::parameter_type() << ") is not yet supported!"); components_.push_back(comp); coefficients_.push_back(coeff); ++size_; } // ... register_component(..., ...) unsigned int size() const { return size_; } /** * \attention The ownership of the component remains with this class! */ OperatorInterface* component(const int ii) throw (Exception::requirements_not_met, Exception::index_out_of_range) { if (size() == 0) DUNE_PYMOR_THROW(Exception::requirements_not_met, "do not call component(ii) if size() == 0!"); if (ii < 0 || ii >= size()) DUNE_PYMOR_THROW(Exception::index_out_of_range, "the condition 0 < ii < size() is not fulfilled for ii = " << ii << "and size() = " << size() << "!"); return components_[ii]; } /** * \attention The ownership of the component remains with this class! */ const OperatorInterface* component(const int ii) const throw (Exception::requirements_not_met, Exception::index_out_of_range) { if (size() == 0) DUNE_PYMOR_THROW(Exception::requirements_not_met, "do not call component(ii) if size() == 0!"); if (ii < 0 || ii >= size()) DUNE_PYMOR_THROW(Exception::index_out_of_range, "the condition 0 < ii < size() is not fulfilled for ii = " << ii << "and size() = " << size() << "!"); return components_[ii]; } /** * \attention The ownership of the coefficient remains with this class! */ const ParameterFunctional* coefficient(const int ii) const throw (Exception::requirements_not_met, Exception::index_out_of_range) { if (size() == 0) DUNE_PYMOR_THROW(Exception::requirements_not_met, "do not call coefficient(ii) if size() == 0!"); if (ii < 0 || ii >= size()) DUNE_PYMOR_THROW(Exception::index_out_of_range, "the condition 0 < ii < size() is not fulfilled for ii = " << ii << "and size() = " << size() << "!"); return coefficient[ii]; } bool hasAffinePart() const { return hasAffinePart_; } /** * \attention The ownership of the affinePart remains with this class! */ OperatorInterface* affinePart() throw(Exception::requirements_not_met) { if (!hasAffinePart()) DUNE_PYMOR_THROW(Exception::requirements_not_met, "do not call affinePart() if hasAffinePart() == false!"); return affinePart_; } /** * \attention The ownership of affinePart() remains in this class! */ const OperatorInterface* affinePart(const int ii) const { if (!hasAffinePart()) DUNE_PYMOR_THROW(Exception::requirements_not_met, "do not call affinePart() if hasAffinePart() == false!"); return affinePart_; } virtual bool linear() const { return linear_; } virtual unsigned int dim_source() const { return dim_source_; } virtual unsigned int dim_range() const { return dim_range_; } virtual std::string type_source() const { return type_source_; } virtual std::string type_range() const { return type_range_; } virtual void apply(const LA::VectorInterface* source, LA::VectorInterface* range, const Parameter mu = Parameter()) const throw (Exception::types_are_not_compatible, Exception::you_have_to_implement_this, Exception::sizes_do_not_match, Exception::wrong_parameter_type, Exception::requirements_not_met) { if (source->dim() != dim_source()) DUNE_PYMOR_THROW(Exception::sizes_do_not_match, "the dim of source (" << source->dim() << ") does not match the dim of this (" << dim_source() << ")!"); if (range->dim() != dim_range()) DUNE_PYMOR_THROW(Exception::sizes_do_not_match, "the dim of range (" << range->dim() << ") does not match the dim of this (" << dim_range() << ")!"); if (mu.type() != Parametric::parameter_type()) DUNE_PYMOR_THROW(Exception::wrong_parameter_type, "the type of mu (" << mu.report() << "does not match the parameter_type of this (" << Parametric::parameter_type() << ")!"); if (size() == 0 && !hasAffinePart_) DUNE_THROW(Exception::requirements_not_met, "do not call apply() if size() == 0 and hasAffinePart() == false!"); if (hasAffinePart_) { affinePart_->apply(source, range); if (size_ > 0) { LA::VectorInterface* tmp = LA::createVector(range->type()); assert(components_.size() == size_ && "This should not happen!"); assert(coefficients_.size() == size_ && "This should not happen!"); for (size_t ii = 0; ii < size_; ++ii) { components_[ii]->apply(source, tmp); tmp->scal(coefficients_[ii]->evaluate(mu)); range->iadd(tmp); } } } else { assert(components_.size() == size_ && "This should not happen!"); assert(coefficients_.size() == size_ && "This should not happen!"); components_[0]->apply(source, range); range->scal(coefficients_[0]->evaluate()); if (size_ > 1) { LA::VectorInterface* tmp = LA::createVector(range->type()); for (size_t ii = 1; ii < size_; ++ii) { components_[ii]->apply(source, tmp); tmp->scal(coefficients_[ii]->evaluate(mu)); range->iadd(tmp); } } } } // void apply(...) private: bool linear_; unsigned int size_; bool hasAffinePart_; unsigned int dim_source_; unsigned int dim_range_; std::string type_source_; std::string type_range_; std::vector< const OperatorInterface* > components_; std::vector< const ParameterFunctional* > coefficients_; OperatorInterface* affinePart_; }; // class AffinelyDecomposedOperator } // namespace Pymor } // namespace Dune #endif // DUNE_PYMOR_OPERATORS_AFFINE_HH <commit_msg>[operators.affine] renamed AffinelyDecomposedOperator -> Operators::AffinelyDecomposed<commit_after>// This file is part of the dune-pymor project: // https://github.com/pyMor/dune-pymor // Copyright Holders: Felix Albrecht, Stephan Rave // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_PYMOR_OPERATORS_AFFINE_HH #define DUNE_PYMOR_OPERATORS_AFFINE_HH #include <dune/pymor/common/exceptions.hh> #include <dune/pymor/parameters/base.hh> #include <dune/pymor/parameters/functional.hh> #include "interfaces.hh" namespace Dune { namespace Pymor { namespace Operators { class AffinelyDecomposed : public OperatorInterface { public: AffinelyDecomposed(const ParameterType& tt = ParameterType()) : OperatorInterface(tt) , linear_(true) , size_(0) , hasAffinePart_(false) , dim_source_(0) , dim_range_(0) , type_source_("") , type_range_("") {} AffinelyDecomposed(OperatorInterface* aff, const ParameterType& tt = ParameterType()) throw (Exception::requirements_not_met) : OperatorInterface(tt) , linear_(aff->linear()) , size_(0) , hasAffinePart_(true) , dim_source_(aff->dim_source()) , dim_range_(aff->dim_range()) , type_source_(aff->type_source()) , type_range_(aff->type_range()) , affinePart_(aff) { if (affinePart_->parametric()) DUNE_PYMOR_THROW(Exception::requirements_not_met, "the affinePart must not be parametric!"); } virtual ~AffinelyDecomposed() { if (hasAffinePart_) delete affinePart_; for (auto& element : components_) delete element; for (auto& element : coefficients_) delete element; } /** * \attention This class takes ownership of aff! */ virtual void register_component(OperatorInterface* aff) throw (Exception::this_does_not_make_any_sense, Exception::sizes_do_not_match, Exception::types_are_not_compatible) { if (hasAffinePart_) DUNE_PYMOR_THROW(Exception::this_does_not_make_any_sense, "do not call register_component(affinePart) if hasAffinePart() == true!"); if (aff->parametric()) DUNE_PYMOR_THROW(Exception::this_does_not_make_any_sense, "the affinePart must not be parametric!"); if (size_ == 0) { dim_source_ = aff->dim_source(); dim_range_ = aff->dim_range(); type_source_ = aff->type_source(); type_range_ = aff->type_range(); linear_ = aff->linear(); } else { if (aff->dim_source() != dim_source_) DUNE_PYMOR_THROW(Exception::sizes_do_not_match, "the dim_source of aff (" << aff->dim_source() << ") does not match the dim_source of this (" << dim_source_ << ")!"); if (aff->dim_range() != dim_range_) DUNE_PYMOR_THROW(Exception::sizes_do_not_match, "the dim_range of aff (" << aff->dim_range() << ") does not match the dim_range of this (" << dim_range_ << ")!"); if (aff->type_source() != type_source_) DUNE_PYMOR_THROW(Exception::types_are_not_compatible, "the type_source of aff (" << aff->type_source() << ") does not match the type_source of this (" << type_source_ << ")!"); if (aff->type_range() != type_range_) DUNE_PYMOR_THROW(Exception::types_are_not_compatible, "the type_range of aff (" << aff->type_range() << ") does not match the type_range of this (" << type_range_ << ")!"); if (!aff->linear() != linear_) linear_ = false; } affinePart_ = aff; hasAffinePart_ = true; } // ... register_component(...) /** * \attention This class takes ownership of comp and coeff! */ virtual void register_component(OperatorInterface* comp, const ParameterFunctional* coeff) { if (comp->parametric()) DUNE_PYMOR_THROW(Exception::this_does_not_make_any_sense, "a component must not be parametric!"); if (size_ == 0 && !hasAffinePart_) { dim_source_ = comp->dim_source(); dim_range_ = comp->dim_range(); type_source_ = comp->type_source(); type_range_ = comp->type_range(); linear_ = comp->linear(); } else { if (comp->dim_source() != dim_source_) DUNE_PYMOR_THROW(Exception::sizes_do_not_match, "the dim_source of comp (" << comp->dim_source() << ") does not match the dim_source of this (" << dim_source_ << ")!"); if (comp->dim_range() != dim_range_) DUNE_PYMOR_THROW(Exception::sizes_do_not_match, "the dim_range of comp (" << comp->dim_range() << ") does not match the dim_range of this (" << dim_range_ << ")!"); if (comp->type_source() != type_source_) DUNE_PYMOR_THROW(Exception::types_are_not_compatible, "the type_source of comp (" << comp->type_source() << ") does not match the type_source of this (" << type_source_ << ")!"); if (comp->type_range() != type_range_) DUNE_PYMOR_THROW(Exception::types_are_not_compatible, "the type_range of comp (" << comp->type_range() << ") does not match the type_range of this (" << type_range_ << ")!"); } if (!comp->linear() != linear_) linear_ = false; if (coeff->parameter_type() != Parametric::parameter_type()) DUNE_PYMOR_THROW(Exception::wrong_parameter_type, "a different parameter types for coeff (" << coeff->parameter_type() << ") and this (" << Parametric::parameter_type() << ") is not yet supported!"); components_.push_back(comp); coefficients_.push_back(coeff); ++size_; } // ... register_component(..., ...) virtual unsigned int size() const { return size_; } /** * \attention The ownership of the component remains with this class! */ virtual OperatorInterface* component(const int ii) throw (Exception::requirements_not_met, Exception::index_out_of_range) { if (size() == 0) DUNE_PYMOR_THROW(Exception::requirements_not_met, "do not call component(ii) if size() == 0!"); if (ii < 0 || ii >= size()) DUNE_PYMOR_THROW(Exception::index_out_of_range, "the condition 0 < ii < size() is not fulfilled for ii = " << ii << "and size() = " << size() << "!"); return components_[ii]; } /** * \attention The ownership of the component remains with this class! */ virtual const OperatorInterface* component(const int ii) const throw (Exception::requirements_not_met, Exception::index_out_of_range) { if (size() == 0) DUNE_PYMOR_THROW(Exception::requirements_not_met, "do not call component(ii) if size() == 0!"); if (ii < 0 || ii >= size()) DUNE_PYMOR_THROW(Exception::index_out_of_range, "the condition 0 < ii < size() is not fulfilled for ii = " << ii << "and size() = " << size() << "!"); return components_[ii]; } /** * \attention The ownership of the coefficient remains with this class! */ virtual const ParameterFunctional* coefficient(const int ii) const throw (Exception::requirements_not_met, Exception::index_out_of_range) { if (size() == 0) DUNE_PYMOR_THROW(Exception::requirements_not_met, "do not call coefficient(ii) if size() == 0!"); if (ii < 0 || ii >= size()) DUNE_PYMOR_THROW(Exception::index_out_of_range, "the condition 0 < ii < size() is not fulfilled for ii = " << ii << "and size() = " << size() << "!"); return coefficients_[ii]; } virtual bool hasAffinePart() const { return hasAffinePart_; } /** * \attention The ownership of the affinePart remains with this class! */ virtual OperatorInterface* affinePart() throw(Exception::requirements_not_met) { if (!hasAffinePart()) DUNE_PYMOR_THROW(Exception::requirements_not_met, "do not call affinePart() if hasAffinePart() == false!"); return affinePart_; } /** * \attention The ownership of affinePart() remains in this class! */ virtual const OperatorInterface* affinePart() const throw(Exception::requirements_not_met) { if (!hasAffinePart()) DUNE_PYMOR_THROW(Exception::requirements_not_met, "do not call affinePart() if hasAffinePart() == false!"); return affinePart_; } virtual bool linear() const { return linear_; } virtual unsigned int dim_source() const { return dim_source_; } virtual unsigned int dim_range() const { return dim_range_; } virtual std::string type_source() const { return type_source_; } virtual std::string type_range() const { return type_range_; } virtual void apply(const LA::VectorInterface* source, LA::VectorInterface* range, const Parameter mu = Parameter()) const throw (Exception::types_are_not_compatible, Exception::you_have_to_implement_this, Exception::sizes_do_not_match, Exception::wrong_parameter_type, Exception::requirements_not_met) { if (source->dim() != dim_source()) DUNE_PYMOR_THROW(Exception::sizes_do_not_match, "the dim of source (" << source->dim() << ") does not match the dim of this (" << dim_source() << ")!"); if (range->dim() != dim_range()) DUNE_PYMOR_THROW(Exception::sizes_do_not_match, "the dim of range (" << range->dim() << ") does not match the dim of this (" << dim_range() << ")!"); if (mu.type() != Parametric::parameter_type()) DUNE_PYMOR_THROW(Exception::wrong_parameter_type, "the type of mu (" << mu.type() << "does not match the parameter_type of this (" << Parametric::parameter_type() << ")!"); if (size() == 0 && !hasAffinePart_) DUNE_PYMOR_THROW(Exception::requirements_not_met, "do not call apply() if size() == 0 and hasAffinePart() == false!"); if (hasAffinePart_) { affinePart_->apply(source, range); if (size_ > 0) { LA::VectorInterface* tmp = LA::createVector(range->type(), dim_range()); assert(components_.size() == size_ && "This should not happen!"); assert(coefficients_.size() == size_ && "This should not happen!"); for (size_t ii = 0; ii < size_; ++ii) { components_[ii]->apply(source, tmp); tmp->scal(coefficients_[ii]->evaluate(mu)); range->iadd(tmp); } } } else { assert(components_.size() == size_ && "This should not happen!"); assert(coefficients_.size() == size_ && "This should not happen!"); components_[0]->apply(source, range); range->scal(coefficients_[0]->evaluate(mu)); if (size_ > 1) { LA::VectorInterface* tmp = LA::createVector(range->type(), dim_range()); for (size_t ii = 1; ii < size_; ++ii) { components_[ii]->apply(source, tmp); tmp->scal(coefficients_[ii]->evaluate(mu)); range->iadd(tmp); } } } } // void apply(...) private: bool linear_; unsigned int size_; bool hasAffinePart_; unsigned int dim_source_; unsigned int dim_range_; std::string type_source_; std::string type_range_; std::vector< OperatorInterface* > components_; std::vector< const ParameterFunctional* > coefficients_; OperatorInterface* affinePart_; }; // class AffinelyDecomposed } // namespace Operators } // namespace Pymor } // namespace Dune #endif // DUNE_PYMOR_OPERATORS_AFFINE_HH <|endoftext|>
<commit_before>#include "GLIcoSphere.h" #include "GL/glew.h" #include <map> #include <stdint.h> GLIcoSphere::GLIcoSphere( const int entityID /*= 0*/ ) : IComponent(entityID) { } unsigned int GLIcoSphere::VertBuf() const { return this->vertBuf; } void GLIcoSphere::VertBuf(unsigned int vb) { this->vertBuf = vb; } unsigned int GLIcoSphere::ColBuf() const { return this->colBuf; } void GLIcoSphere::ColBuf(unsigned int cb) { this->colBuf = cb; } unsigned int GLIcoSphere::Vao() const { return this->vao; } void GLIcoSphere::Vao(unsigned int v) { this->vao = v; } unsigned int GLIcoSphere::ElemBuf() const { return this->elemBuf; } void GLIcoSphere::ElemBuf(unsigned int eb) { this->elemBuf = eb; } GLIcoSphere* GLIcoSphere::Factory(int entityID) { GLIcoSphere* sphere = new GLIcoSphere(entityID); // We must create a vao and then store it in our GLIcoSphere. GLuint vaoID; glGenVertexArrays(1, &vaoID); glBindVertexArray(vaoID); // Create the verts to begin our deforming at. double t = (1.0 + glm::sqrt(5.0)) / 2.0; glm::vec2 coordPair = glm::normalize(glm::vec2(1,t)); sphere->verts.push_back(vertex(-coordPair.r, coordPair.g, 0)); sphere->verts.push_back(vertex(coordPair.r, coordPair.g, 0)); sphere->verts.push_back(vertex(-coordPair.r, -coordPair.g, 0)); sphere->verts.push_back(vertex(coordPair.r, -coordPair.g, 0)); sphere->verts.push_back(vertex(0, -coordPair.r, coordPair.g)); sphere->verts.push_back(vertex(0, coordPair.r, coordPair.g)); sphere->verts.push_back(vertex(0, -coordPair.r, -coordPair.g)); sphere->verts.push_back(vertex(0, coordPair.r, -coordPair.g)); sphere->verts.push_back(vertex(coordPair.g, 0, -coordPair.r)); sphere->verts.push_back(vertex(coordPair.g, 0, coordPair.r)); sphere->verts.push_back(vertex(-coordPair.g, 0, -coordPair.r)); sphere->verts.push_back(vertex(-coordPair.g, 0, coordPair.r)); std::vector<face> faceLevelZero; faceLevelZero.push_back(face(0,11,5)); faceLevelZero.push_back(face(0,5,1)); faceLevelZero.push_back(face(0,1,7)); faceLevelZero.push_back(face(0,7,10)); faceLevelZero.push_back(face(0,10,11)); faceLevelZero.push_back(face(1,5,9)); faceLevelZero.push_back(face(5,11,4)); faceLevelZero.push_back(face(11,10,2)); faceLevelZero.push_back(face(10,7,6)); faceLevelZero.push_back(face(7,1,8)); faceLevelZero.push_back(face(3,9,4)); faceLevelZero.push_back(face(3,4,2)); faceLevelZero.push_back(face(3,2,6)); faceLevelZero.push_back(face(3,6,8)); faceLevelZero.push_back(face(3,8,9)); faceLevelZero.push_back(face(4,9,5)); faceLevelZero.push_back(face(2,4,11)); faceLevelZero.push_back(face(6,2,10)); faceLevelZero.push_back(face(8,6,7)); faceLevelZero.push_back(face(9,8,1)); sphere->Refine(sphere->verts, faceLevelZero, 2); sphere->faces = faceLevelZero; GLuint vertbuf; glGenBuffers(1, &vertbuf); glBindBuffer(GL_ARRAY_BUFFER, vertbuf); glBufferData(GL_ARRAY_BUFFER, sizeof(vertex) * sphere->verts.size(), &sphere->verts.front(), GL_STATIC_DRAW); GLint posLocation = glGetAttribLocation(GLIcoSphere::shader.GetProgram(), "in_Position"); glVertexAttribPointer(posLocation, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(posLocation); GLuint elembuf; glGenBuffers(1, &elembuf); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elembuf); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(face) * sphere->faces.size(), &sphere->faces.front(), GL_STATIC_DRAW); static const GLfloat col[1]; GLuint colorbuf; glGenBuffers(1, &colorbuf); glBindBuffer(GL_ARRAY_BUFFER, colorbuf); glBufferData(GL_ARRAY_BUFFER, sizeof(col), col, GL_STATIC_DRAW); GLint colLocation = glGetAttribLocation(GLIcoSphere::shader.GetProgram(), "in_Color"); glVertexAttribPointer(colLocation, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(colLocation); glBindVertexArray(0); sphere->Vao(vaoID); sphere->VertBuf(vertbuf); sphere->ColBuf(colorbuf); sphere->ElemBuf(elembuf); return sphere; } void GLIcoSphere::LoadShader() { GLIcoSphere::shader.LoadFromFile(GL_VERTEX_SHADER, "..\\..\\shaders\\vert.shade"); GLIcoSphere::shader.LoadFromFile(GL_FRAGMENT_SHADER, "..\\..\\shaders\\frag.shade"); GLIcoSphere::shader.CreateAndLinkProgram(); } glm::vec3 GetMidPoint(vertex v1, vertex v2) { return glm::normalize(glm::vec3((v1.x + v2.x) / 2.0, (v1.y + v2.y) / 2.0, (v1.z + v2.z) / 2.0)); } void GLIcoSphere::Refine(std::vector<vertex> &verts, std::vector<face> &faces, int level) { std::map<int64_t, int> cache; // refine faces std::vector<face> newFaces = faces; for (int i = 0; i < level; ++i) { std::vector<face> tempFaces; for (auto faceitr = newFaces.begin(); faceitr != newFaces.end(); ++faceitr) { int a,b,c; { int v1 = (*faceitr).v1; int v2 = (*faceitr).v2; // first check if we have it already bool firstIsSmaller = v1 < v2; int64_t smallerIndex = firstIsSmaller ? v1 : v2; int64_t greaterIndex = firstIsSmaller ? v2 : v1; int64_t key = (smallerIndex << 32) + greaterIndex; if (cache.find(key) != cache.end()) { a = cache[key]; } else { glm::vec3 middle = GetMidPoint(this->verts[v1], this->verts[v2]); verts.push_back(vertex(middle.x, middle.y, middle.z)); a = cache[key] = this->verts.size() - 1; } } { int v1 = (*faceitr).v2; int v2 = (*faceitr).v3; // first check if we have it already bool firstIsSmaller = v1 < v2; int64_t smallerIndex = firstIsSmaller ? v1 : v2; int64_t greaterIndex = firstIsSmaller ? v2 : v1; int64_t key = (smallerIndex << 32) + greaterIndex; if (cache.find(key) != cache.end()) { b = cache[key]; } else { glm::vec3 middle = GetMidPoint(this->verts[v1], this->verts[v2]); verts.push_back(vertex(middle.x, middle.y, middle.z)); b = cache[key] = this->verts.size() - 1; } } { int v1 = (*faceitr).v3; int v2 = (*faceitr).v1; // first check if we have it already bool firstIsSmaller = v1 < v2; int64_t smallerIndex = firstIsSmaller ? v1 : v2; int64_t greaterIndex = firstIsSmaller ? v2 : v1; int64_t key = (smallerIndex << 32) + greaterIndex; if (cache.find(key) != cache.end()) { c = cache[key]; } else { glm::vec3 middle = GetMidPoint(this->verts[v1], this->verts[v2]); verts.push_back(vertex(middle.x, middle.y, middle.z)); c = cache[key] = this->verts.size() - 1; } } tempFaces.push_back(face((*faceitr).v1, a, c)); tempFaces.push_back(face((*faceitr).v2, b, a)); tempFaces.push_back(face((*faceitr).v3, c, b)); tempFaces.push_back(face(a, b, c)); } newFaces = tempFaces; } faces = newFaces; } GLSLShader GLIcoSphere::shader; <commit_msg>Fix color buffer issues in GLIcoSpehre<commit_after>#include "GLIcoSphere.h" #include "GL/glew.h" #include <map> #include <stdint.h> GLIcoSphere::GLIcoSphere( const int entityID /*= 0*/ ) : IComponent(entityID) { } unsigned int GLIcoSphere::VertBuf() const { return this->vertBuf; } void GLIcoSphere::VertBuf(unsigned int vb) { this->vertBuf = vb; } unsigned int GLIcoSphere::ColBuf() const { return this->colBuf; } void GLIcoSphere::ColBuf(unsigned int cb) { this->colBuf = cb; } unsigned int GLIcoSphere::Vao() const { return this->vao; } void GLIcoSphere::Vao(unsigned int v) { this->vao = v; } unsigned int GLIcoSphere::ElemBuf() const { return this->elemBuf; } void GLIcoSphere::ElemBuf(unsigned int eb) { this->elemBuf = eb; } GLIcoSphere* GLIcoSphere::Factory(int entityID) { GLIcoSphere* sphere = new GLIcoSphere(entityID); // We must create a vao and then store it in our GLIcoSphere. GLuint vaoID; glGenVertexArrays(1, &vaoID); glBindVertexArray(vaoID); // Create the verts to begin our deforming at. double t = (1.0 + glm::sqrt(5.0)) / 2.0; glm::vec2 coordPair = glm::normalize(glm::vec2(1,t)); sphere->verts.push_back(vertex(-coordPair.r, coordPair.g, 0)); sphere->verts.push_back(vertex(coordPair.r, coordPair.g, 0)); sphere->verts.push_back(vertex(-coordPair.r, -coordPair.g, 0)); sphere->verts.push_back(vertex(coordPair.r, -coordPair.g, 0)); sphere->verts.push_back(vertex(0, -coordPair.r, coordPair.g)); sphere->verts.push_back(vertex(0, coordPair.r, coordPair.g)); sphere->verts.push_back(vertex(0, -coordPair.r, -coordPair.g)); sphere->verts.push_back(vertex(0, coordPair.r, -coordPair.g)); sphere->verts.push_back(vertex(coordPair.g, 0, -coordPair.r)); sphere->verts.push_back(vertex(coordPair.g, 0, coordPair.r)); sphere->verts.push_back(vertex(-coordPair.g, 0, -coordPair.r)); sphere->verts.push_back(vertex(-coordPair.g, 0, coordPair.r)); std::vector<face> faceLevelZero; faceLevelZero.push_back(face(0,11,5)); faceLevelZero.push_back(face(0,5,1)); faceLevelZero.push_back(face(0,1,7)); faceLevelZero.push_back(face(0,7,10)); faceLevelZero.push_back(face(0,10,11)); faceLevelZero.push_back(face(1,5,9)); faceLevelZero.push_back(face(5,11,4)); faceLevelZero.push_back(face(11,10,2)); faceLevelZero.push_back(face(10,7,6)); faceLevelZero.push_back(face(7,1,8)); faceLevelZero.push_back(face(3,9,4)); faceLevelZero.push_back(face(3,4,2)); faceLevelZero.push_back(face(3,2,6)); faceLevelZero.push_back(face(3,6,8)); faceLevelZero.push_back(face(3,8,9)); faceLevelZero.push_back(face(4,9,5)); faceLevelZero.push_back(face(2,4,11)); faceLevelZero.push_back(face(6,2,10)); faceLevelZero.push_back(face(8,6,7)); faceLevelZero.push_back(face(9,8,1)); sphere->Refine(sphere->verts, faceLevelZero, 2); sphere->faces = faceLevelZero; GLuint vertbuf; glGenBuffers(1, &vertbuf); glBindBuffer(GL_ARRAY_BUFFER, vertbuf); glBufferData(GL_ARRAY_BUFFER, sizeof(vertex) * sphere->verts.size(), &sphere->verts.front(), GL_STATIC_DRAW); GLint posLocation = glGetAttribLocation(GLIcoSphere::shader.GetProgram(), "in_Position"); glVertexAttribPointer(posLocation, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(posLocation); GLuint elembuf; glGenBuffers(1, &elembuf); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elembuf); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(face) * sphere->faces.size(), &sphere->faces.front(), GL_STATIC_DRAW); /*static const GLfloat col[1]; GLuint colorbuf; glGenBuffers(1, &colorbuf); glBindBuffer(GL_ARRAY_BUFFER, colorbuf); glBufferData(GL_ARRAY_BUFFER, sizeof(col), col, GL_STATIC_DRAW); GLint colLocation = glGetAttribLocation(GLIcoSphere::shader.GetProgram(), "in_Color"); glVertexAttribPointer(colLocation, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(colLocation);*/ glBindVertexArray(0); sphere->Vao(vaoID); sphere->VertBuf(vertbuf); //sphere->ColBuf(colorbuf); sphere->ElemBuf(elembuf); return sphere; } void GLIcoSphere::LoadShader() { GLIcoSphere::shader.LoadFromFile(GL_VERTEX_SHADER, "..\\..\\shaders\\vert.shade"); GLIcoSphere::shader.LoadFromFile(GL_FRAGMENT_SHADER, "..\\..\\shaders\\frag.shade"); GLIcoSphere::shader.CreateAndLinkProgram(); } glm::vec3 GetMidPoint(vertex v1, vertex v2) { return glm::normalize(glm::vec3((v1.x + v2.x) / 2.0, (v1.y + v2.y) / 2.0, (v1.z + v2.z) / 2.0)); } void GLIcoSphere::Refine(std::vector<vertex> &verts, std::vector<face> &faces, int level) { std::map<int64_t, int> cache; // refine faces std::vector<face> newFaces = faces; for (int i = 0; i < level; ++i) { std::vector<face> tempFaces; for (auto faceitr = newFaces.begin(); faceitr != newFaces.end(); ++faceitr) { int a,b,c; { int v1 = (*faceitr).v1; int v2 = (*faceitr).v2; // first check if we have it already bool firstIsSmaller = v1 < v2; int64_t smallerIndex = firstIsSmaller ? v1 : v2; int64_t greaterIndex = firstIsSmaller ? v2 : v1; int64_t key = (smallerIndex << 32) + greaterIndex; if (cache.find(key) != cache.end()) { a = cache[key]; } else { glm::vec3 middle = GetMidPoint(this->verts[v1], this->verts[v2]); verts.push_back(vertex(middle.x, middle.y, middle.z)); a = cache[key] = this->verts.size() - 1; } } { int v1 = (*faceitr).v2; int v2 = (*faceitr).v3; // first check if we have it already bool firstIsSmaller = v1 < v2; int64_t smallerIndex = firstIsSmaller ? v1 : v2; int64_t greaterIndex = firstIsSmaller ? v2 : v1; int64_t key = (smallerIndex << 32) + greaterIndex; if (cache.find(key) != cache.end()) { b = cache[key]; } else { glm::vec3 middle = GetMidPoint(this->verts[v1], this->verts[v2]); verts.push_back(vertex(middle.x, middle.y, middle.z)); b = cache[key] = this->verts.size() - 1; } } { int v1 = (*faceitr).v3; int v2 = (*faceitr).v1; // first check if we have it already bool firstIsSmaller = v1 < v2; int64_t smallerIndex = firstIsSmaller ? v1 : v2; int64_t greaterIndex = firstIsSmaller ? v2 : v1; int64_t key = (smallerIndex << 32) + greaterIndex; if (cache.find(key) != cache.end()) { c = cache[key]; } else { glm::vec3 middle = GetMidPoint(this->verts[v1], this->verts[v2]); verts.push_back(vertex(middle.x, middle.y, middle.z)); c = cache[key] = this->verts.size() - 1; } } tempFaces.push_back(face((*faceitr).v1, a, c)); tempFaces.push_back(face((*faceitr).v2, b, a)); tempFaces.push_back(face((*faceitr).v3, c, b)); tempFaces.push_back(face(a, b, c)); } newFaces = tempFaces; } faces = newFaces; } GLSLShader GLIcoSphere::shader; <|endoftext|>
<commit_before>/* * ______ __ __ __ * /\ _ \ __ /\ \/\ \ /\ \__ * \ \ \L\ \ __ __ /\_\ \_\ \ \ \____ ___\ \ ,_\ ____ * \ \ __ \/\ \/\ \\/\ \ /'_` \ \ '__`\ / __`\ \ \/ /',__\ * \ \ \/\ \ \ \_/ |\ \ \/\ \L\ \ \ \L\ \/\ \L\ \ \ \_/\__, `\ * \ \_\ \_\ \___/ \ \_\ \___,_\ \_,__/\ \____/\ \__\/\____/ * \/_/\/_/\/__/ \/_/\/__,_ /\/___/ \/___/ \/__/\/___/ * @copyright Copyright 2017 Avidbots Corp. * @name laser.cpp * @brief Laser plugin * @author Chunshang Li * * Software License Agreement (BSD License) * * Copyright (c) 2017, Avidbots Corp. * 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 Avidbots Corp. 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 <flatland_plugins/laser.h> #include <flatland_server/collision_filter_registry.h> #include <flatland_server/exceptions.h> #include <flatland_server/model_plugin.h> #include <flatland_server/yaml_reader.h> #include <geometry_msgs/TransformStamped.h> #include <pluginlib/class_list_macros.h> #include <boost/algorithm/string/join.hpp> #include <cmath> #include <limits> using namespace flatland_server; namespace flatland_plugins { void Laser::OnInitialize(const YAML::Node &config) { float i; double b = cos(i); ParseParameters(config); update_timer_.SetRate(update_rate_); scan_publisher_ = nh_.advertise<sensor_msgs::LaserScan>(topic_, 1); // construct the body to laser transformation matrix once since it never // changes double c = cos(origin_.theta); double s = sin(origin_.theta); double x = origin_.x, y = origin_.y; m_body_to_laser_ << c, -s, x, s, c, y, 0, 0, 1; int num_laser_points = std::lround((max_angle_ - min_angle_) / increment_) + 1; // initialize size for the matrix storing the laser points m_laser_points_ = Eigen::MatrixXf(3, num_laser_points); m_world_laser_points_ = Eigen::MatrixXf(3, num_laser_points); v_zero_point_ << 0, 0, 1; // pre-calculate the laser points w.r.t to the laser frame, since this never // changes for (int i = 0; i < num_laser_points; i++) { float angle = min_angle_ + i * increment_; float x = range_ * cos(angle); float y = range_ * sin(angle); m_laser_points_(0, i) = x; m_laser_points_(1, i) = y; m_laser_points_(2, i) = 1; } // initialize constants in the laser scan message laser_scan_.angle_min = min_angle_; laser_scan_.angle_max = max_angle_; laser_scan_.angle_increment = increment_; laser_scan_.time_increment = 0; laser_scan_.scan_time = 0; laser_scan_.range_min = 0; laser_scan_.range_max = range_; laser_scan_.ranges.resize(num_laser_points); laser_scan_.intensities.resize(0); laser_scan_.header.seq = 0; laser_scan_.header.frame_id = tf::resolve(model_->GetNameSpace(), frame_id_); // Broadcast transform between the body and laser tf::Quaternion q; q.setRPY(0, 0, origin_.theta); static_tf_.header.frame_id = tf::resolve(model_->GetNameSpace(), body_->GetName()); static_tf_.child_frame_id = tf::resolve(model_->GetNameSpace(), frame_id_); static_tf_.transform.translation.x = origin_.x; static_tf_.transform.translation.y = origin_.y; static_tf_.transform.translation.z = 0; static_tf_.transform.rotation.x = q.x(); static_tf_.transform.rotation.y = q.y(); static_tf_.transform.rotation.z = q.z(); static_tf_.transform.rotation.w = q.w(); } void Laser::BeforePhysicsStep(const Timekeeper &timekeeper) { // keep the update rate if (!update_timer_.CheckUpdate(timekeeper)) { return; } // only compute and publish when the number of subscribers is not zero if (scan_publisher_.getNumSubscribers() > 0) { ComputeLaserRanges(); laser_scan_.header.stamp = ros::Time::now(); scan_publisher_.publish(laser_scan_); } static_tf_.header.stamp = ros::Time::now(); tf_broadcaster_.sendTransform(static_tf_); } void Laser::ComputeLaserRanges() { // get the transformation matrix from the world to the body, and get the // world to laser frame transformation matrix by multiplying the world to body // and body to laser const b2Transform &t = body_->GetPhysicsBody()->GetTransform(); m_world_to_body_ << t.q.c, -t.q.s, t.p.x, t.q.s, t.q.c, t.p.y, 0, 0, 1; m_world_to_laser_ = m_world_to_body_ * m_body_to_laser_; // Get the laser points in the world frame by multiplying the laser points in // the laser frame to the transformation matrix from world to laser frame m_world_laser_points_ = m_world_to_laser_ * m_laser_points_; // Get the (0, 0) point in the laser frame v_world_laser_origin_ = m_world_to_laser_ * v_zero_point_; // Conver to Box2D data types b2Vec2 laser_point; b2Vec2 laser_origin_point(v_world_laser_origin_(0), v_world_laser_origin_(1)); // loop through the laser points and call the Box2D world raycast for (int i = 0; i < laser_scan_.ranges.size(); ++i) { laser_point.x = m_world_laser_points_(0, i); laser_point.y = m_world_laser_points_(1, i); did_hit_ = false; model_->GetPhysicsWorld()->RayCast(this, laser_origin_point, laser_point); if (!did_hit_) { laser_scan_.ranges[i] = NAN; } else { laser_scan_.ranges[i] = fraction_ * range_; } } } float Laser::ReportFixture(b2Fixture *fixture, const b2Vec2 &point, const b2Vec2 &normal, float fraction) { // only register hit in the specified layers if (!(fixture->GetFilterData().categoryBits & layers_bits_)) { return -1.0f; // return -1 to ignore this hit } did_hit_ = true; fraction_ = fraction; return fraction; } void Laser::ParseParameters(const YAML::Node &config) { YamlReader reader(config); std::string body_name = reader.Get<std::string>("body"); topic_ = reader.Get<std::string>("topic", "scan"); frame_id_ = reader.Get<std::string>("frame", name_); update_rate_ = reader.Get<double>("update_rate", std::numeric_limits<double>::infinity()); origin_ = reader.GetPose("origin", Pose(0, 0, 0)); range_ = reader.Get<double>("range"); std::vector<std::string> layers = reader.GetList<std::string>("layers", {"all"}, -1, -1); YamlReader angle_reader = reader.Subnode("angle", YamlReader::MAP); min_angle_ = angle_reader.Get<double>("min"); max_angle_ = angle_reader.Get<double>("max"); increment_ = angle_reader.Get<double>("increment"); angle_reader.EnsureAccessedAllKeys(); reader.EnsureAccessedAllKeys(); if (max_angle_ < min_angle_) { throw YAMLException("Invalid \"angle\" params, must have max > min"); } body_ = model_->GetBody(body_name); if (!body_) { throw YAMLException("Cannot find body with name " + body_name); } std::vector<std::string> invalid_layers; layers_bits_ = model_->GetCfr()->GetCategoryBits(layers, &invalid_layers); if (!invalid_layers.empty()) { throw YAMLException("Cannot find layer(s): {" + boost::algorithm::join(invalid_layers, ",") + "}"); } ROS_DEBUG_NAMED("LaserPlugin", "Laser %s params: topic(%s) body(%s, %p) origin(%f,%f,%f) " "frame_id(%s) update_rate(%f) range(%f) angle_min(%f) " "angle_max(%f) angle_increment(%f) layers(0x%u {%s})", name_.c_str(), topic_.c_str(), body_name.c_str(), body_, origin_.x, origin_.y, origin_.theta, frame_id_.c_str(), update_rate_, range_, min_angle_, max_angle_, increment_, layers_bits_, boost::algorithm::join(layers, ",").c_str()); } }; PLUGINLIB_EXPORT_CLASS(flatland_plugins::Laser, flatland_server::ModelPlugin)<commit_msg>clang format<commit_after>/* * ______ __ __ __ * /\ _ \ __ /\ \/\ \ /\ \__ * \ \ \L\ \ __ __ /\_\ \_\ \ \ \____ ___\ \ ,_\ ____ * \ \ __ \/\ \/\ \\/\ \ /'_` \ \ '__`\ / __`\ \ \/ /',__\ * \ \ \/\ \ \ \_/ |\ \ \/\ \L\ \ \ \L\ \/\ \L\ \ \ \_/\__, `\ * \ \_\ \_\ \___/ \ \_\ \___,_\ \_,__/\ \____/\ \__\/\____/ * \/_/\/_/\/__/ \/_/\/__,_ /\/___/ \/___/ \/__/\/___/ * @copyright Copyright 2017 Avidbots Corp. * @name laser.cpp * @brief Laser plugin * @author Chunshang Li * * Software License Agreement (BSD License) * * Copyright (c) 2017, Avidbots Corp. * 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 Avidbots Corp. 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 <flatland_plugins/laser.h> #include <flatland_server/collision_filter_registry.h> #include <flatland_server/exceptions.h> #include <flatland_server/model_plugin.h> #include <flatland_server/yaml_reader.h> #include <geometry_msgs/TransformStamped.h> #include <pluginlib/class_list_macros.h> #include <boost/algorithm/string/join.hpp> #include <cmath> #include <limits> using namespace flatland_server; namespace flatland_plugins { void Laser::OnInitialize(const YAML::Node &config) { float i; double b = cos(i); ParseParameters(config); update_timer_.SetRate(update_rate_); scan_publisher_ = nh_.advertise<sensor_msgs::LaserScan>(topic_, 1); // construct the body to laser transformation matrix once since it never // changes double c = cos(origin_.theta); double s = sin(origin_.theta); double x = origin_.x, y = origin_.y; m_body_to_laser_ << c, -s, x, s, c, y, 0, 0, 1; int num_laser_points = std::lround((max_angle_ - min_angle_) / increment_) + 1; // initialize size for the matrix storing the laser points m_laser_points_ = Eigen::MatrixXf(3, num_laser_points); m_world_laser_points_ = Eigen::MatrixXf(3, num_laser_points); v_zero_point_ << 0, 0, 1; // pre-calculate the laser points w.r.t to the laser frame, since this never // changes for (int i = 0; i < num_laser_points; i++) { float angle = min_angle_ + i * increment_; float x = range_ * cos(angle); float y = range_ * sin(angle); m_laser_points_(0, i) = x; m_laser_points_(1, i) = y; m_laser_points_(2, i) = 1; } // initialize constants in the laser scan message laser_scan_.angle_min = min_angle_; laser_scan_.angle_max = max_angle_; laser_scan_.angle_increment = increment_; laser_scan_.time_increment = 0; laser_scan_.scan_time = 0; laser_scan_.range_min = 0; laser_scan_.range_max = range_; laser_scan_.ranges.resize(num_laser_points); laser_scan_.intensities.resize(0); laser_scan_.header.seq = 0; laser_scan_.header.frame_id = tf::resolve(model_->GetNameSpace(), frame_id_); // Broadcast transform between the body and laser tf::Quaternion q; q.setRPY(0, 0, origin_.theta); static_tf_.header.frame_id = tf::resolve(model_->GetNameSpace(), body_->GetName()); static_tf_.child_frame_id = tf::resolve(model_->GetNameSpace(), frame_id_); static_tf_.transform.translation.x = origin_.x; static_tf_.transform.translation.y = origin_.y; static_tf_.transform.translation.z = 0; static_tf_.transform.rotation.x = q.x(); static_tf_.transform.rotation.y = q.y(); static_tf_.transform.rotation.z = q.z(); static_tf_.transform.rotation.w = q.w(); } void Laser::BeforePhysicsStep(const Timekeeper &timekeeper) { // keep the update rate if (!update_timer_.CheckUpdate(timekeeper)) { return; } // only compute and publish when the number of subscribers is not zero if (scan_publisher_.getNumSubscribers() > 0) { ComputeLaserRanges(); laser_scan_.header.stamp = ros::Time::now(); scan_publisher_.publish(laser_scan_); } static_tf_.header.stamp = ros::Time::now(); tf_broadcaster_.sendTransform(static_tf_); } void Laser::ComputeLaserRanges() { // get the transformation matrix from the world to the body, and get the // world to laser frame transformation matrix by multiplying the world to body // and body to laser const b2Transform &t = body_->GetPhysicsBody()->GetTransform(); m_world_to_body_ << t.q.c, -t.q.s, t.p.x, t.q.s, t.q.c, t.p.y, 0, 0, 1; m_world_to_laser_ = m_world_to_body_ * m_body_to_laser_; // Get the laser points in the world frame by multiplying the laser points in // the laser frame to the transformation matrix from world to laser frame m_world_laser_points_ = m_world_to_laser_ * m_laser_points_; // Get the (0, 0) point in the laser frame v_world_laser_origin_ = m_world_to_laser_ * v_zero_point_; // Conver to Box2D data types b2Vec2 laser_point; b2Vec2 laser_origin_point(v_world_laser_origin_(0), v_world_laser_origin_(1)); // loop through the laser points and call the Box2D world raycast for (int i = 0; i < laser_scan_.ranges.size(); ++i) { laser_point.x = m_world_laser_points_(0, i); laser_point.y = m_world_laser_points_(1, i); did_hit_ = false; model_->GetPhysicsWorld()->RayCast(this, laser_origin_point, laser_point); if (!did_hit_) { laser_scan_.ranges[i] = NAN; } else { laser_scan_.ranges[i] = fraction_ * range_; } } } float Laser::ReportFixture(b2Fixture *fixture, const b2Vec2 &point, const b2Vec2 &normal, float fraction) { // only register hit in the specified layers if (!(fixture->GetFilterData().categoryBits & layers_bits_)) { return -1.0f; // return -1 to ignore this hit } did_hit_ = true; fraction_ = fraction; return fraction; } void Laser::ParseParameters(const YAML::Node &config) { YamlReader reader(config); std::string body_name = reader.Get<std::string>("body"); topic_ = reader.Get<std::string>("topic", "scan"); frame_id_ = reader.Get<std::string>("frame", name_); update_rate_ = reader.Get<double>("update_rate", std::numeric_limits<double>::infinity()); origin_ = reader.GetPose("origin", Pose(0, 0, 0)); range_ = reader.Get<double>("range"); std::vector<std::string> layers = reader.GetList<std::string>("layers", {"all"}, -1, -1); YamlReader angle_reader = reader.Subnode("angle", YamlReader::MAP); min_angle_ = angle_reader.Get<double>("min"); max_angle_ = angle_reader.Get<double>("max"); increment_ = angle_reader.Get<double>("increment"); angle_reader.EnsureAccessedAllKeys(); reader.EnsureAccessedAllKeys(); if (max_angle_ < min_angle_) { throw YAMLException("Invalid \"angle\" params, must have max > min"); } body_ = model_->GetBody(body_name); if (!body_) { throw YAMLException("Cannot find body with name " + body_name); } std::vector<std::string> invalid_layers; layers_bits_ = model_->GetCfr()->GetCategoryBits(layers, &invalid_layers); if (!invalid_layers.empty()) { throw YAMLException("Cannot find layer(s): {" + boost::algorithm::join(invalid_layers, ",") + "}"); } ROS_DEBUG_NAMED("LaserPlugin", "Laser %s params: topic(%s) body(%s, %p) origin(%f,%f,%f) " "frame_id(%s) update_rate(%f) range(%f) angle_min(%f) " "angle_max(%f) angle_increment(%f) layers(0x%u {%s})", name_.c_str(), topic_.c_str(), body_name.c_str(), body_, origin_.x, origin_.y, origin_.theta, frame_id_.c_str(), update_rate_, range_, min_angle_, max_angle_, increment_, layers_bits_, boost::algorithm::join(layers, ",").c_str()); } }; PLUGINLIB_EXPORT_CLASS(flatland_plugins::Laser, flatland_server::ModelPlugin)<|endoftext|>
<commit_before># include <cstdlib> // std :: rand () # include <vector> // std :: vector <> # include <list> // std :: list <> # include <iostream> // std :: cout # include <iterator> // std :: ostream_iterator <> # include <algorithm> // std :: reverse , std :: generate # include <set> #include <map> int main () { std::list <unsigned int> l1(100); //Liste mit random-Zahlen füllen for (auto& l : l1){ l = std::rand() % 101; } // std::copy(std::begin(l1), std::end(l1), // std::ostream_iterator<int>(std::cout, "\n")); std::vector<unsigned int> v1(l1.size()); //Inhalt der Liste in Vektor kopieren std::copy(std::begin(l1), std::end(l1), std::begin(v1)); std::copy(std::begin(v1), std::end(v1), std::ostream_iterator<int>(std::cout, "\n")); std::set<int> s1; //Inhalt des Vektors in set sortieren (doppelte werden nur 1x einsortiert) for(auto& i : v1){ s1.insert(i); } std::copy(std::begin(s1), std::end(s1), //set ausgeben std::ostream_iterator<int>(std::cout, "\n")); std::cout << "In der Liste stehen " << s1.size() << " verschiedene Zahlen. \n"; std::cout << "Diese Zahlen zwischen 0 und 100 fehlen: \n"; for (int j = 0; j <= 100; ++j){ //alle Zahlen zw 1 u 100 finden, die nicht im set stehen. if(s1.find(j) == s1.end()){ std::cout << j << "\n"; } } std::map<int, int> map1; /* mit map, weil man bei map der jeweiligen Zahl (key) einen Wert (value) *zuweisen und diesen entsprechend erhöhen kann, wenn die Zahl erneut *gefunden wird. Map ist ein assoziativer Container. */ int i{0}; int c; while(i<v1.size()){ c = v1[i]; ++map1[c]; /*Jede Zahl, die in v1 gefunden wird, wird mit Schlüssel 0 hinzugefügt *und dann durch ++ um 1 erhöht. Wird sie nochmal gefunden, wird der *Schlüssel nochmal um 1 erhöht */ ++i; } typedef std::map<int,int>::const_iterator Iter; //Ausgabe der map als key : value for(Iter p = map1.begin(); p!= map1.end(); ++p){ std::cout << p -> first << " : " << p -> second << '\n'; } return 0; } <commit_msg>Add 3.4 Map<commit_after># include <cstdlib> // std :: rand () # include <vector> // std :: vector <> # include <list> // std :: list <> # include <iostream> // std :: cout # include <iterator> // std :: ostream_iterator <> # include <algorithm> // std :: reverse , std :: generate # include <set> # include <map> int main () { std::list <unsigned int> l1(100); //Liste mit random-Zahlen füllen for (auto& l : l1){ l = std::rand() % 101; } // std::copy(std::begin(l1), std::end(l1), // std::ostream_iterator<int>(std::cout, "\n")); std::vector<unsigned int> v1(l1.size()); //Inhalt der Liste in Vektor kopieren std::copy(std::begin(l1), std::end(l1), std::begin(v1)); std::copy(std::begin(v1), std::end(v1), std::ostream_iterator<int>(std::cout, "\n")); std::set<int> s1; //Inhalt des Vektors in set sortieren (doppelte werden nur 1x einsortiert) for(auto& i : v1){ s1.insert(i); } std::copy(std::begin(s1), std::end(s1), //set ausgeben std::ostream_iterator<int>(std::cout, "\n")); std::cout << "In der Liste stehen " << s1.size() << " verschiedene Zahlen. \n"; std::cout << "Diese Zahlen zwischen 0 und 100 fehlen: \n"; for (int j = 0; j <= 100; ++j){ //alle Zahlen zw 1 u 100 finden, die nicht im set stehen. if(s1.find(j) == s1.end()){ std::cout << j << "\n"; } } std::map<int, int> map1; /* mit map, weil man bei map der jeweiligen Zahl (key) einen Wert (value) *zuweisen und diesen entsprechend erhöhen kann, wenn die Zahl erneut *gefunden wird. Map ist ein assoziativer Container. */ int i{0}; int c; while(i<v1.size()){ c = v1[i]; ++map1[c]; /*Jede Zahl, die in v1 gefunden wird, wird mit Schlüssel 0 hinzugefügt *und dann durch ++ um 1 erhöht. Wird sie nochmal gefunden, wird der *Schlüssel nochmal um 1 erhöht */ ++i; } typedef std::map<int,int>::const_iterator Iter; //Ausgabe der map als key : value for(Iter p = map1.begin(); p!= map1.end(); ++p){ std::cout << p -> first << " : " << p -> second << '\n'; } return 0; } <|endoftext|>
<commit_before>/********************************************************************** * $Id$ * * GEOS - Geometry Engine Open Source * http://geos.refractions.net * * Copyright (C) 2001-2002 Vivid Solutions Inc. * * 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. * ********************************************************************** * $Log$ * Revision 1.43 2004/07/27 16:35:46 strk * Geometry::getEnvelopeInternal() changed to return a const Envelope *. * This should reduce object copies as once computed the envelope of a * geometry remains the same. * * Revision 1.42 2004/07/22 07:04:49 strk * Documented missing geometry functions. * * Revision 1.41 2004/07/13 08:33:52 strk * Added missing virtual destructor to virtual classes. * Fixed implicit unsigned int -> int casts * * Revision 1.40 2004/07/08 19:34:49 strk * Mirrored JTS interface of CoordinateSequence, factory and * default implementations. * Added DefaultCoordinateSequenceFactory::instance() function. * * Revision 1.39 2004/07/06 17:58:22 strk * Removed deprecated Geometry constructors based on PrecisionModel and * SRID specification. Removed SimpleGeometryPrecisionReducer capability * of changing Geometry's factory. Reverted Geometry::factory member * to be a reference to external factory. * * Revision 1.38 2004/07/05 10:50:20 strk * deep-dopy construction taken out of Geometry and implemented only * in GeometryFactory. * Deep-copy geometry construction takes care of cleaning up copies * on exception. * Implemented clone() method for CoordinateSequence * Changed createMultiPoint(CoordinateSequence) signature to reflect * copy semantic (by-ref instead of by-pointer). * Cleaned up documentation. * * Revision 1.37 2004/07/02 13:28:26 strk * Fixed all #include lines to reflect headers layout change. * Added client application build tips in README. * * Revision 1.36 2004/07/01 14:12:44 strk * * Geometry constructors come now in two flavors: * - deep-copy args (pass-by-reference) * - take-ownership of args (pass-by-pointer) * Same functionality is available through GeometryFactory, * including buildGeometry(). * * Revision 1.35 2004/06/28 21:58:24 strk * Constructors speedup. * * Revision 1.34 2004/06/28 21:11:43 strk * Moved getGeometryTypeId() definitions from geom.h to each geometry module. * Added holes argument check in Polygon.cpp. * * Revision 1.33 2004/06/15 20:30:47 strk * updated to respect deep-copy GeometryCollection interface * * Revision 1.32 2004/04/20 13:24:15 strk * More leaks removed. * * Revision 1.31 2004/04/20 08:52:01 strk * GeometryFactory and Geometry const correctness. * Memory leaks removed from SimpleGeometryPrecisionReducer * and GeometryFactory. * * Revision 1.30 2004/04/01 10:44:33 ybychkov * All "geom" classes from JTS 1.3 upgraded to JTS 1.4 * * Revision 1.29 2004/03/31 07:50:37 ybychkov * "geom" partially upgraded to JTS 1.4 * * Revision 1.28 2004/02/27 17:43:45 strk * memory leak fix in Polygon::getArea() - reported by 'Manuel Prieto Villegas' <mprieto@dap.es> * * Revision 1.27 2003/11/07 01:23:42 pramsey * Add standard CVS headers licence notices and copyrights to all cpp and h * files. * * Revision 1.26 2003/10/31 16:36:04 strk * Re-introduced clone() method. Copy constructor could not really * replace it. * * Revision 1.25 2003/10/17 05:51:21 ybychkov * Fixed a small memory leak. * * Revision 1.24 2003/10/16 08:50:00 strk * Memory leak fixes. Improved performance by mean of more calls to * new getCoordinatesRO() when applicable. * **********************************************************************/ #include <geos/geom.h> #include <typeinfo> #include <geos/geosAlgorithm.h> namespace geos { Polygon::Polygon(const Polygon &p): Geometry(p.getFactory()){ shell=new LinearRing(*p.shell); holes=new vector<Geometry *>(); for(int i=0;i<(int)p.holes->size();i++) { LinearRing *h=new LinearRing(* (LinearRing*)(*p.holes)[i]); holes->push_back(h); } } /* * Constructs a <code>Polygon</code> with the given exterior * and interior boundaries. * * @param shell the outer boundary of the new <code>Polygon</code>, * or <code>null</code> or an empty * <code>LinearRing</code> if the empty geometry * is to be created. * * @param holes the <code>LinearRings</code> defining the inner * boundaries of the new <code>Polygon</code>, or * <code>null</code> or empty <code>LinearRing</code>s * if the empty geometry is to be created. * * Polygon will take ownership of Shell and Holes LinearRings * */ Polygon::Polygon(LinearRing *newShell, vector<Geometry *> *newHoles, const GeometryFactory *newFactory): Geometry(newFactory) { if (newShell==NULL) { shell=getFactory()->createLinearRing(NULL); } else { if (newShell->isEmpty() && hasNonEmptyElements(newHoles)) { delete newShell; delete newHoles; throw new IllegalArgumentException("shell is empty but holes are not"); } shell=newShell; } if (newHoles==NULL) { holes=new vector<Geometry *>(); } else { if (hasNullElements(newHoles)) { delete newShell; delete newHoles; throw new IllegalArgumentException("holes must not contain null elements"); } for (unsigned int i=0; i<newHoles->size(); i++) if ( (*newHoles)[i]->getGeometryTypeId() != GEOS_LINEARRING) throw new IllegalArgumentException("holes must be LinearRings"); holes=newHoles; } } Geometry *Polygon::clone() const { return new Polygon(*this); } CoordinateSequence* Polygon::getCoordinates() const { if (isEmpty()) { return getFactory()->getCoordinateSequenceFactory()->create(NULL); } vector<Coordinate> *cl = new vector<Coordinate>; int k = -1; const CoordinateSequence* shellCoords=shell->getCoordinatesRO(); for (int x = 0; x < shellCoords->getSize(); x++) { k++; cl->push_back(shellCoords->getAt(x)); } for (unsigned int i = 0; i < holes->size(); i++) { const CoordinateSequence* childCoords=((LinearRing *)(*holes)[i])->getCoordinatesRO(); for (int j = 0; j < childCoords->getSize(); j++) { k++; cl->push_back(childCoords->getAt(j)); } } return getFactory()->getCoordinateSequenceFactory()->create(cl); } int Polygon::getNumPoints() const { int numPoints = shell->getNumPoints(); for (unsigned int i = 0; i < holes->size(); i++) { numPoints += ((LinearRing *)(*holes)[i])->getNumPoints(); } return numPoints; } int Polygon::getDimension() const { return 2; } int Polygon::getBoundaryDimension() const { return 1; } bool Polygon::isEmpty() const { return shell->isEmpty(); } bool Polygon::isSimple() const { return true; } const LineString* Polygon::getExteriorRing() const { return shell; } int Polygon::getNumInteriorRing() const { return (int)holes->size(); } const LineString* Polygon::getInteriorRingN(int n) const { return (LineString *) (*holes)[n]; } string Polygon::getGeometryType() const { return "Polygon"; } // Returns a newly allocated Geometry object Geometry* Polygon::getBoundary() const { if (isEmpty()) { return getFactory()->createGeometryCollection(NULL); } vector<Geometry *> rings(holes->size()+1); rings[0]=shell; for (unsigned int i=0; i<holes->size(); i++) { rings[i + 1] = (*holes)[i]; } MultiLineString *ret =getFactory()->createMultiLineString(rings); return ret; } Envelope* Polygon::computeEnvelopeInternal() const { return new Envelope(*(shell->getEnvelopeInternal())); } bool Polygon::equalsExact(const Geometry *other, double tolerance) const { if (!isEquivalentClass(other)) { return false; } const Polygon* otherPolygon=dynamic_cast<const Polygon*>(other); Geometry* thisShell=dynamic_cast<Geometry *>(shell); if (typeid(*(otherPolygon->shell))!=typeid(Geometry)) { return false; } Geometry* otherPolygonShell=dynamic_cast<Geometry *>(otherPolygon->shell); if (!shell->equalsExact(otherPolygonShell, tolerance)) { return false; } if (holes->size()!=otherPolygon->holes->size()) { return false; } for (unsigned int i = 0; i < holes->size(); i++) { if (!((LinearRing *)(*holes)[i])->equalsExact((*(otherPolygon->holes))[i],tolerance)) { return false; } } return true; } void Polygon::apply_ro(CoordinateFilter *filter) const { shell->apply_ro(filter); for (unsigned int i = 0; i < holes->size(); i++) { ((LinearRing *)(*holes)[i])->apply_ro(filter); } } void Polygon::apply_rw(CoordinateFilter *filter) { shell->apply_rw(filter); for (unsigned int i = 0; i < holes->size(); i++) { ((LinearRing *)(*holes)[i])->apply_rw(filter); } } void Polygon::apply_rw(GeometryFilter *filter) { filter->filter_rw(this); } void Polygon::apply_ro(GeometryFilter *filter) const { filter->filter_ro(this); } Geometry* Polygon::convexHull() const { return getExteriorRing()->convexHull(); } void Polygon::normalize() { normalize(shell, true); for (unsigned int i = 0; i < holes->size(); i++) { normalize((LinearRing *)(*holes)[i], false); } sort(holes->begin(),holes->end(),greaterThen); } int Polygon::compareToSameClass(const Geometry *p) const { return shell->compareToSameClass(((Polygon*)p)->shell); } void Polygon::normalize(LinearRing *ring, bool clockwise) { if (ring->isEmpty()) { return; } CoordinateSequence* uniqueCoordinates=ring->getCoordinates(); uniqueCoordinates->deleteAt(uniqueCoordinates->getSize()-1); const Coordinate* minCoordinate=CoordinateSequence::minCoordinate(uniqueCoordinates); CoordinateSequence::scroll(uniqueCoordinates, minCoordinate); uniqueCoordinates->add(uniqueCoordinates->getAt(0)); if (CGAlgorithms::isCCW(uniqueCoordinates)==clockwise) { CoordinateSequence::reverse(uniqueCoordinates); } ring->setPoints(uniqueCoordinates); delete(uniqueCoordinates); } const Coordinate* Polygon::getCoordinate() const { return shell->getCoordinate(); } /* * Returns the area of this <code>Polygon</code> * *@return the area of the polygon */ double Polygon::getArea() const { double area=0.0; area+=fabs(CGAlgorithms::signedArea(shell->getCoordinatesRO())); for(unsigned int i=0;i<holes->size();i++) { CoordinateSequence *h=(*holes)[i]->getCoordinates(); area-=fabs(CGAlgorithms::signedArea(h)); delete h; } return area; } /** * Returns the perimeter of this <code>Polygon</code> * * @return the perimeter of the polygon */ double Polygon::getLength() const { double len=0.0; len+=shell->getLength(); for(unsigned int i=0;i<holes->size();i++) { len+=(*holes)[i]->getLength(); } return len; } void Polygon::apply_ro(GeometryComponentFilter *filter) const { filter->filter_ro(this); shell->apply_ro(filter); for(unsigned int i=0;i<holes->size();i++) { (*holes)[i]->apply_ro(filter); } } void Polygon::apply_rw(GeometryComponentFilter *filter) { filter->filter_rw(this); shell->apply_rw(filter); for(unsigned int i=0;i<holes->size();i++) { (*holes)[i]->apply_rw(filter); } } Polygon::~Polygon(){ delete shell; for(int i=0;i<(int)holes->size();i++) { delete (*holes)[i]; } delete holes; } GeometryTypeId Polygon::getGeometryTypeId() const { return GEOS_POLYGON; } } <commit_msg>Changed ::getBoundary() to return LineString if polygon has no holes. (has required to pass OGC conformance test T20)<commit_after>/********************************************************************** * $Id$ * * GEOS - Geometry Engine Open Source * http://geos.refractions.net * * Copyright (C) 2001-2002 Vivid Solutions Inc. * * 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. * ********************************************************************** * $Log$ * Revision 1.44 2004/11/12 18:12:05 strk * Changed ::getBoundary() to return LineString if polygon has no holes. * (has required to pass OGC conformance test T20) * * Revision 1.43 2004/07/27 16:35:46 strk * Geometry::getEnvelopeInternal() changed to return a const Envelope *. * This should reduce object copies as once computed the envelope of a * geometry remains the same. * * Revision 1.42 2004/07/22 07:04:49 strk * Documented missing geometry functions. * * Revision 1.41 2004/07/13 08:33:52 strk * Added missing virtual destructor to virtual classes. * Fixed implicit unsigned int -> int casts * * Revision 1.40 2004/07/08 19:34:49 strk * Mirrored JTS interface of CoordinateSequence, factory and * default implementations. * Added DefaultCoordinateSequenceFactory::instance() function. * * Revision 1.39 2004/07/06 17:58:22 strk * Removed deprecated Geometry constructors based on PrecisionModel and * SRID specification. Removed SimpleGeometryPrecisionReducer capability * of changing Geometry's factory. Reverted Geometry::factory member * to be a reference to external factory. * * Revision 1.38 2004/07/05 10:50:20 strk * deep-dopy construction taken out of Geometry and implemented only * in GeometryFactory. * Deep-copy geometry construction takes care of cleaning up copies * on exception. * Implemented clone() method for CoordinateSequence * Changed createMultiPoint(CoordinateSequence) signature to reflect * copy semantic (by-ref instead of by-pointer). * Cleaned up documentation. * * Revision 1.37 2004/07/02 13:28:26 strk * Fixed all #include lines to reflect headers layout change. * Added client application build tips in README. * * Revision 1.36 2004/07/01 14:12:44 strk * * Geometry constructors come now in two flavors: * - deep-copy args (pass-by-reference) * - take-ownership of args (pass-by-pointer) * Same functionality is available through GeometryFactory, * including buildGeometry(). * * Revision 1.35 2004/06/28 21:58:24 strk * Constructors speedup. * * Revision 1.34 2004/06/28 21:11:43 strk * Moved getGeometryTypeId() definitions from geom.h to each geometry module. * Added holes argument check in Polygon.cpp. * * Revision 1.33 2004/06/15 20:30:47 strk * updated to respect deep-copy GeometryCollection interface * * Revision 1.32 2004/04/20 13:24:15 strk * More leaks removed. * * Revision 1.31 2004/04/20 08:52:01 strk * GeometryFactory and Geometry const correctness. * Memory leaks removed from SimpleGeometryPrecisionReducer * and GeometryFactory. * * Revision 1.30 2004/04/01 10:44:33 ybychkov * All "geom" classes from JTS 1.3 upgraded to JTS 1.4 * * Revision 1.29 2004/03/31 07:50:37 ybychkov * "geom" partially upgraded to JTS 1.4 * * Revision 1.28 2004/02/27 17:43:45 strk * memory leak fix in Polygon::getArea() - reported by 'Manuel Prieto Villegas' <mprieto@dap.es> * * Revision 1.27 2003/11/07 01:23:42 pramsey * Add standard CVS headers licence notices and copyrights to all cpp and h * files. * * Revision 1.26 2003/10/31 16:36:04 strk * Re-introduced clone() method. Copy constructor could not really * replace it. * * Revision 1.25 2003/10/17 05:51:21 ybychkov * Fixed a small memory leak. * * Revision 1.24 2003/10/16 08:50:00 strk * Memory leak fixes. Improved performance by mean of more calls to * new getCoordinatesRO() when applicable. * **********************************************************************/ #include <geos/geom.h> #include <typeinfo> #include <geos/geosAlgorithm.h> namespace geos { Polygon::Polygon(const Polygon &p): Geometry(p.getFactory()){ shell=new LinearRing(*p.shell); holes=new vector<Geometry *>(); for(int i=0;i<(int)p.holes->size();i++) { LinearRing *h=new LinearRing(* (LinearRing*)(*p.holes)[i]); holes->push_back(h); } } /* * Constructs a <code>Polygon</code> with the given exterior * and interior boundaries. * * @param shell the outer boundary of the new <code>Polygon</code>, * or <code>null</code> or an empty * <code>LinearRing</code> if the empty geometry * is to be created. * * @param holes the <code>LinearRings</code> defining the inner * boundaries of the new <code>Polygon</code>, or * <code>null</code> or empty <code>LinearRing</code>s * if the empty geometry is to be created. * * Polygon will take ownership of Shell and Holes LinearRings * */ Polygon::Polygon(LinearRing *newShell, vector<Geometry *> *newHoles, const GeometryFactory *newFactory): Geometry(newFactory) { if (newShell==NULL) { shell=getFactory()->createLinearRing(NULL); } else { if (newShell->isEmpty() && hasNonEmptyElements(newHoles)) { delete newShell; delete newHoles; throw new IllegalArgumentException("shell is empty but holes are not"); } shell=newShell; } if (newHoles==NULL) { holes=new vector<Geometry *>(); } else { if (hasNullElements(newHoles)) { delete newShell; delete newHoles; throw new IllegalArgumentException("holes must not contain null elements"); } for (unsigned int i=0; i<newHoles->size(); i++) if ( (*newHoles)[i]->getGeometryTypeId() != GEOS_LINEARRING) throw new IllegalArgumentException("holes must be LinearRings"); holes=newHoles; } } Geometry *Polygon::clone() const { return new Polygon(*this); } CoordinateSequence* Polygon::getCoordinates() const { if (isEmpty()) { return getFactory()->getCoordinateSequenceFactory()->create(NULL); } vector<Coordinate> *cl = new vector<Coordinate>; int k = -1; const CoordinateSequence* shellCoords=shell->getCoordinatesRO(); for (int x = 0; x < shellCoords->getSize(); x++) { k++; cl->push_back(shellCoords->getAt(x)); } for (unsigned int i = 0; i < holes->size(); i++) { const CoordinateSequence* childCoords=((LinearRing *)(*holes)[i])->getCoordinatesRO(); for (int j = 0; j < childCoords->getSize(); j++) { k++; cl->push_back(childCoords->getAt(j)); } } return getFactory()->getCoordinateSequenceFactory()->create(cl); } int Polygon::getNumPoints() const { int numPoints = shell->getNumPoints(); for (unsigned int i = 0; i < holes->size(); i++) { numPoints += ((LinearRing *)(*holes)[i])->getNumPoints(); } return numPoints; } int Polygon::getDimension() const { return 2; } int Polygon::getBoundaryDimension() const { return 1; } bool Polygon::isEmpty() const { return shell->isEmpty(); } bool Polygon::isSimple() const { return true; } const LineString* Polygon::getExteriorRing() const { return shell; } int Polygon::getNumInteriorRing() const { return (int)holes->size(); } const LineString* Polygon::getInteriorRingN(int n) const { return (LineString *) (*holes)[n]; } string Polygon::getGeometryType() const { return "Polygon"; } // Returns a newly allocated Geometry object Geometry* Polygon::getBoundary() const { if (isEmpty()) { return getFactory()->createGeometryCollection(NULL); } if ( ! holes->size() ) { return shell->clone(); } vector<Geometry *> rings(holes->size()+1); rings[0]=shell; for (unsigned int i=0; i<holes->size(); i++) { rings[i + 1] = (*holes)[i]; } MultiLineString *ret =getFactory()->createMultiLineString(rings); return ret; } Envelope* Polygon::computeEnvelopeInternal() const { return new Envelope(*(shell->getEnvelopeInternal())); } bool Polygon::equalsExact(const Geometry *other, double tolerance) const { if (!isEquivalentClass(other)) { return false; } const Polygon* otherPolygon=dynamic_cast<const Polygon*>(other); Geometry* thisShell=dynamic_cast<Geometry *>(shell); if (typeid(*(otherPolygon->shell))!=typeid(Geometry)) { return false; } Geometry* otherPolygonShell=dynamic_cast<Geometry *>(otherPolygon->shell); if (!shell->equalsExact(otherPolygonShell, tolerance)) { return false; } if (holes->size()!=otherPolygon->holes->size()) { return false; } for (unsigned int i = 0; i < holes->size(); i++) { if (!((LinearRing *)(*holes)[i])->equalsExact((*(otherPolygon->holes))[i],tolerance)) { return false; } } return true; } void Polygon::apply_ro(CoordinateFilter *filter) const { shell->apply_ro(filter); for (unsigned int i = 0; i < holes->size(); i++) { ((LinearRing *)(*holes)[i])->apply_ro(filter); } } void Polygon::apply_rw(CoordinateFilter *filter) { shell->apply_rw(filter); for (unsigned int i = 0; i < holes->size(); i++) { ((LinearRing *)(*holes)[i])->apply_rw(filter); } } void Polygon::apply_rw(GeometryFilter *filter) { filter->filter_rw(this); } void Polygon::apply_ro(GeometryFilter *filter) const { filter->filter_ro(this); } Geometry* Polygon::convexHull() const { return getExteriorRing()->convexHull(); } void Polygon::normalize() { normalize(shell, true); for (unsigned int i = 0; i < holes->size(); i++) { normalize((LinearRing *)(*holes)[i], false); } sort(holes->begin(),holes->end(),greaterThen); } int Polygon::compareToSameClass(const Geometry *p) const { return shell->compareToSameClass(((Polygon*)p)->shell); } void Polygon::normalize(LinearRing *ring, bool clockwise) { if (ring->isEmpty()) { return; } CoordinateSequence* uniqueCoordinates=ring->getCoordinates(); uniqueCoordinates->deleteAt(uniqueCoordinates->getSize()-1); const Coordinate* minCoordinate=CoordinateSequence::minCoordinate(uniqueCoordinates); CoordinateSequence::scroll(uniqueCoordinates, minCoordinate); uniqueCoordinates->add(uniqueCoordinates->getAt(0)); if (CGAlgorithms::isCCW(uniqueCoordinates)==clockwise) { CoordinateSequence::reverse(uniqueCoordinates); } ring->setPoints(uniqueCoordinates); delete(uniqueCoordinates); } const Coordinate* Polygon::getCoordinate() const { return shell->getCoordinate(); } /* * Returns the area of this <code>Polygon</code> * *@return the area of the polygon */ double Polygon::getArea() const { double area=0.0; area+=fabs(CGAlgorithms::signedArea(shell->getCoordinatesRO())); for(unsigned int i=0;i<holes->size();i++) { CoordinateSequence *h=(*holes)[i]->getCoordinates(); area-=fabs(CGAlgorithms::signedArea(h)); delete h; } return area; } /** * Returns the perimeter of this <code>Polygon</code> * * @return the perimeter of the polygon */ double Polygon::getLength() const { double len=0.0; len+=shell->getLength(); for(unsigned int i=0;i<holes->size();i++) { len+=(*holes)[i]->getLength(); } return len; } void Polygon::apply_ro(GeometryComponentFilter *filter) const { filter->filter_ro(this); shell->apply_ro(filter); for(unsigned int i=0;i<holes->size();i++) { (*holes)[i]->apply_ro(filter); } } void Polygon::apply_rw(GeometryComponentFilter *filter) { filter->filter_rw(this); shell->apply_rw(filter); for(unsigned int i=0;i<holes->size();i++) { (*holes)[i]->apply_rw(filter); } } Polygon::~Polygon(){ delete shell; for(int i=0;i<(int)holes->size();i++) { delete (*holes)[i]; } delete holes; } GeometryTypeId Polygon::getGeometryTypeId() const { return GEOS_POLYGON; } } <|endoftext|>
<commit_before>#include "log_ui.h" #include "core/log.h" #include "imgui/imgui.h" LogUI::LogUI(Lumix::IAllocator& allocator) : m_allocator(allocator) , m_messages(allocator) , m_current_tab(0) , m_notifications(allocator) , m_last_uid(1) , m_guard(false) { m_is_opened = false; Lumix::g_log_info.getCallback().bind<LogUI, &LogUI::onInfo>(this); Lumix::g_log_error.getCallback().bind<LogUI, &LogUI::onError>(this); Lumix::g_log_warning.getCallback().bind<LogUI, &LogUI::onWarning>(this); for (int i = 0; i < Count; ++i) { m_new_message_count[i] = 0; m_messages.emplace(allocator); } } LogUI::~LogUI() { Lumix::g_log_info.getCallback().unbind<LogUI, &LogUI::onInfo>(this); Lumix::g_log_error.getCallback().unbind<LogUI, &LogUI::onError>(this); Lumix::g_log_warning.getCallback().unbind<LogUI, &LogUI::onWarning>(this); } void LogUI::setNotificationTime(int uid, float time) { for (auto& notif : m_notifications) { if (notif.uid == uid) { notif.time = time; break; } } } int LogUI::addNotification(const char* text) { m_move_notifications_to_front = true; auto& notif = m_notifications.emplace(m_allocator); notif.time = 10.0f; notif.message = text; notif.uid = ++m_last_uid; return notif.uid; } void LogUI::push(Type type, const char* message) { Lumix::MT::SpinLock lock(m_guard); ++m_new_message_count[type]; m_messages[type].push(Lumix::string(message, m_allocator)); if (type == Error || type == Warning) { addNotification(message); } } void LogUI::onInfo(const char* system, const char* message) { push(Lumix::compareString(system, "bgfx") == 0 ? BGFX : Info, message); } void LogUI::onWarning(const char* system, const char* message) { push(Lumix::compareString(system, "bgfx") == 0 ? BGFX : Warning, message); } void LogUI::onError(const char* system, const char* message) { push(Lumix::compareString(system, "bgfx") == 0 ? BGFX : Error, message); } void fillLabel(char* output, int max_size, const char* label, int count) { Lumix::copyString(output, max_size, label); Lumix::catString(output, max_size, "("); int len = Lumix::stringLength(output); Lumix::toCString(count, output + len, max_size - len); Lumix::catString(output, max_size, ")"); } void LogUI::showNotifications() { m_are_notifications_hovered = false; if (m_notifications.empty()) return; ImGui::SetNextWindowPos(ImVec2(10, 30)); bool opened; if (!ImGui::Begin("Notifications", &opened, ImVec2(200, 0), 1.0f, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings)) { ImGui::End(); return; } m_are_notifications_hovered = ImGui::IsWindowHovered(); if (ImGui::Button("Close")) m_notifications.clear(); if (m_move_notifications_to_front) ImGui::BringToFront(); m_move_notifications_to_front = false; for (int i = 0; i < m_notifications.size(); ++i) { if (i > 0) ImGui::Separator(); ImGui::Text(m_notifications[i].message.c_str()); } ImGui::End(); } void LogUI::update(float time_delta) { if (m_are_notifications_hovered) return; for (int i = 0; i < m_notifications.size(); ++i) { m_notifications[i].time -= time_delta; if (m_notifications[i].time < 0) { m_notifications.erase(i); --i; } } } void LogUI::onGUI() { Lumix::MT::SpinLock lock(m_guard); showNotifications(); if (ImGui::BeginDock("Log", &m_is_opened)) { const char* labels[] = { "Info", "Warning", "Error", "BGFX" }; for (int i = 0; i < Lumix::lengthOf(labels); ++i) { char label[20]; fillLabel(label, sizeof(label), labels[i], m_new_message_count[i]); if(i > 0) ImGui::SameLine(); if (ImGui::Button(label)) { m_current_tab = i; m_new_message_count[i] = 0; } } auto* messages = &m_messages[m_current_tab]; if (ImGui::Button("Clear")) { for (int i = 0; i < m_messages.size(); ++i) { m_messages[i].clear(); m_new_message_count[i] = 0; } } ImGui::SameLine(); char filter[128] = ""; ImGui::InputText("Filter", filter, sizeof(filter)); if (ImGui::BeginChild("log_messages")) { for (int i = 0; i < messages->size(); ++i) { const char* msg = (*messages)[i].c_str(); if (filter[0] == '\0' || strstr(msg, filter) != nullptr) { ImGui::Text(msg); } } } ImGui::EndChild(); } ImGui::EndDock(); } <commit_msg>notifications have border<commit_after>#include "log_ui.h" #include "core/log.h" #include "imgui/imgui.h" LogUI::LogUI(Lumix::IAllocator& allocator) : m_allocator(allocator) , m_messages(allocator) , m_current_tab(0) , m_notifications(allocator) , m_last_uid(1) , m_guard(false) { m_is_opened = false; Lumix::g_log_info.getCallback().bind<LogUI, &LogUI::onInfo>(this); Lumix::g_log_error.getCallback().bind<LogUI, &LogUI::onError>(this); Lumix::g_log_warning.getCallback().bind<LogUI, &LogUI::onWarning>(this); for (int i = 0; i < Count; ++i) { m_new_message_count[i] = 0; m_messages.emplace(allocator); } } LogUI::~LogUI() { Lumix::g_log_info.getCallback().unbind<LogUI, &LogUI::onInfo>(this); Lumix::g_log_error.getCallback().unbind<LogUI, &LogUI::onError>(this); Lumix::g_log_warning.getCallback().unbind<LogUI, &LogUI::onWarning>(this); } void LogUI::setNotificationTime(int uid, float time) { for (auto& notif : m_notifications) { if (notif.uid == uid) { notif.time = time; break; } } } int LogUI::addNotification(const char* text) { m_move_notifications_to_front = true; auto& notif = m_notifications.emplace(m_allocator); notif.time = 10.0f; notif.message = text; notif.uid = ++m_last_uid; return notif.uid; } void LogUI::push(Type type, const char* message) { Lumix::MT::SpinLock lock(m_guard); ++m_new_message_count[type]; m_messages[type].push(Lumix::string(message, m_allocator)); if (type == Error || type == Warning) { addNotification(message); } } void LogUI::onInfo(const char* system, const char* message) { push(Lumix::compareString(system, "bgfx") == 0 ? BGFX : Info, message); } void LogUI::onWarning(const char* system, const char* message) { push(Lumix::compareString(system, "bgfx") == 0 ? BGFX : Warning, message); } void LogUI::onError(const char* system, const char* message) { push(Lumix::compareString(system, "bgfx") == 0 ? BGFX : Error, message); } void fillLabel(char* output, int max_size, const char* label, int count) { Lumix::copyString(output, max_size, label); Lumix::catString(output, max_size, "("); int len = Lumix::stringLength(output); Lumix::toCString(count, output + len, max_size - len); Lumix::catString(output, max_size, ")"); } void LogUI::showNotifications() { m_are_notifications_hovered = false; if (m_notifications.empty()) return; ImGui::SetNextWindowPos(ImVec2(10, 30)); bool opened; if (!ImGui::Begin("Notifications", &opened, ImVec2(200, 0), 1.0f, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_ShowBorders)) { ImGui::End(); return; } m_are_notifications_hovered = ImGui::IsWindowHovered(); if (ImGui::Button("Close")) m_notifications.clear(); if (m_move_notifications_to_front) ImGui::BringToFront(); m_move_notifications_to_front = false; for (int i = 0; i < m_notifications.size(); ++i) { if (i > 0) ImGui::Separator(); ImGui::Text(m_notifications[i].message.c_str()); } ImGui::End(); } void LogUI::update(float time_delta) { if (m_are_notifications_hovered) return; for (int i = 0; i < m_notifications.size(); ++i) { m_notifications[i].time -= time_delta; if (m_notifications[i].time < 0) { m_notifications.erase(i); --i; } } } void LogUI::onGUI() { Lumix::MT::SpinLock lock(m_guard); showNotifications(); if (ImGui::BeginDock("Log", &m_is_opened)) { const char* labels[] = { "Info", "Warning", "Error", "BGFX" }; for (int i = 0; i < Lumix::lengthOf(labels); ++i) { char label[20]; fillLabel(label, sizeof(label), labels[i], m_new_message_count[i]); if(i > 0) ImGui::SameLine(); if (ImGui::Button(label)) { m_current_tab = i; m_new_message_count[i] = 0; } } auto* messages = &m_messages[m_current_tab]; if (ImGui::Button("Clear")) { for (int i = 0; i < m_messages.size(); ++i) { m_messages[i].clear(); m_new_message_count[i] = 0; } } ImGui::SameLine(); char filter[128] = ""; ImGui::InputText("Filter", filter, sizeof(filter)); if (ImGui::BeginChild("log_messages")) { for (int i = 0; i < messages->size(); ++i) { const char* msg = (*messages)[i].c_str(); if (filter[0] == '\0' || strstr(msg, filter) != nullptr) { ImGui::Text(msg); } } } ImGui::EndChild(); } ImGui::EndDock(); } <|endoftext|>
<commit_before>/* * Spdylay - SPDY Library * * Copyright (c) 2012 Tatsuhiro Tsujikawa * * 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 "shrpx_client_handler.h" #include <unistd.h> #include <cerrno> #include "shrpx_upstream.h" #include "shrpx_spdy_upstream.h" #include "shrpx_https_upstream.h" #include "shrpx_config.h" #include "shrpx_http_downstream_connection.h" #include "shrpx_spdy_downstream_connection.h" #include "shrpx_accesslog.h" namespace shrpx { namespace { void upstream_readcb(bufferevent *bev, void *arg) { ClientHandler *handler = static_cast<ClientHandler*>(arg); int rv = handler->on_read(); if(rv != 0) { delete handler; } } } // namespace namespace { void upstream_writecb(bufferevent *bev, void *arg) { ClientHandler *handler = static_cast<ClientHandler*>(arg); // We actually depend on write low-warter mark == 0. if(handler->get_outbuf_length() > 0) { // Possibly because of deferred callback, we may get this callback // when the output buffer is not empty. return; } if(handler->get_should_close_after_write()) { delete handler; } else { Upstream *upstream = handler->get_upstream(); int rv = upstream->on_write(); if(rv != 0) { delete handler; } } } } // namespace namespace { void upstream_eventcb(bufferevent *bev, short events, void *arg) { ClientHandler *handler = static_cast<ClientHandler*>(arg); bool finish = false; if(events & BEV_EVENT_EOF) { if(LOG_ENABLED(INFO)) { CLOG(INFO, handler) << "EOF"; } finish = true; } if(events & BEV_EVENT_ERROR) { if(LOG_ENABLED(INFO)) { CLOG(INFO, handler) << "Network error: " << evutil_socket_error_to_string (EVUTIL_SOCKET_ERROR()); } finish = true; } if(events & BEV_EVENT_TIMEOUT) { if(LOG_ENABLED(INFO)) { CLOG(INFO, handler) << "Time out"; } finish = true; } if(finish) { delete handler; } else { if(events & BEV_EVENT_CONNECTED) { handler->set_tls_handshake(true); if(LOG_ENABLED(INFO)) { CLOG(INFO, handler) << "SSL/TLS handshake completed"; } handler->set_bev_cb(upstream_readcb, upstream_writecb, upstream_eventcb); handler->validate_next_proto(); if(LOG_ENABLED(INFO)) { if(SSL_session_reused(handler->get_ssl())) { CLOG(INFO, handler) << "SSL/TLS session reused"; } } // At this point, input buffer is already filled with some // bytes. The read callback is not called until new data // come. So consume input buffer here. handler->get_upstream()->on_read(); } } } } // namespace namespace { void tls_raw_readcb(evbuffer *buffer, const evbuffer_cb_info *info, void *arg) { ClientHandler *handler = static_cast<ClientHandler*>(arg); if(handler->get_tls_renegotiation()) { if(LOG_ENABLED(INFO)) { CLOG(INFO, handler) << "Close connection due to TLS renegotiation"; } delete handler; } } } // namespace ClientHandler::ClientHandler(bufferevent *bev, int fd, SSL *ssl, const char *ipaddr) : ipaddr_(ipaddr), bev_(bev), ssl_(ssl), upstream_(0), spdy_(0), fd_(fd), should_close_after_write_(false), tls_handshake_(false), tls_renegotiation_(false) { bufferevent_set_rate_limit(bev_, get_config()->rate_limit_cfg); bufferevent_enable(bev_, EV_READ | EV_WRITE); bufferevent_setwatermark(bev_, EV_READ, 0, SHRPX_READ_WARTER_MARK); set_upstream_timeouts(&get_config()->upstream_read_timeout, &get_config()->upstream_write_timeout); if(ssl_) { SSL_set_app_data(ssl_, reinterpret_cast<char*>(this)); set_bev_cb(0, upstream_writecb, upstream_eventcb); evbuffer *input = bufferevent_get_input(bufferevent_get_underlying(bev_)); evbuffer_add_cb(input, tls_raw_readcb, this); } else { if(get_config()->client_mode) { // Client mode upstream_ = new HttpsUpstream(this); } else { // no-TLS SPDY upstream_ = new SpdyUpstream(get_config()->spdy_upstream_version, this); } set_bev_cb(upstream_readcb, upstream_writecb, upstream_eventcb); } } ClientHandler::~ClientHandler() { if(LOG_ENABLED(INFO)) { CLOG(INFO, this) << "Deleting"; } if(ssl_) { SSL_set_app_data(ssl_, 0); SSL_set_shutdown(ssl_, SSL_RECEIVED_SHUTDOWN); SSL_shutdown(ssl_); } bufferevent *underlying = bufferevent_get_underlying(bev_); bufferevent_disable(bev_, EV_READ | EV_WRITE); bufferevent_free(bev_); if(underlying) { bufferevent_disable(underlying, EV_READ | EV_WRITE); bufferevent_free(underlying); } if(ssl_) { SSL_free(ssl_); } shutdown(fd_, SHUT_WR); close(fd_); delete upstream_; for(std::set<DownstreamConnection*>::iterator i = dconn_pool_.begin(); i != dconn_pool_.end(); ++i) { delete *i; } if(LOG_ENABLED(INFO)) { CLOG(INFO, this) << "Deleted"; } } Upstream* ClientHandler::get_upstream() { return upstream_; } bufferevent* ClientHandler::get_bev() const { return bev_; } event_base* ClientHandler::get_evbase() const { return bufferevent_get_base(bev_); } void ClientHandler::set_bev_cb (bufferevent_data_cb readcb, bufferevent_data_cb writecb, bufferevent_event_cb eventcb) { bufferevent_setcb(bev_, readcb, writecb, eventcb, this); } void ClientHandler::set_upstream_timeouts(const timeval *read_timeout, const timeval *write_timeout) { bufferevent_set_timeouts(bev_, read_timeout, write_timeout); } int ClientHandler::validate_next_proto() { const unsigned char *next_proto = 0; unsigned int next_proto_len; SSL_get0_next_proto_negotiated(ssl_, &next_proto, &next_proto_len); if(next_proto) { if(LOG_ENABLED(INFO)) { std::string proto(next_proto, next_proto+next_proto_len); CLOG(INFO, this) << "The negotiated next protocol: " << proto; } uint16_t version = spdylay_npn_get_version(next_proto, next_proto_len); if(version) { SpdyUpstream *spdy_upstream = new SpdyUpstream(version, this); upstream_ = spdy_upstream; return 0; } } else { if(LOG_ENABLED(INFO)) { CLOG(INFO, this) << "No proto negotiated."; } } if(LOG_ENABLED(INFO)) { CLOG(INFO, this) << "Use HTTP/1.1"; } HttpsUpstream *https_upstream = new HttpsUpstream(this); upstream_ = https_upstream; return 0; } int ClientHandler::on_read() { return upstream_->on_read(); } int ClientHandler::on_event() { return upstream_->on_event(); } const std::string& ClientHandler::get_ipaddr() const { return ipaddr_; } bool ClientHandler::get_should_close_after_write() const { return should_close_after_write_; } void ClientHandler::set_should_close_after_write(bool f) { should_close_after_write_ = f; } void ClientHandler::pool_downstream_connection(DownstreamConnection *dconn) { if(LOG_ENABLED(INFO)) { CLOG(INFO, this) << "Pooling downstream connection DCONN:" << dconn; } dconn_pool_.insert(dconn); } void ClientHandler::remove_downstream_connection(DownstreamConnection *dconn) { if(LOG_ENABLED(INFO)) { CLOG(INFO, this) << "Removing downstream connection DCONN:" << dconn << " from pool"; } dconn_pool_.erase(dconn); } DownstreamConnection* ClientHandler::get_downstream_connection() { if(dconn_pool_.empty()) { if(LOG_ENABLED(INFO)) { CLOG(INFO, this) << "Downstream connection pool is empty." << " Create new one"; } if(spdy_) { return new SpdyDownstreamConnection(this); } else { return new HttpDownstreamConnection(this); } } else { DownstreamConnection *dconn = *dconn_pool_.begin(); dconn_pool_.erase(dconn); if(LOG_ENABLED(INFO)) { CLOG(INFO, this) << "Reuse downstream connection DCONN:" << dconn << " from pool"; } return dconn; } } size_t ClientHandler::get_outbuf_length() { bufferevent *underlying = bufferevent_get_underlying(bev_); size_t len = evbuffer_get_length(bufferevent_get_output(bev_)); if(underlying) { len += evbuffer_get_length(bufferevent_get_output(underlying)); } return len; } SSL* ClientHandler::get_ssl() const { return ssl_; } void ClientHandler::set_spdy_session(SpdySession *spdy) { spdy_ = spdy; } SpdySession* ClientHandler::get_spdy_session() const { return spdy_; } void ClientHandler::set_tls_handshake(bool f) { tls_handshake_ = f; } bool ClientHandler::get_tls_handshake() const { return tls_handshake_; } void ClientHandler::set_tls_renegotiation(bool f) { tls_renegotiation_ = f; } bool ClientHandler::get_tls_renegotiation() const { return tls_renegotiation_; } } // namespace shrpx <commit_msg>shrpx: Call upstream_writecb when underlying bufferevent buffer gets empty<commit_after>/* * Spdylay - SPDY Library * * Copyright (c) 2012 Tatsuhiro Tsujikawa * * 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 "shrpx_client_handler.h" #include <unistd.h> #include <cerrno> #include "shrpx_upstream.h" #include "shrpx_spdy_upstream.h" #include "shrpx_https_upstream.h" #include "shrpx_config.h" #include "shrpx_http_downstream_connection.h" #include "shrpx_spdy_downstream_connection.h" #include "shrpx_accesslog.h" namespace shrpx { namespace { void upstream_readcb(bufferevent *bev, void *arg) { ClientHandler *handler = static_cast<ClientHandler*>(arg); int rv = handler->on_read(); if(rv != 0) { delete handler; } } } // namespace namespace { void upstream_writecb(bufferevent *bev, void *arg) { ClientHandler *handler = static_cast<ClientHandler*>(arg); // We actually depend on write low-warter mark == 0. if(handler->get_outbuf_length() > 0) { // Possibly because of deferred callback, we may get this callback // when the output buffer is not empty. return; } if(handler->get_should_close_after_write()) { delete handler; return; } Upstream *upstream = handler->get_upstream(); if(!upstream) { return; } int rv = upstream->on_write(); if(rv != 0) { delete handler; } } } // namespace namespace { void upstream_eventcb(bufferevent *bev, short events, void *arg) { ClientHandler *handler = static_cast<ClientHandler*>(arg); bool finish = false; if(events & BEV_EVENT_EOF) { if(LOG_ENABLED(INFO)) { CLOG(INFO, handler) << "EOF"; } finish = true; } if(events & BEV_EVENT_ERROR) { if(LOG_ENABLED(INFO)) { CLOG(INFO, handler) << "Network error: " << evutil_socket_error_to_string (EVUTIL_SOCKET_ERROR()); } finish = true; } if(events & BEV_EVENT_TIMEOUT) { if(LOG_ENABLED(INFO)) { CLOG(INFO, handler) << "Time out"; } finish = true; } if(finish) { delete handler; } else { if(events & BEV_EVENT_CONNECTED) { handler->set_tls_handshake(true); if(LOG_ENABLED(INFO)) { CLOG(INFO, handler) << "SSL/TLS handshake completed"; } handler->set_bev_cb(upstream_readcb, upstream_writecb, upstream_eventcb); handler->validate_next_proto(); if(LOG_ENABLED(INFO)) { if(SSL_session_reused(handler->get_ssl())) { CLOG(INFO, handler) << "SSL/TLS session reused"; } } // At this point, input buffer is already filled with some // bytes. The read callback is not called until new data // come. So consume input buffer here. handler->get_upstream()->on_read(); } } } } // namespace namespace { void tls_raw_readcb(evbuffer *buffer, const evbuffer_cb_info *info, void *arg) { ClientHandler *handler = static_cast<ClientHandler*>(arg); if(handler->get_tls_renegotiation()) { if(LOG_ENABLED(INFO)) { CLOG(INFO, handler) << "Close connection due to TLS renegotiation"; } delete handler; } } } // namespace namespace { void tls_raw_writecb(evbuffer *buffer, const evbuffer_cb_info *info, void *arg) { ClientHandler *handler = static_cast<ClientHandler*>(arg); // upstream_writecb() is called when external bufferevent // handler->bev's output buffer gets empty. But the underlying // bufferevent may have pending output buffer. upstream_writecb(handler->get_bev(), handler); } } // namespace ClientHandler::ClientHandler(bufferevent *bev, int fd, SSL *ssl, const char *ipaddr) : ipaddr_(ipaddr), bev_(bev), ssl_(ssl), upstream_(0), spdy_(0), fd_(fd), should_close_after_write_(false), tls_handshake_(false), tls_renegotiation_(false) { bufferevent_set_rate_limit(bev_, get_config()->rate_limit_cfg); bufferevent_enable(bev_, EV_READ | EV_WRITE); bufferevent_setwatermark(bev_, EV_READ, 0, SHRPX_READ_WARTER_MARK); set_upstream_timeouts(&get_config()->upstream_read_timeout, &get_config()->upstream_write_timeout); if(ssl_) { SSL_set_app_data(ssl_, reinterpret_cast<char*>(this)); set_bev_cb(0, upstream_writecb, upstream_eventcb); evbuffer *input = bufferevent_get_input(bufferevent_get_underlying(bev_)); evbuffer_add_cb(input, tls_raw_readcb, this); evbuffer *output = bufferevent_get_output(bufferevent_get_underlying(bev_)); evbuffer_add_cb(output, tls_raw_writecb, this); } else { if(get_config()->client_mode) { // Client mode upstream_ = new HttpsUpstream(this); } else { // no-TLS SPDY upstream_ = new SpdyUpstream(get_config()->spdy_upstream_version, this); } set_bev_cb(upstream_readcb, upstream_writecb, upstream_eventcb); } } ClientHandler::~ClientHandler() { if(LOG_ENABLED(INFO)) { CLOG(INFO, this) << "Deleting"; } if(ssl_) { SSL_set_app_data(ssl_, 0); SSL_set_shutdown(ssl_, SSL_RECEIVED_SHUTDOWN); SSL_shutdown(ssl_); } bufferevent *underlying = bufferevent_get_underlying(bev_); bufferevent_disable(bev_, EV_READ | EV_WRITE); bufferevent_free(bev_); if(underlying) { bufferevent_disable(underlying, EV_READ | EV_WRITE); bufferevent_free(underlying); } if(ssl_) { SSL_free(ssl_); } shutdown(fd_, SHUT_WR); close(fd_); delete upstream_; for(std::set<DownstreamConnection*>::iterator i = dconn_pool_.begin(); i != dconn_pool_.end(); ++i) { delete *i; } if(LOG_ENABLED(INFO)) { CLOG(INFO, this) << "Deleted"; } } Upstream* ClientHandler::get_upstream() { return upstream_; } bufferevent* ClientHandler::get_bev() const { return bev_; } event_base* ClientHandler::get_evbase() const { return bufferevent_get_base(bev_); } void ClientHandler::set_bev_cb (bufferevent_data_cb readcb, bufferevent_data_cb writecb, bufferevent_event_cb eventcb) { bufferevent_setcb(bev_, readcb, writecb, eventcb, this); } void ClientHandler::set_upstream_timeouts(const timeval *read_timeout, const timeval *write_timeout) { bufferevent_set_timeouts(bev_, read_timeout, write_timeout); } int ClientHandler::validate_next_proto() { const unsigned char *next_proto = 0; unsigned int next_proto_len; SSL_get0_next_proto_negotiated(ssl_, &next_proto, &next_proto_len); if(next_proto) { if(LOG_ENABLED(INFO)) { std::string proto(next_proto, next_proto+next_proto_len); CLOG(INFO, this) << "The negotiated next protocol: " << proto; } uint16_t version = spdylay_npn_get_version(next_proto, next_proto_len); if(version) { SpdyUpstream *spdy_upstream = new SpdyUpstream(version, this); upstream_ = spdy_upstream; return 0; } } else { if(LOG_ENABLED(INFO)) { CLOG(INFO, this) << "No proto negotiated."; } } if(LOG_ENABLED(INFO)) { CLOG(INFO, this) << "Use HTTP/1.1"; } HttpsUpstream *https_upstream = new HttpsUpstream(this); upstream_ = https_upstream; return 0; } int ClientHandler::on_read() { return upstream_->on_read(); } int ClientHandler::on_event() { return upstream_->on_event(); } const std::string& ClientHandler::get_ipaddr() const { return ipaddr_; } bool ClientHandler::get_should_close_after_write() const { return should_close_after_write_; } void ClientHandler::set_should_close_after_write(bool f) { should_close_after_write_ = f; } void ClientHandler::pool_downstream_connection(DownstreamConnection *dconn) { if(LOG_ENABLED(INFO)) { CLOG(INFO, this) << "Pooling downstream connection DCONN:" << dconn; } dconn_pool_.insert(dconn); } void ClientHandler::remove_downstream_connection(DownstreamConnection *dconn) { if(LOG_ENABLED(INFO)) { CLOG(INFO, this) << "Removing downstream connection DCONN:" << dconn << " from pool"; } dconn_pool_.erase(dconn); } DownstreamConnection* ClientHandler::get_downstream_connection() { if(dconn_pool_.empty()) { if(LOG_ENABLED(INFO)) { CLOG(INFO, this) << "Downstream connection pool is empty." << " Create new one"; } if(spdy_) { return new SpdyDownstreamConnection(this); } else { return new HttpDownstreamConnection(this); } } else { DownstreamConnection *dconn = *dconn_pool_.begin(); dconn_pool_.erase(dconn); if(LOG_ENABLED(INFO)) { CLOG(INFO, this) << "Reuse downstream connection DCONN:" << dconn << " from pool"; } return dconn; } } size_t ClientHandler::get_outbuf_length() { bufferevent *underlying = bufferevent_get_underlying(bev_); size_t len = evbuffer_get_length(bufferevent_get_output(bev_)); if(underlying) { len += evbuffer_get_length(bufferevent_get_output(underlying)); } return len; } SSL* ClientHandler::get_ssl() const { return ssl_; } void ClientHandler::set_spdy_session(SpdySession *spdy) { spdy_ = spdy; } SpdySession* ClientHandler::get_spdy_session() const { return spdy_; } void ClientHandler::set_tls_handshake(bool f) { tls_handshake_ = f; } bool ClientHandler::get_tls_handshake() const { return tls_handshake_; } void ClientHandler::set_tls_renegotiation(bool f) { tls_renegotiation_ = f; } bool ClientHandler::get_tls_renegotiation() const { return tls_renegotiation_; } } // namespace shrpx <|endoftext|>
<commit_before>/* libwpd * Copyright (C) 2003 William Lachance (william.lachance@sympatico.ca) * Copyright (C) 2003 Marc Maurer (j.m.maurer@student.utwente.nl) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * For further information visit http://libwpd.sourceforge.net */ /* "This product is not manufactured, approved, or supported by * Corel Corporation or Corel Corporation Limited." */ #include "WP5Parser.h" #include "WPXHeader.h" #include "WP5Part.h" #include "WP5HLListener.h" #include "WP5HLStylesListener.h" #include "libwpd_internal.h" #include "WPXTable.h" WP5Parser::WP5Parser(WPXInputStream *input, WPXHeader *header) : WPXParser(input, header) { } WP5Parser::~WP5Parser() { } void WP5Parser::parse(WPXInputStream *input, WP5HLListener *listener) { listener->startDocument(); input->seek(getHeader()->getDocumentOffset(), WPX_SEEK_SET); WPD_DEBUG_MSG(("WordPerfect: Starting document body parse (position = %ld)\n",(long)input->tell())); parseDocument(input, listener); listener->endDocument(); } // parseDocument: parses a document body (may call itself recursively, on other streams, or itself) void WP5Parser::parseDocument(WPXInputStream *input, WP5HLListener *listener) { while (!input->atEOS()) { uint8_t readVal; readVal = readU8(input); if (readVal == 0 || readVal == 0x7F || readVal == 0xFF) { // do nothing: this token is meaningless and is likely just corruption } else if (readVal >= (uint8_t)0x01 && readVal <= (uint8_t)0x1F) { // control characters switch (readVal) { case 0x0A: // hard new line listener->insertEOL(); break; case 0x0B: // soft new page listener->insertBreak(WPX_PAGE_BREAK); break; case 0x0C: // hard new page listener->insertBreak(WPX_PAGE_BREAK); break; case 0x0D: // soft new line listener->insertEOL(); break; default: // unsupported or undocumented token, ignore break; } } else if (readVal >= (uint8_t)0x20 && readVal <= (uint8_t)0x7E) { listener->insertCharacter( readVal ); } /* else if (readVal >= (uint8_t)0x80 && readVal <= (uint8_t)0xBF) { // single byte functions }*/ else { WP5Part *part = WP5Part::constructPart(input, readVal); if (part != NULL) { part->parse(listener); DELETEP(part); } } } } void WP5Parser::parse(WPXHLListenerImpl *listenerImpl) { WPXInputStream *input = getInput(); vector<WPXPageSpan *> pageList; WPXTableList tableList; try { // do a "first-pass" parse of the document // gather table border information, page properties (per-page) WP5HLStylesListener stylesListener(&pageList, &tableList); parse(input, &stylesListener); // second pass: here is where we actually send the messages to the target app // that are necessary to emit the body of the target document WP5HLListener listener(&pageList, listenerImpl); // FIXME: SHOULD BE CONTENT_LISTENER, AND SHOULD BE PASSED TABLE DATA! parse(input, &listener); // cleanup section: free the used resources for (vector<WPXPageSpan *>::iterator iterSpan = pageList.begin(); iterSpan != pageList.end(); iterSpan++) { delete *iterSpan; } } catch(FileException) { WPD_DEBUG_MSG(("WordPerfect: File Exception. Parse terminated prematurely.")); for (vector<WPXPageSpan *>::iterator iterSpan = pageList.begin(); iterSpan != pageList.end(); iterSpan++) { delete *iterSpan; } throw FileException(); } } <commit_msg>Changing the conversion of Soft returns and Soft Pages in WP5Parser<commit_after>/* libwpd * Copyright (C) 2003 William Lachance (william.lachance@sympatico.ca) * Copyright (C) 2003 Marc Maurer (j.m.maurer@student.utwente.nl) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * For further information visit http://libwpd.sourceforge.net */ /* "This product is not manufactured, approved, or supported by * Corel Corporation or Corel Corporation Limited." */ #include "WP5Parser.h" #include "WPXHeader.h" #include "WP5Part.h" #include "WP5HLListener.h" #include "WP5HLStylesListener.h" #include "libwpd_internal.h" #include "WPXTable.h" WP5Parser::WP5Parser(WPXInputStream *input, WPXHeader *header) : WPXParser(input, header) { } WP5Parser::~WP5Parser() { } void WP5Parser::parse(WPXInputStream *input, WP5HLListener *listener) { listener->startDocument(); input->seek(getHeader()->getDocumentOffset(), WPX_SEEK_SET); WPD_DEBUG_MSG(("WordPerfect: Starting document body parse (position = %ld)\n",(long)input->tell())); parseDocument(input, listener); listener->endDocument(); } // parseDocument: parses a document body (may call itself recursively, on other streams, or itself) void WP5Parser::parseDocument(WPXInputStream *input, WP5HLListener *listener) { while (!input->atEOS()) { uint8_t readVal; readVal = readU8(input); if (readVal == 0 || readVal == 0x7F || readVal == 0xFF) { // do nothing: this token is meaningless and is likely just corruption } else if (readVal >= (uint8_t)0x01 && readVal <= (uint8_t)0x1F) { // control characters switch (readVal) { case 0x0A: // hard new line listener->insertEOL(); break; case 0x0B: // soft new page (convert like space) listener->insertCharacter((uint16_t) ' '); break; case 0x0C: // hard new page listener->insertBreak(WPX_PAGE_BREAK); break; case 0x0D: // soft new line (convert like space) listener->insertCharacter((uint16_t) ' '); break; default: // unsupported or undocumented token, ignore break; } } else if (readVal >= (uint8_t)0x20 && readVal <= (uint8_t)0x7E) { listener->insertCharacter( readVal ); } /* else if (readVal >= (uint8_t)0x80 && readVal <= (uint8_t)0xBF) { // single byte functions }*/ else { WP5Part *part = WP5Part::constructPart(input, readVal); if (part != NULL) { part->parse(listener); DELETEP(part); } } } } void WP5Parser::parse(WPXHLListenerImpl *listenerImpl) { WPXInputStream *input = getInput(); vector<WPXPageSpan *> pageList; WPXTableList tableList; try { // do a "first-pass" parse of the document // gather table border information, page properties (per-page) WP5HLStylesListener stylesListener(&pageList, &tableList); parse(input, &stylesListener); // second pass: here is where we actually send the messages to the target app // that are necessary to emit the body of the target document WP5HLListener listener(&pageList, listenerImpl); // FIXME: SHOULD BE CONTENT_LISTENER, AND SHOULD BE PASSED TABLE DATA! parse(input, &listener); // cleanup section: free the used resources for (vector<WPXPageSpan *>::iterator iterSpan = pageList.begin(); iterSpan != pageList.end(); iterSpan++) { delete *iterSpan; } } catch(FileException) { WPD_DEBUG_MSG(("WordPerfect: File Exception. Parse terminated prematurely.")); for (vector<WPXPageSpan *>::iterator iterSpan = pageList.begin(); iterSpan != pageList.end(); iterSpan++) { delete *iterSpan; } throw FileException(); } } <|endoftext|>
<commit_before>#include <QtCore> #include <QGuiApplication> #include <QQmlApplicationEngine> #include <QQuickView> #include <QQmlContext> #include "automator.h" #include "ansystemdispatcher.h" #ifdef Q_OS_ANDROID #include <QtAndroidExtras/QAndroidJniObject> #include <QtAndroidExtras/QAndroidJniEnvironment> JNIEXPORT jint JNI_OnLoad(JavaVM* vm, void*) { Q_UNUSED(vm); qDebug("NativeInterface::JNI_OnLoad()"); // It must call this function within JNI_OnLoad to enable System Dispatcher ANSystemDispatcher::registerNatives(); /* Optional: Register your own service */ // Call quickandroid.example.ExampleService.start() QAndroidJniObject::callStaticMethod<void>("quickandroid/example/ExampleService", "start", "()V"); return JNI_VERSION_1_6; } #endif int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); QQmlApplicationEngine engine; engine.addImportPath("qrc:///"); engine.load(QUrl(QStringLiteral("qrc:///main.qml"))); /* Testing Code. Not needed for regular project */ Automator* automator = new Automator(); automator->start(); return app.exec(); } <commit_msg>tests/instrument/activity/main.cpp: Initial AndroidNative::SystemDispatcher<commit_after>#include <QtCore> #include <QGuiApplication> #include <QQmlApplicationEngine> #include <QQuickView> #include <QQmlContext> #include "automator.h" #include "AndroidNative/systemdispatcher.h" #ifdef Q_OS_ANDROID #include <QtAndroidExtras/QAndroidJniObject> #include <QtAndroidExtras/QAndroidJniEnvironment> using namespace AndroidNative; JNIEXPORT jint JNI_OnLoad(JavaVM* vm, void*) { Q_UNUSED(vm); qDebug("NativeInterface::JNI_OnLoad()"); // It must call this function within JNI_OnLoad to enable System Dispatcher SystemDispatcher::registerNatives(); /* Optional: Register your own service */ // Call quickandroid.example.ExampleService.start() QAndroidJniObject::callStaticMethod<void>("quickandroid/example/ExampleService", "start", "()V"); return JNI_VERSION_1_6; } #endif int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); QQmlApplicationEngine engine; engine.addImportPath("qrc:///"); engine.load(QUrl(QStringLiteral("qrc:///main.qml"))); /* Testing Code. Not needed for regular project */ Automator* automator = new Automator(); automator->start(); return app.exec(); } <|endoftext|>
<commit_before>#include <nanosoft/error.h> #include <nanosoft/xmlparser.h> #include <iostream> using namespace std; namespace nanosoft { /** * Конструктор */ XMLParser::XMLParser(): parsing(false), resetNeed(false) { initParser(); } /** * Деструктор */ XMLParser::~XMLParser() { XML_ParserFree(parser); } /** * Инициализация парсера */ void XMLParser::initParser() { parser = XML_ParserCreate((XML_Char *) "UTF-8"); if ( parser == 0 ) error("[XMLParser] XML_ParserCreate() fault"); XML_SetUserData(parser, (void*) this); XML_SetElementHandler(parser, startElementCallback, endElementCallback); XML_SetCharacterDataHandler(parser, characterDataCallback); } /** * Парсинг * @param buf буфер с данными * @param len длина буфера с данными * @param isFinal TRUE - последний кусок, FALSE - будет продолжение * @return TRUE - успешно, FALSE - ошибка парсинга */ bool XMLParser::parseXML(const char *buf, size_t len, bool isFinal) { cout << "\nparse: \033[22;31m" << string(buf, len) << "\033[0m\n"; parsing = true; int r = XML_Parse(parser, buf, len, isFinal); parsing = false; if ( resetNeed ) realResetParser(); else if ( ! r ) { onParseError(XML_ErrorString(XML_GetErrorCode(parser))); return false; } return true; } /** * Реальная переинициализация парсера */ void XMLParser::realResetParser() { XML_ParserFree(parser); initParser(); } /** * Сбросить парсер, начать парсить новый поток */ void XMLParser::resetParser() { if ( parsing ) resetNeed = true; else realResetParser(); } /** * Обработчик открытия тега */ void XMLParser::startElementCallback(void *user_data, const XML_Char *name, const XML_Char **atts) { attributtes_t attributes; for(int i = 0; atts[i]; i += 2) { attributes[ atts[i] ] = atts[i + 1]; } static_cast<XMLParser *>(user_data)->onStartElement(name, attributes); } /** * Отработчик символьных данных */ void XMLParser::characterDataCallback(void *user_data, const XML_Char *s, int len) { static_cast<XMLParser *>(user_data)->onCharacterData(string(s, len)); } /** * Отбработчик закрытия тега */ void XMLParser::endElementCallback(void *user_data, const XML_Char *name) { static_cast<XMLParser *>(user_data)->onEndElement(name); } } <commit_msg>fix: resetNeed = false после сброса парсера<commit_after>#include <nanosoft/error.h> #include <nanosoft/xmlparser.h> #include <iostream> using namespace std; namespace nanosoft { /** * Конструктор */ XMLParser::XMLParser(): parsing(false), resetNeed(false) { initParser(); } /** * Деструктор */ XMLParser::~XMLParser() { XML_ParserFree(parser); } /** * Инициализация парсера */ void XMLParser::initParser() { parser = XML_ParserCreate((XML_Char *) "UTF-8"); if ( parser == 0 ) error("[XMLParser] XML_ParserCreate() fault"); XML_SetUserData(parser, (void*) this); XML_SetElementHandler(parser, startElementCallback, endElementCallback); XML_SetCharacterDataHandler(parser, characterDataCallback); } /** * Парсинг * @param buf буфер с данными * @param len длина буфера с данными * @param isFinal TRUE - последний кусок, FALSE - будет продолжение * @return TRUE - успешно, FALSE - ошибка парсинга */ bool XMLParser::parseXML(const char *buf, size_t len, bool isFinal) { cout << "\nparse: \033[22;31m" << string(buf, len) << "\033[0m\n"; parsing = true; int r = XML_Parse(parser, buf, len, isFinal); parsing = false; if ( resetNeed ) realResetParser(); else if ( ! r ) { onParseError(XML_ErrorString(XML_GetErrorCode(parser))); return false; } return true; } /** * Реальная переинициализация парсера */ void XMLParser::realResetParser() { XML_ParserFree(parser); initParser(); resetNeed = false; } /** * Сбросить парсер, начать парсить новый поток */ void XMLParser::resetParser() { if ( parsing ) resetNeed = true; else realResetParser(); } /** * Обработчик открытия тега */ void XMLParser::startElementCallback(void *user_data, const XML_Char *name, const XML_Char **atts) { attributtes_t attributes; for(int i = 0; atts[i]; i += 2) { attributes[ atts[i] ] = atts[i + 1]; } static_cast<XMLParser *>(user_data)->onStartElement(name, attributes); } /** * Отработчик символьных данных */ void XMLParser::characterDataCallback(void *user_data, const XML_Char *s, int len) { static_cast<XMLParser *>(user_data)->onCharacterData(string(s, len)); } /** * Отбработчик закрытия тега */ void XMLParser::endElementCallback(void *user_data, const XML_Char *name) { static_cast<XMLParser *>(user_data)->onEndElement(name); } } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the Qt Build Suite. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include <string> #include <iostream> #include <fstream> using namespace std; bool displayTextFile(const string &dirPath, const string &fileName) { string fullPath = dirPath + fileName; ifstream istream(fullPath.c_str()); if (!istream.is_open()) { cout << "Cannot open " << fileName << endl; return false; } cout << "---" << fileName << "---" << endl; char buf[256]; unsigned int i = 1; while (istream.good()) { istream.getline(buf, sizeof(buf)); cout << i++ << ": " << buf << endl; } return true; } int main(int, char **argv) { string appPath(argv[0]); size_t i = appPath.find_last_of('/'); if (i == string::npos) i = appPath.find_last_of('\\'); if (i != string::npos) appPath.resize(i + 1); if (!displayTextFile(appPath, "foo.txt")) return 1; if (!displayTextFile(appPath, "bar.txt")) return 2; cout << "-------------" << endl; return 0; } <commit_msg>Tests: Fix transformer test plain execution on Windows<commit_after>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the Qt Build Suite. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include <string> #include <iostream> #include <fstream> using namespace std; bool displayTextFile(const string &dirPath, const string &fileName) { string fullPath = dirPath + fileName; ifstream istream(fullPath.c_str()); if (!istream.is_open()) { cout << "Cannot open " << fileName << endl; return false; } cout << "---" << fileName << "---" << endl; char buf[256]; unsigned int i = 1; while (istream.good()) { istream.getline(buf, sizeof(buf)); cout << i++ << ": " << buf << endl; } return true; } int main(int, char **argv) { string appPath(argv[0]); size_t i = appPath.find_last_of('/'); if (i == string::npos) i = appPath.find_last_of('\\'); if (i == string::npos) // No path, plain executable was called appPath.clear(); else appPath.resize(i + 1); if (!displayTextFile(appPath, "foo.txt")) return 1; if (!displayTextFile(appPath, "bar.txt")) return 2; cout << "-------------" << endl; return 0; } <|endoftext|>
<commit_before>// Ignore unused parameter warnings coming from cppunit headers #include <libmesh/ignore_warnings.h> #include <cppunit/extensions/HelperMacros.h> #include <cppunit/TestCase.h> #include <libmesh/restore_warnings.h> // libmesh includes #include <libmesh/dense_matrix.h> #include <libmesh/dense_vector.h> #ifdef LIBMESH_HAVE_PETSC #include "libmesh/petsc_macro.h" #endif // THE CPPUNIT_TEST_SUITE_END macro expands to code that involves // std::auto_ptr, which in turn produces -Wdeprecated-declarations // warnings. These can be ignored in GCC as long as we wrap the // offending code in appropriate pragmas. We can't get away with a // single ignore_warnings.h inclusion at the beginning of this file, // since the libmesh headers pull in a restore_warnings.h at some // point. We also don't bother restoring warnings at the end of this // file since it's not a header. #include <libmesh/ignore_warnings.h> using namespace libMesh; class DenseMatrixTest : public CppUnit::TestCase { public: void setUp() {} void tearDown() {} CPPUNIT_TEST_SUITE(DenseMatrixTest); CPPUNIT_TEST(testSVD); CPPUNIT_TEST(testEVDreal); CPPUNIT_TEST(testEVDcomplex); CPPUNIT_TEST(testComplexSVD); CPPUNIT_TEST_SUITE_END(); private: void testSVD() { DenseMatrix<Number> U, VT; DenseVector<Real> sigma; DenseMatrix<Number> A; A.resize(3, 2); A(0,0) = 1.0; A(0,1) = 2.0; A(1,0) = 3.0; A(1,1) = 4.0; A(2,0) = 5.0; A(2,1) = 6.0; A.svd(sigma, U, VT); // Solution for this case is (verified with numpy) DenseMatrix<Number> true_U(3,2), true_VT(2,2); DenseVector<Real> true_sigma(2); true_U(0,0) = -2.298476964000715e-01; true_U(0,1) = 8.834610176985250e-01; true_U(1,0) = -5.247448187602936e-01; true_U(1,1) = 2.407824921325463e-01; true_U(2,0) = -8.196419411205157e-01; true_U(2,1) = -4.018960334334318e-01; true_VT(0,0) = -6.196294838293402e-01; true_VT(0,1) = -7.848944532670524e-01; true_VT(1,0) = -7.848944532670524e-01; true_VT(1,1) = 6.196294838293400e-01; true_sigma(0) = 9.525518091565109e+00; true_sigma(1) = 5.143005806586446e-01; for (unsigned i=0; i<U.m(); ++i) for (unsigned j=0; j<U.n(); ++j) CPPUNIT_ASSERT_DOUBLES_EQUAL( libmesh_real(U(i,j)), libmesh_real(true_U(i,j)), TOLERANCE*TOLERANCE); for (unsigned i=0; i<VT.m(); ++i) for (unsigned j=0; j<VT.n(); ++j) CPPUNIT_ASSERT_DOUBLES_EQUAL( libmesh_real(VT(i,j)), libmesh_real(true_VT(i,j)), TOLERANCE*TOLERANCE); for (unsigned i=0; i<sigma.size(); ++i) CPPUNIT_ASSERT_DOUBLES_EQUAL(sigma(i), true_sigma(i), TOLERANCE*TOLERANCE); } // This function is called by testEVD for different matrices. The // Lapack results are compared to known eigenvalue real and // imaginary parts for the matrix in question, which must also be // passed in by non-const value, since this routine will sort them // in-place. void testEVD_helper(DenseMatrix<Real> & A, std::vector<Real> true_lambda_real, std::vector<Real> true_lambda_imag) { // Note: see bottom of this file, we only do this test if PETSc is // available, but this function currently only exists if we're // using real numbers. #ifdef LIBMESH_USE_REAL_NUMBERS DenseVector<Real> lambda_real, lambda_imag; A.evd(lambda_real, lambda_imag); // Sort the results from Lapack *individually*. std::sort(lambda_real.get_values().begin(), lambda_real.get_values().end()); std::sort(lambda_imag.get_values().begin(), lambda_imag.get_values().end()); // Sort the true eigenvalues *individually*. std::sort(true_lambda_real.begin(), true_lambda_real.end()); std::sort(true_lambda_imag.begin(), true_lambda_imag.end()); // Compare the individually-sorted values. for (unsigned i=0; i<lambda_real.size(); ++i) { CPPUNIT_ASSERT_DOUBLES_EQUAL(lambda_real(i), true_lambda_real[i], TOLERANCE*TOLERANCE); CPPUNIT_ASSERT_DOUBLES_EQUAL(lambda_imag(i), true_lambda_imag[i], TOLERANCE*TOLERANCE); } #endif } void testEVDreal() { // This is an example from Matlab's gallery(3) which is a // non-symmetric 3x3 matrix with eigen values lambda = 1, 2, 3. DenseMatrix<Real> A(3, 3); A(0,0) = -149; A(0,1) = -50; A(0,2) = -154; A(1,0) = 537; A(1,1) = 180; A(1,2) = 546; A(2,0) = -27; A(2,1) = -9; A(2,2) = -25; std::vector<Real> true_lambda_real(3); true_lambda_real[0] = 1.; true_lambda_real[1] = 2.; true_lambda_real[2] = 3.; std::vector<Real> true_lambda_imag(3); // all zero // call helper function to compute and verify results testEVD_helper(A, true_lambda_real, true_lambda_imag); } void testEVDcomplex() { // This test is also from a Matlab example, and has complex eigenvalues. // http://www.mathworks.com/help/matlab/math/eigenvalues.html?s_tid=gn_loc_drop DenseMatrix<Real> A(3, 3); A(0,0) = 0; A(0,1) = -6; A(0,2) = -1; A(1,0) = 6; A(1,1) = 2; A(1,2) = -16; A(2,0) = -5; A(2,1) = 20; A(2,2) = -10; std::vector<Real> true_lambda_real(3); true_lambda_real[0] = -3.070950351248293; true_lambda_real[1] = -2.464524824375853; true_lambda_real[2] = -2.464524824375853; std::vector<Real> true_lambda_imag(3); true_lambda_imag[0] = 0.; true_lambda_imag[1] = 17.60083096447099; true_lambda_imag[2] = -17.60083096447099; // call helper function to compute and verify results testEVD_helper(A, true_lambda_real, true_lambda_imag); } void testComplexSVD() { #ifdef LIBMESH_USE_COMPLEX_NUMBERS DenseMatrix<Complex> A(3,3); A(0,0) = Complex(2.18904,4.44523e-18); A(0,1) = Complex(-3.20491,-0.136699); A(0,2) = Complex(0.716316,-0.964802); A(1,0) = Complex(-3.20491,0.136699); A(1,1) = Complex(4.70076,-3.25261e-18); A(1,2) = Complex(-0.98849,1.45727); A(2,0) = Complex(0.716316,0.964802); A(2,1) = Complex(-0.98849,-1.45727); A(2,2) = Complex(0.659629,-4.01155e-18); DenseVector<Real> sigma; A.svd(sigma); DenseVector<Real> true_sigma(3); true_sigma(0) = 7.54942516052; true_sigma(1) = 3.17479511368e-06; true_sigma(2) = 6.64680908281e-07; for (unsigned i=0; i<sigma.size(); ++i) CPPUNIT_ASSERT_DOUBLES_EQUAL(sigma(i), true_sigma(i), 1.e-10); #endif } }; // Only run the test if we expect it can actually work! #ifdef LIBMESH_HAVE_PETSC #if !PETSC_VERSION_LESS_THAN(3,1,0) CPPUNIT_TEST_SUITE_REGISTRATION(DenseMatrixTest); #endif #endif <commit_msg>Add unit test verifying left and right eigenvector calculation.<commit_after>// Ignore unused parameter warnings coming from cppunit headers #include <libmesh/ignore_warnings.h> #include <cppunit/extensions/HelperMacros.h> #include <cppunit/TestCase.h> #include <libmesh/restore_warnings.h> // libmesh includes #include <libmesh/dense_matrix.h> #include <libmesh/dense_vector.h> #ifdef LIBMESH_HAVE_PETSC #include "libmesh/petsc_macro.h" #endif // THE CPPUNIT_TEST_SUITE_END macro expands to code that involves // std::auto_ptr, which in turn produces -Wdeprecated-declarations // warnings. These can be ignored in GCC as long as we wrap the // offending code in appropriate pragmas. We can't get away with a // single ignore_warnings.h inclusion at the beginning of this file, // since the libmesh headers pull in a restore_warnings.h at some // point. We also don't bother restoring warnings at the end of this // file since it's not a header. #include <libmesh/ignore_warnings.h> using namespace libMesh; class DenseMatrixTest : public CppUnit::TestCase { public: void setUp() {} void tearDown() {} CPPUNIT_TEST_SUITE(DenseMatrixTest); CPPUNIT_TEST(testSVD); CPPUNIT_TEST(testEVDreal); CPPUNIT_TEST(testEVDcomplex); CPPUNIT_TEST(testComplexSVD); CPPUNIT_TEST_SUITE_END(); private: void testSVD() { DenseMatrix<Number> U, VT; DenseVector<Real> sigma; DenseMatrix<Number> A; A.resize(3, 2); A(0,0) = 1.0; A(0,1) = 2.0; A(1,0) = 3.0; A(1,1) = 4.0; A(2,0) = 5.0; A(2,1) = 6.0; A.svd(sigma, U, VT); // Solution for this case is (verified with numpy) DenseMatrix<Number> true_U(3,2), true_VT(2,2); DenseVector<Real> true_sigma(2); true_U(0,0) = -2.298476964000715e-01; true_U(0,1) = 8.834610176985250e-01; true_U(1,0) = -5.247448187602936e-01; true_U(1,1) = 2.407824921325463e-01; true_U(2,0) = -8.196419411205157e-01; true_U(2,1) = -4.018960334334318e-01; true_VT(0,0) = -6.196294838293402e-01; true_VT(0,1) = -7.848944532670524e-01; true_VT(1,0) = -7.848944532670524e-01; true_VT(1,1) = 6.196294838293400e-01; true_sigma(0) = 9.525518091565109e+00; true_sigma(1) = 5.143005806586446e-01; for (unsigned i=0; i<U.m(); ++i) for (unsigned j=0; j<U.n(); ++j) CPPUNIT_ASSERT_DOUBLES_EQUAL( libmesh_real(U(i,j)), libmesh_real(true_U(i,j)), TOLERANCE*TOLERANCE); for (unsigned i=0; i<VT.m(); ++i) for (unsigned j=0; j<VT.n(); ++j) CPPUNIT_ASSERT_DOUBLES_EQUAL( libmesh_real(VT(i,j)), libmesh_real(true_VT(i,j)), TOLERANCE*TOLERANCE); for (unsigned i=0; i<sigma.size(); ++i) CPPUNIT_ASSERT_DOUBLES_EQUAL(sigma(i), true_sigma(i), TOLERANCE*TOLERANCE); } // This function is called by testEVD for different matrices. The // Lapack results are compared to known eigenvalue real and // imaginary parts for the matrix in question, which must also be // passed in by non-const value, since this routine will sort them // in-place. void testEVD_helper(DenseMatrix<Real> & A, std::vector<Real> true_lambda_real, std::vector<Real> true_lambda_imag) { // Note: see bottom of this file, we only do this test if PETSc is // available, but this function currently only exists if we're // using real numbers. #ifdef LIBMESH_USE_REAL_NUMBERS // Let's compute the eigenvalues on a copy of A, so that we can // use the original to check the computation. DenseMatrix<Real> A_copy = A; DenseVector<Real> lambda_real, lambda_imag; DenseMatrix<Real> VR; // right eigenvectors DenseMatrix<Real> VL; // left eigenvectors A_copy.evd_left_and_right(lambda_real, lambda_imag, VL, VR); // The matrix is square and of size N x N. const unsigned N = A.m(); // Verify left eigen-values. // Test that the right eigenvalues are self-consistent by computing // u_j**H * A = lambda_j * u_j**H // Note that we have to handle real and complex eigenvalues // differently, since complex eigenvectors share their storage. for (unsigned eigenval=0; eigenval<N; ++eigenval) { // Only check real eigenvalues if (std::abs(lambda_imag(eigenval)) < TOLERANCE*TOLERANCE) { // remove print libMesh::out << "Checking eigenvalue: " << eigenval << std::endl; DenseVector<Real> lhs(N), rhs(N); for (unsigned i=0; i<N; ++i) { rhs(i) = lambda_real(eigenval) * VL(i, eigenval); for (unsigned j=0; j<N; ++j) lhs(i) += A(j, i) * VL(j, eigenval); // Note: A(j,i) } // Subtract and assert that the norm of the difference is // below some tolerance. lhs -= rhs; CPPUNIT_ASSERT_DOUBLES_EQUAL(/*expected=*/0., /*actual=*/lhs.l2_norm(), std::sqrt(TOLERANCE)*TOLERANCE); } else { // This is a complex eigenvalue, so: // a.) It occurs in a complex-conjugate pair // b.) the real part of the eigenvector is stored is VL(:,eigenval) // c.) the imag part of the eigenvector is stored in VL(:,eigenval+1) // // Equating the real and imaginary parts of Ax=lambda*x leads to two sets // of relations that must hold: // 1.) A^T x_r = lambda_r*x_r + lambda_i*x_i // 2.) A^T x_i = -lambda_i*x_r + lambda_r*x_i // which we can verify. // 1.) DenseVector<Real> lhs(N), rhs(N); for (unsigned i=0; i<N; ++i) { rhs(i) = lambda_real(eigenval) * VL(i, eigenval) + lambda_imag(eigenval) * VL(i, eigenval+1); for (unsigned j=0; j<N; ++j) lhs(i) += A(j, i) * VL(j, eigenval); // Note: A(j,i) } lhs -= rhs; CPPUNIT_ASSERT_DOUBLES_EQUAL(/*expected=*/0., /*actual=*/lhs.l2_norm(), std::sqrt(TOLERANCE)*TOLERANCE); // libMesh::out << "lhs=" << std::endl; // lhs.print_scientific(libMesh::out, /*precision=*/15); // // libMesh::out << "rhs=" << std::endl; // rhs.print_scientific(libMesh::out, /*precision=*/15); // 2.) lhs.zero(); rhs.zero(); for (unsigned i=0; i<N; ++i) { rhs(i) = -lambda_imag(eigenval) * VL(i, eigenval) + lambda_real(eigenval) * VL(i, eigenval+1); for (unsigned j=0; j<N; ++j) lhs(i) += A(j, i) * VL(j, eigenval+1); // Note: A(j,i) } lhs -= rhs; CPPUNIT_ASSERT_DOUBLES_EQUAL(/*expected=*/0., /*actual=*/lhs.l2_norm(), std::sqrt(TOLERANCE)*TOLERANCE); // libMesh::out << "lhs=" << std::endl; // lhs.print_scientific(libMesh::out, /*precision=*/15); // // libMesh::out << "rhs=" << std::endl; // rhs.print_scientific(libMesh::out, /*precision=*/15); // We'll skip the second member of the complex conjugate // pair. If the first one worked, the second one should // as well... eigenval += 1; } } // Verify right eigen-values. // Test that the right eigenvalues are self-consistent by computing // A * v_j - lambda_j * v_j // Note that we have to handle real and complex eigenvalues // differently, since complex eigenvectors share their storage. for (unsigned eigenval=0; eigenval<N; ++eigenval) { // Only check real eigenvalues if (std::abs(lambda_imag(eigenval)) < TOLERANCE*TOLERANCE) { // remove print libMesh::out << "Checking eigenvalue: " << eigenval << std::endl; DenseVector<Real> lhs(N), rhs(N); for (unsigned i=0; i<N; ++i) { rhs(i) = lambda_real(eigenval) * VR(i, eigenval); for (unsigned j=0; j<N; ++j) lhs(i) += A(i, j) * VR(j, eigenval); } lhs -= rhs; CPPUNIT_ASSERT_DOUBLES_EQUAL(/*expected=*/0., /*actual=*/lhs.l2_norm(), std::sqrt(TOLERANCE)*TOLERANCE); } else { // This is a complex eigenvalue, so: // a.) It occurs in a complex-conjugate pair // b.) the real part of the eigenvector is stored is VR(:,eigenval) // c.) the imag part of the eigenvector is stored in VR(:,eigenval+1) // // Equating the real and imaginary parts of Ax=lambda*x leads to two sets // of relations that must hold: // 1.) Ax_r = lambda_r*x_r - lambda_i*x_i // 2.) Ax_i = lambda_i*x_r + lambda_r*x_i // which we can verify. // 1.) DenseVector<Real> lhs(N), rhs(N); for (unsigned i=0; i<N; ++i) { rhs(i) = lambda_real(eigenval) * VR(i, eigenval) - lambda_imag(eigenval) * VR(i, eigenval+1); for (unsigned j=0; j<N; ++j) lhs(i) += A(i, j) * VR(j, eigenval); } lhs -= rhs; CPPUNIT_ASSERT_DOUBLES_EQUAL(/*expected=*/0., /*actual=*/lhs.l2_norm(), std::sqrt(TOLERANCE)*TOLERANCE); // 2.) lhs.zero(); rhs.zero(); for (unsigned i=0; i<N; ++i) { rhs(i) = lambda_imag(eigenval) * VR(i, eigenval) + lambda_real(eigenval) * VR(i, eigenval+1); for (unsigned j=0; j<N; ++j) lhs(i) += A(i, j) * VR(j, eigenval+1); } lhs -= rhs; CPPUNIT_ASSERT_DOUBLES_EQUAL(/*expected=*/0., /*actual=*/lhs.l2_norm(), std::sqrt(TOLERANCE)*TOLERANCE); // We'll skip the second member of the complex conjugate // pair. If the first one worked, the second one should // as well... eigenval += 1; } } // Sort the results from Lapack *individually*. std::sort(lambda_real.get_values().begin(), lambda_real.get_values().end()); std::sort(lambda_imag.get_values().begin(), lambda_imag.get_values().end()); // Sort the true eigenvalues *individually*. std::sort(true_lambda_real.begin(), true_lambda_real.end()); std::sort(true_lambda_imag.begin(), true_lambda_imag.end()); // Compare the individually-sorted values. for (unsigned i=0; i<lambda_real.size(); ++i) { // Note: I initially verified the results with TOLERANCE**2, // but that turned out to be just a bit too tight for some of // the test problems. I'm not sure what controls the accuracy // of the eigenvalue computation in LAPACK, there is no way to // set a tolerance in the LAPACKgeev_ interface. CPPUNIT_ASSERT_DOUBLES_EQUAL(/*expected=*/true_lambda_real[i], /*actual=*/lambda_real(i), std::sqrt(TOLERANCE)*TOLERANCE); CPPUNIT_ASSERT_DOUBLES_EQUAL(/*expected=*/true_lambda_imag[i], /*actual=*/lambda_imag(i), std::sqrt(TOLERANCE)*TOLERANCE); } #endif } void testEVDreal() { // This is an example from Matlab's gallery(3) which is a // non-symmetric 3x3 matrix with eigen values lambda = 1, 2, 3. DenseMatrix<Real> A(3, 3); A(0,0) = -149; A(0,1) = -50; A(0,2) = -154; A(1,0) = 537; A(1,1) = 180; A(1,2) = 546; A(2,0) = -27; A(2,1) = -9; A(2,2) = -25; std::vector<Real> true_lambda_real(3); true_lambda_real[0] = 1.; true_lambda_real[1] = 2.; true_lambda_real[2] = 3.; std::vector<Real> true_lambda_imag(3); // all zero // call helper function to compute and verify results. testEVD_helper(A, true_lambda_real, true_lambda_imag); } void testEVDcomplex() { // This test is also from a Matlab example, and has complex eigenvalues. // http://www.mathworks.com/help/matlab/math/eigenvalues.html?s_tid=gn_loc_drop DenseMatrix<Real> A(3, 3); A(0,0) = 0; A(0,1) = -6; A(0,2) = -1; A(1,0) = 6; A(1,1) = 2; A(1,2) = -16; A(2,0) = -5; A(2,1) = 20; A(2,2) = -10; std::vector<Real> true_lambda_real(3); true_lambda_real[0] = -3.070950351248293; true_lambda_real[1] = -2.464524824375853; true_lambda_real[2] = -2.464524824375853; std::vector<Real> true_lambda_imag(3); true_lambda_imag[0] = 0.; true_lambda_imag[1] = 17.60083096447099; true_lambda_imag[2] = -17.60083096447099; // call helper function to compute and verify results testEVD_helper(A, true_lambda_real, true_lambda_imag); } void testComplexSVD() { #ifdef LIBMESH_USE_COMPLEX_NUMBERS DenseMatrix<Complex> A(3,3); A(0,0) = Complex(2.18904,4.44523e-18); A(0,1) = Complex(-3.20491,-0.136699); A(0,2) = Complex(0.716316,-0.964802); A(1,0) = Complex(-3.20491,0.136699); A(1,1) = Complex(4.70076,-3.25261e-18); A(1,2) = Complex(-0.98849,1.45727); A(2,0) = Complex(0.716316,0.964802); A(2,1) = Complex(-0.98849,-1.45727); A(2,2) = Complex(0.659629,-4.01155e-18); DenseVector<Real> sigma; A.svd(sigma); DenseVector<Real> true_sigma(3); true_sigma(0) = 7.54942516052; true_sigma(1) = 3.17479511368e-06; true_sigma(2) = 6.64680908281e-07; for (unsigned i=0; i<sigma.size(); ++i) CPPUNIT_ASSERT_DOUBLES_EQUAL(sigma(i), true_sigma(i), 1.e-10); #endif } }; // Only run the test if we expect it can actually work! #ifdef LIBMESH_HAVE_PETSC #if !PETSC_VERSION_LESS_THAN(3,1,0) CPPUNIT_TEST_SUITE_REGISTRATION(DenseMatrixTest); #endif #endif <|endoftext|>
<commit_before>#define CATCH_CONFIG_MAIN #include "../../vendor/catch/catch.hpp" #include "thread_utility.hpp" #include "version_monitor.hpp" TEST_CASE("initialize") { krbn::thread_utility::register_main_thread(); } TEST_CASE("file_monitor") { system("rm -rf target"); system("mkdir -p target/sub/"); system("echo 1.0.0 > target/sub/version"); { krbn::version_monitor version_monitor("target/sub/version"); std::string last_changed_version; version_monitor.changed.connect([&](auto&& version) { last_changed_version = version; }); version_monitor.start(); std::this_thread::sleep_for(std::chrono::milliseconds(500)); REQUIRE(last_changed_version.empty()); // ======================================== // Update version // ======================================== last_changed_version.clear(); system("echo 1.1.0 > target/sub/version"); std::this_thread::sleep_for(std::chrono::milliseconds(500)); REQUIRE(last_changed_version == "1.1.0"); // ======================================== // The callback is not called if the file contents is not changed. // ======================================== last_changed_version.clear(); system("touch target/sub/version"); std::this_thread::sleep_for(std::chrono::milliseconds(500)); REQUIRE(last_changed_version.empty()); // ======================================== // `manual_check` does not invoke callback if the version file is not actually changed. // ======================================== last_changed_version.clear(); version_monitor.manual_check(); std::this_thread::sleep_for(std::chrono::milliseconds(500)); REQUIRE(last_changed_version.empty()); // ======================================== // Self update is ignored by `kFSEventStreamCreateFlagIgnoreSelf` // ======================================== last_changed_version.clear(); { std::ofstream("target/sub/version") << "1.2.0"; } std::this_thread::sleep_for(std::chrono::milliseconds(500)); REQUIRE(last_changed_version.empty()); // ======================================== // `manual_check` // ======================================== last_changed_version.clear(); version_monitor.manual_check(); std::this_thread::sleep_for(std::chrono::milliseconds(500)); REQUIRE(last_changed_version == "1.2.0"); // ======================================== // Update version again // ======================================== last_changed_version.clear(); system("echo 1.3.0 > target/sub/version"); std::this_thread::sleep_for(std::chrono::milliseconds(500)); REQUIRE(last_changed_version == "1.3.0"); } } <commit_msg>fix TEST_CASE name<commit_after>#define CATCH_CONFIG_MAIN #include "../../vendor/catch/catch.hpp" #include "thread_utility.hpp" #include "version_monitor.hpp" TEST_CASE("initialize") { krbn::thread_utility::register_main_thread(); } TEST_CASE("version_monitor") { system("rm -rf target"); system("mkdir -p target/sub/"); system("echo 1.0.0 > target/sub/version"); { krbn::version_monitor version_monitor("target/sub/version"); std::string last_changed_version; version_monitor.changed.connect([&](auto&& version) { last_changed_version = version; }); version_monitor.start(); std::this_thread::sleep_for(std::chrono::milliseconds(500)); REQUIRE(last_changed_version.empty()); // ======================================== // Update version // ======================================== last_changed_version.clear(); system("echo 1.1.0 > target/sub/version"); std::this_thread::sleep_for(std::chrono::milliseconds(500)); REQUIRE(last_changed_version == "1.1.0"); // ======================================== // The callback is not called if the file contents is not changed. // ======================================== last_changed_version.clear(); system("touch target/sub/version"); std::this_thread::sleep_for(std::chrono::milliseconds(500)); REQUIRE(last_changed_version.empty()); // ======================================== // `manual_check` does not invoke callback if the version file is not actually changed. // ======================================== last_changed_version.clear(); version_monitor.manual_check(); std::this_thread::sleep_for(std::chrono::milliseconds(500)); REQUIRE(last_changed_version.empty()); // ======================================== // Self update is ignored by `kFSEventStreamCreateFlagIgnoreSelf` // ======================================== last_changed_version.clear(); { std::ofstream("target/sub/version") << "1.2.0"; } std::this_thread::sleep_for(std::chrono::milliseconds(500)); REQUIRE(last_changed_version.empty()); // ======================================== // `manual_check` // ======================================== last_changed_version.clear(); version_monitor.manual_check(); std::this_thread::sleep_for(std::chrono::milliseconds(500)); REQUIRE(last_changed_version == "1.2.0"); // ======================================== // Update version again // ======================================== last_changed_version.clear(); system("echo 1.3.0 > target/sub/version"); std::this_thread::sleep_for(std::chrono::milliseconds(500)); REQUIRE(last_changed_version == "1.3.0"); } } <|endoftext|>
<commit_before>/* * Database.cpp * * Created on: 21 Aug 2013 * Author: nicholas */ #include "../include/Database.hpp" #include <string> #include <odb/transaction.hxx> #include <odb/result.hxx> #include <odb/schema-catalog.hxx> #include <odb/sqlite/exceptions.hxx> #include "table/ImageRecord.hpp" #include "table/ImageRecord-odb.hxx" #include "table/FilterRecord.hpp" #include "table/FilterRecord-odb.hxx" const char *dbName = "imageHasher.db"; const char *insertImageQuery = "INSERT INTO `imagerecord` (`path`,`sha_id`,`phash_id`) VALUES (?,?,?);"; const char *insertInvalidQuery = "INSERT INTO `badfilerecord` (`path`) VALUES (?);"; const char *insertFilterQuery = "INSERT OR IGNORE INTO `filterrecord` (`phash_id`, `reason`) VALUES (?,?);"; const char *prunePathQuery = "SELECT `path` FROM `imagerecord` WHERE `path` LIKE ? UNION SELECT `path` FROM `badfilerecord` WHERE `path` LIKE ?;"; const char *prunePathDeleteImage = "DELETE FROM `imagerecord` WHERE `path` = ?;"; const char *prunePathDeleteBadFile = "DELETE FROM `badfilerecord` WHERE `path` = ?;"; const char *checkExistsQuery = "SELECT EXISTS(SELECT 1 FROM `imagerecord` WHERE `path` = ? LIMIT 1) OR EXISTS(SELECT 1 FROM `badfilerecord` WHERE `path` = ? LIMIT 1);"; const char *checkSHAQuery = "SELECT EXISTS(SELECT 1 FROM `imagerecord` JOIN `sha_hash` ON `sha_id`= `id` WHERE `path` = ? AND `sha256` != '' LIMIT 1);"; const char *updateSha = "UPDATE `imagerecord` SET `sha_id`=? WHERE `path` = ?;"; const char *getSHAQuery = "SELECT `sha256` FROM `imagerecord` AS ir JOIN `sha_hash` AS h ON ir.sha_id=h.id WHERE `path` = ?;"; const char *getPhashQuery = "SELECT `pHash` FROM `imagerecord` AS ir JOIN `phash_hash` AS h ON ir.sha_id=h.id WHERE `path` = ?;"; const char *getSHAidQuery = "SELECT `id` FROM `sha_hash` WHERE `sha256`= ?;"; const char *getpHashidQuery = "SELECT `id` FROM `phash_hash` WHERE `pHash`= ?;"; const char *insertShaRecordQuery = "INSERT INTO `sha_hash` (`sha256`) VALUES (?);"; const char *insertpHashRecordQuery = "INSERT INTO `phash_hash` (`pHash`) VALUES (?);"; const char *startTransactionQuery = "BEGIN TRANSACTION;"; const char *commitTransactionQuery = "COMMIT TRANSACTION;"; using namespace odb; using namespace imageHasher::db::table; Database::Database(const char* dbPath) { dbName = dbPath; init(); } Database::Database() { init(); } Database::~Database() { shutdown(); delete orm_db; } int Database::flush() { int drainCount = 0; LOG4CPLUS_INFO(logger, "Flushing lists..."); drainCount = drain(); drainCount += drain(); return drainCount; } void Database::shutdown() { if (running) { LOG4CPLUS_INFO(logger, "Shutting down..."); running = false; LOG4CPLUS_INFO(logger, "Waiting for db worker to finish..."); workerThread->interrupt(); workerThread->join(); LOG4CPLUS_INFO(logger, "Closing database..."); } } void Database::exec(const char* command) { orm_db->execute(command); } void Database::init() { boost::mutex::scoped_lock lock(dbMutex); this->currentList = &dataA; this->recordsWritten = 0; this->running = true; logger = log4cplus::Logger::getInstance(LOG4CPLUS_TEXT("Database")); setupDatabase(); prepareStatements(); workerThread = new boost::thread(&Database::doWork, this); } bool Database::is_db_initialised() { Hash hash; bool exists = true; transaction t(orm_db->begin()); try { exists = orm_db->find(1, hash); } catch (odb::sqlite::database_exception& e) { exists = false; } t.commit(); return exists; } void Database::initialise_db() { transaction t(orm_db->begin()); odb: schema_catalog::create_schema(*orm_db, "", false); t.commit(); addHashEntry("", 0); } void Database::setupDatabase() { orm_db = new sqlite::database(dbName,SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE); LOG4CPLUS_INFO(logger, "Setting up database " << dbName); bool init_done = is_db_initialised(); if(! init_done) { initialise_db(); } transaction t_pragma (orm_db->begin()); orm_db->execute("PRAGMA page_size = 4096;"); orm_db->execute("PRAGMA cache_size=10000;"); orm_db->execute("PRAGMA locking_mode=EXCLUSIVE;"); orm_db->execute("PRAGMA temp_store = MEMORY;"); orm_db->execute("PRAGMA journal_mode=MEMORY;"); t_pragma.commit(); // perform out of transaction execution connection_ptr c (orm_db->connection()); c->execute("PRAGMA synchronous=NORMAL;"); } void Database::add(db_data data) { boost::mutex::scoped_lock lock(flipMutex); currentList->push_back(data); } void Database::flipLists() { boost::mutex::scoped_lock lock(flipMutex); if(currentList == &dataA) { currentList = &dataB; }else{ currentList = &dataA; } } int Database::drain() { boost::mutex::scoped_lock lock(dbMutex); std::list<db_data>* workList; int drainCount = 0; workList = currentList; flipLists(); for(std::list<db_data>::iterator ite = workList->begin(); ite != workList->end(); ++ite) { addToBatch(*ite); recordsWritten++; drainCount++; } workList->clear(); return drainCount; } bool Database::entryExists(fs::path filePath) { LOG4CPLUS_DEBUG(logger, "Looking for file " << filePath); ImageRecord ir = get_imagerecord(filePath); return ir.is_valid(); } bool Database::entryExists(db_data data) { return entryExists(data.filePath); } std::list<fs::path> Database::getFilesWithPath(fs::path directoryPath) { std::list<fs::path> filePaths; std::string path_query(directoryPath.string()); path_query += "%"; LOG4CPLUS_INFO(logger, "Looking for files with path " << directoryPath); transaction t (orm_db->begin()); result<ImageRecord> r (orm_db->query<ImageRecord>(query<ImageRecord>::path.like(path_query))); for(result<ImageRecord>::iterator itr (r.begin()); itr != r.end(); ++itr) { filePaths.push_back(fs::path(itr->getPath())); } t.commit(); LOG4CPLUS_INFO(logger, "Found " << filePaths.size() << " records for path " << directoryPath); return filePaths; } void Database::prunePath(std::list<fs::path> filePaths) { for(std::list<fs::path>::iterator ite = filePaths.begin(); ite != filePaths.end(); ++ite){ ImageRecord ir = get_imagerecord(*ite); transaction t (orm_db->begin()); if(ir.is_valid()) { orm_db->erase(ir); } t.commit(); } } void Database::addToBatch(db_data data) { int response = 0; int hashId = -1; switch (data.status) { case OK: add_record(data); break; case INVALID: add_invalid(data); break; case FILTER: add_filter(data); break; default: LOG4CPLUS_ERROR(logger, "Unhandled state encountered"); throw "Unhandled state encountered"; break; } } void Database::add_record(db_data data) { Hash hash = get_hash(data.sha256); if (!hash.is_valid()) { hash = addHashEntry(data.sha256, data.pHash); } if(entryExists(data)) { LOG4CPLUS_DEBUG(logger, "Entry for " << data.filePath << " already exists, discarding..."); recordsWritten--; return; } transaction t(orm_db->begin()); ImageRecord ir = ImageRecord(data.filePath.string(), &hash); orm_db->persist(ir); t.commit(); } int Database::add_path_placeholder(std::string path) { transaction t (orm_db->begin()); ImageRecord ir (path,NULL); int id = orm_db->persist(ir); t.commit(); return id; } void Database::add_invalid(db_data data) { LOG4CPLUS_DEBUG(logger, "File with path " << data.filePath << " is invalid"); recordsWritten--; Hash hash = get_hash(""); transaction t(orm_db->begin()); ImageRecord ir = ImageRecord(data.filePath.string(), &hash); orm_db->persist(ir); t.commit(); } void Database::add_filter(db_data data) { LOG4CPLUS_DEBUG(logger, "Adding filter record for pHash" << data.pHash << " with reason " << data.reason); imageHasher::db::table::FilterRecord fr(data.pHash, data.reason); transaction t (orm_db->begin()); orm_db->persist(fr); t.commit(); } void Database::prepareStatements() { LOG4CPLUS_INFO(logger, "Creating prepared statements..."); } void Database::doWork() { while(running) { try{ boost::this_thread::sleep_for(boost::chrono::seconds(3)); }catch(boost::thread_interrupted&) { LOG4CPLUS_INFO(logger,"DB thread interrupted"); } if(currentList->size() > 1000) { int drainCount = drain(); LOG4CPLUS_INFO(logger, drainCount << " records processed, Total: " << recordsWritten); } } // make sure both lists are committed int drainCount = flush(); LOG4CPLUS_INFO(logger, drainCount << " records processed, Total: " << recordsWritten); } unsigned int Database::getRecordsWritten() { return recordsWritten; } std::string Database::getSHA(fs::path filepath) { std::string sha = ""; LOG4CPLUS_DEBUG(logger, "Getting SHA for path " << filepath); transaction t (orm_db->begin()); result<ImageRecord> r (orm_db->query<ImageRecord>(query<ImageRecord>::path == filepath.string())); for(result<ImageRecord>::iterator itr (r.begin()); itr != r.end(); ++itr) { Hash hash = itr->get_hash(); sha = hash.get_sha256(); break; } t.commit(); return sha; } bool Database::sha_exists(std::string sha) { Hash hash = get_hash(sha); return hash.is_valid(); } int64_t Database::getPhash(fs::path filepath) { LOG4CPLUS_DEBUG(logger, "Getting pHash for path " << filepath); ImageRecord ir = get_imagerecord(filepath); if(ir.is_valid()) { return ir.get_hash().get_pHash(); } return -1; } imageHasher::db::table::Hash Database::get_hash(std::string sha) { Hash hash; LOG4CPLUS_DEBUG(logger, "Getting hash for sha " << sha); transaction t (orm_db->begin()); result<Hash> r (orm_db->query<Hash>(query<Hash>::sha256 == sha)); for(result<Hash>::iterator itr (r.begin()); itr != r.end(); ++itr) { hash = *itr; break; } t.commit(); return hash; } imageHasher::db::table::Hash Database::get_hash(u_int64_t phash) { Hash hash; LOG4CPLUS_DEBUG(logger, "Getting hash for pHash " << phash); transaction t (orm_db->begin()); result<Hash> r (orm_db->query<Hash>(query<Hash>::pHash == phash)); for(result<Hash>::iterator itr (r.begin()); itr != r.end(); ++itr) { hash = *itr; break; } t.commit(); return hash; } imageHasher::db::table::ImageRecord Database::get_imagerecord(fs::path filepath) { ImageRecord ir; transaction t (orm_db->begin()); result<ImageRecord> r (orm_db->query<ImageRecord>(query<ImageRecord>::path == filepath.string())); for(result<ImageRecord>::iterator itr (r.begin()); itr != r.end(); ++itr) { ir = *itr; break; } t.commit(); return ir; } Hash Database::addHashEntry(std::string sha, u_int64_t pHash) { Hash hash(sha,pHash); transaction t (orm_db->begin()); orm_db->persist(hash); t.commit(); return hash; } <commit_msg>Fixed workerthread not deleted after join<commit_after>/* * Database.cpp * * Created on: 21 Aug 2013 * Author: nicholas */ #include "../include/Database.hpp" #include <string> #include <odb/transaction.hxx> #include <odb/result.hxx> #include <odb/schema-catalog.hxx> #include <odb/sqlite/exceptions.hxx> #include "table/ImageRecord.hpp" #include "table/ImageRecord-odb.hxx" #include "table/FilterRecord.hpp" #include "table/FilterRecord-odb.hxx" const char *dbName = "imageHasher.db"; const char *insertImageQuery = "INSERT INTO `imagerecord` (`path`,`sha_id`,`phash_id`) VALUES (?,?,?);"; const char *insertInvalidQuery = "INSERT INTO `badfilerecord` (`path`) VALUES (?);"; const char *insertFilterQuery = "INSERT OR IGNORE INTO `filterrecord` (`phash_id`, `reason`) VALUES (?,?);"; const char *prunePathQuery = "SELECT `path` FROM `imagerecord` WHERE `path` LIKE ? UNION SELECT `path` FROM `badfilerecord` WHERE `path` LIKE ?;"; const char *prunePathDeleteImage = "DELETE FROM `imagerecord` WHERE `path` = ?;"; const char *prunePathDeleteBadFile = "DELETE FROM `badfilerecord` WHERE `path` = ?;"; const char *checkExistsQuery = "SELECT EXISTS(SELECT 1 FROM `imagerecord` WHERE `path` = ? LIMIT 1) OR EXISTS(SELECT 1 FROM `badfilerecord` WHERE `path` = ? LIMIT 1);"; const char *checkSHAQuery = "SELECT EXISTS(SELECT 1 FROM `imagerecord` JOIN `sha_hash` ON `sha_id`= `id` WHERE `path` = ? AND `sha256` != '' LIMIT 1);"; const char *updateSha = "UPDATE `imagerecord` SET `sha_id`=? WHERE `path` = ?;"; const char *getSHAQuery = "SELECT `sha256` FROM `imagerecord` AS ir JOIN `sha_hash` AS h ON ir.sha_id=h.id WHERE `path` = ?;"; const char *getPhashQuery = "SELECT `pHash` FROM `imagerecord` AS ir JOIN `phash_hash` AS h ON ir.sha_id=h.id WHERE `path` = ?;"; const char *getSHAidQuery = "SELECT `id` FROM `sha_hash` WHERE `sha256`= ?;"; const char *getpHashidQuery = "SELECT `id` FROM `phash_hash` WHERE `pHash`= ?;"; const char *insertShaRecordQuery = "INSERT INTO `sha_hash` (`sha256`) VALUES (?);"; const char *insertpHashRecordQuery = "INSERT INTO `phash_hash` (`pHash`) VALUES (?);"; const char *startTransactionQuery = "BEGIN TRANSACTION;"; const char *commitTransactionQuery = "COMMIT TRANSACTION;"; using namespace odb; using namespace imageHasher::db::table; Database::Database(const char* dbPath) { dbName = dbPath; init(); } Database::Database() { init(); } Database::~Database() { shutdown(); delete orm_db; } int Database::flush() { int drainCount = 0; LOG4CPLUS_INFO(logger, "Flushing lists..."); drainCount = drain(); drainCount += drain(); return drainCount; } void Database::shutdown() { if (running) { LOG4CPLUS_INFO(logger, "Shutting down..."); running = false; LOG4CPLUS_INFO(logger, "Waiting for db worker to finish..."); workerThread->interrupt(); workerThread->join(); delete(workerThread); LOG4CPLUS_INFO(logger, "Closing database..."); } } void Database::exec(const char* command) { orm_db->execute(command); } void Database::init() { boost::mutex::scoped_lock lock(dbMutex); this->currentList = &dataA; this->recordsWritten = 0; this->running = true; logger = log4cplus::Logger::getInstance(LOG4CPLUS_TEXT("Database")); setupDatabase(); prepareStatements(); workerThread = new boost::thread(&Database::doWork, this); } bool Database::is_db_initialised() { Hash hash; bool exists = true; transaction t(orm_db->begin()); try { exists = orm_db->find(1, hash); } catch (odb::sqlite::database_exception& e) { exists = false; } t.commit(); return exists; } void Database::initialise_db() { transaction t(orm_db->begin()); odb: schema_catalog::create_schema(*orm_db, "", false); t.commit(); addHashEntry("", 0); } void Database::setupDatabase() { orm_db = new sqlite::database(dbName,SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE); LOG4CPLUS_INFO(logger, "Setting up database " << dbName); bool init_done = is_db_initialised(); if(! init_done) { initialise_db(); } transaction t_pragma (orm_db->begin()); orm_db->execute("PRAGMA page_size = 4096;"); orm_db->execute("PRAGMA cache_size=10000;"); orm_db->execute("PRAGMA locking_mode=EXCLUSIVE;"); orm_db->execute("PRAGMA temp_store = MEMORY;"); orm_db->execute("PRAGMA journal_mode=MEMORY;"); t_pragma.commit(); // perform out of transaction execution connection_ptr c (orm_db->connection()); c->execute("PRAGMA synchronous=NORMAL;"); } void Database::add(db_data data) { boost::mutex::scoped_lock lock(flipMutex); currentList->push_back(data); } void Database::flipLists() { boost::mutex::scoped_lock lock(flipMutex); if(currentList == &dataA) { currentList = &dataB; }else{ currentList = &dataA; } } int Database::drain() { boost::mutex::scoped_lock lock(dbMutex); std::list<db_data>* workList; int drainCount = 0; workList = currentList; flipLists(); for(std::list<db_data>::iterator ite = workList->begin(); ite != workList->end(); ++ite) { addToBatch(*ite); recordsWritten++; drainCount++; } workList->clear(); return drainCount; } bool Database::entryExists(fs::path filePath) { LOG4CPLUS_DEBUG(logger, "Looking for file " << filePath); ImageRecord ir = get_imagerecord(filePath); return ir.is_valid(); } bool Database::entryExists(db_data data) { return entryExists(data.filePath); } std::list<fs::path> Database::getFilesWithPath(fs::path directoryPath) { std::list<fs::path> filePaths; std::string path_query(directoryPath.string()); path_query += "%"; LOG4CPLUS_INFO(logger, "Looking for files with path " << directoryPath); transaction t (orm_db->begin()); result<ImageRecord> r (orm_db->query<ImageRecord>(query<ImageRecord>::path.like(path_query))); for(result<ImageRecord>::iterator itr (r.begin()); itr != r.end(); ++itr) { filePaths.push_back(fs::path(itr->getPath())); } t.commit(); LOG4CPLUS_INFO(logger, "Found " << filePaths.size() << " records for path " << directoryPath); return filePaths; } void Database::prunePath(std::list<fs::path> filePaths) { for(std::list<fs::path>::iterator ite = filePaths.begin(); ite != filePaths.end(); ++ite){ ImageRecord ir = get_imagerecord(*ite); transaction t (orm_db->begin()); if(ir.is_valid()) { orm_db->erase(ir); } t.commit(); } } void Database::addToBatch(db_data data) { int response = 0; int hashId = -1; switch (data.status) { case OK: add_record(data); break; case INVALID: add_invalid(data); break; case FILTER: add_filter(data); break; default: LOG4CPLUS_ERROR(logger, "Unhandled state encountered"); throw "Unhandled state encountered"; break; } } void Database::add_record(db_data data) { Hash hash = get_hash(data.sha256); if (!hash.is_valid()) { hash = addHashEntry(data.sha256, data.pHash); } if(entryExists(data)) { LOG4CPLUS_DEBUG(logger, "Entry for " << data.filePath << " already exists, discarding..."); recordsWritten--; return; } transaction t(orm_db->begin()); ImageRecord ir = ImageRecord(data.filePath.string(), &hash); orm_db->persist(ir); t.commit(); } int Database::add_path_placeholder(std::string path) { transaction t (orm_db->begin()); ImageRecord ir (path,NULL); int id = orm_db->persist(ir); t.commit(); return id; } void Database::add_invalid(db_data data) { LOG4CPLUS_DEBUG(logger, "File with path " << data.filePath << " is invalid"); recordsWritten--; Hash hash = get_hash(""); transaction t(orm_db->begin()); ImageRecord ir = ImageRecord(data.filePath.string(), &hash); orm_db->persist(ir); t.commit(); } void Database::add_filter(db_data data) { LOG4CPLUS_DEBUG(logger, "Adding filter record for pHash" << data.pHash << " with reason " << data.reason); imageHasher::db::table::FilterRecord fr(data.pHash, data.reason); transaction t (orm_db->begin()); orm_db->persist(fr); t.commit(); } void Database::prepareStatements() { LOG4CPLUS_INFO(logger, "Creating prepared statements..."); } void Database::doWork() { while(running) { try{ boost::this_thread::sleep_for(boost::chrono::seconds(3)); }catch(boost::thread_interrupted&) { LOG4CPLUS_INFO(logger,"DB thread interrupted"); } if(currentList->size() > 1000) { int drainCount = drain(); LOG4CPLUS_INFO(logger, drainCount << " records processed, Total: " << recordsWritten); } } // make sure both lists are committed int drainCount = flush(); LOG4CPLUS_INFO(logger, drainCount << " records processed, Total: " << recordsWritten); } unsigned int Database::getRecordsWritten() { return recordsWritten; } std::string Database::getSHA(fs::path filepath) { std::string sha = ""; LOG4CPLUS_DEBUG(logger, "Getting SHA for path " << filepath); transaction t (orm_db->begin()); result<ImageRecord> r (orm_db->query<ImageRecord>(query<ImageRecord>::path == filepath.string())); for(result<ImageRecord>::iterator itr (r.begin()); itr != r.end(); ++itr) { Hash hash = itr->get_hash(); sha = hash.get_sha256(); break; } t.commit(); return sha; } bool Database::sha_exists(std::string sha) { Hash hash = get_hash(sha); return hash.is_valid(); } int64_t Database::getPhash(fs::path filepath) { LOG4CPLUS_DEBUG(logger, "Getting pHash for path " << filepath); ImageRecord ir = get_imagerecord(filepath); if(ir.is_valid()) { return ir.get_hash().get_pHash(); } return -1; } imageHasher::db::table::Hash Database::get_hash(std::string sha) { Hash hash; LOG4CPLUS_DEBUG(logger, "Getting hash for sha " << sha); transaction t (orm_db->begin()); result<Hash> r (orm_db->query<Hash>(query<Hash>::sha256 == sha)); for(result<Hash>::iterator itr (r.begin()); itr != r.end(); ++itr) { hash = *itr; break; } t.commit(); return hash; } imageHasher::db::table::Hash Database::get_hash(u_int64_t phash) { Hash hash; LOG4CPLUS_DEBUG(logger, "Getting hash for pHash " << phash); transaction t (orm_db->begin()); result<Hash> r (orm_db->query<Hash>(query<Hash>::pHash == phash)); for(result<Hash>::iterator itr (r.begin()); itr != r.end(); ++itr) { hash = *itr; break; } t.commit(); return hash; } imageHasher::db::table::ImageRecord Database::get_imagerecord(fs::path filepath) { ImageRecord ir; transaction t (orm_db->begin()); result<ImageRecord> r (orm_db->query<ImageRecord>(query<ImageRecord>::path == filepath.string())); for(result<ImageRecord>::iterator itr (r.begin()); itr != r.end(); ++itr) { ir = *itr; break; } t.commit(); return ir; } Hash Database::addHashEntry(std::string sha, u_int64_t pHash) { Hash hash(sha,pHash); transaction t (orm_db->begin()); orm_db->persist(hash); t.commit(); return hash; } <|endoftext|>
<commit_before>#include "NetworkManagerClient.h" #include <string.h> #include <sys/types.h> #include <stdlib.h> #ifndef WIN32 #include <unistd.h> #include <sys/time.h> #else #include <windows.h> #include <time.h> #endif NetworkManagerClient::NetworkManagerClient(void) : connected(false), scores() { if(SDL_Init(0) != 0){ printf("SDL_Init done goofed: %s\n", SDL_GetError()); exit(1); } if(SDLNet_Init() != 0){ printf("SDLNet_Init done goofed: %s\n",SDLNet_GetError()); } } NetworkManagerClient::~NetworkManagerClient(void) { SDLNet_Quit(); SDL_Quit(); } //main method from tcpmulticlient.c in the SDLNet demos int NetworkManagerClient::TCPConnect(char *host, long portNo, char *name) { IPaddress ip; // TCPsocket sock; char message[MAXLEN]; int numready; SDLNet_SocketSet set; fd_set fdset; int result; char *str; struct timeval tv; Uint16 port = (Uint16)portNo; Packet pack; set = SDLNet_AllocSocketSet(1); if(!set) { printf("SDLNet_AllocSocketSet done goofed: %s\n", SDLNet_GetError()); SDLNet_Quit(); SDL_Quit(); exit(4); /*most of the time this is a major error, but do what you want. */ } /* Resolve the argument into an IPaddress type */ printf("Connecting to %s port %d\n", host, port); if(SDLNet_ResolveHost(&ip, host, port)==-1) { printf("SDLNet_ResolveHost done goofed: %s\n",SDLNet_GetError()); std::string exception = "fail_to_connect"; throw exception; } printf("Opening server socket.\n"); /* open the server socket */ serverSock = SDLNet_TCP_Open(&ip); if(!serverSock) { printf("SDLNet_TCP_Open done goofed: %s\n",SDLNet_GetError()); SDLNet_Quit(); SDL_Quit(); std::string exception = "fail_to_connect"; throw exception; } if(SDLNet_TCP_AddSocket(set,serverSock) == -1) { printf("SDLNet_TCP_AddSocket done goofed: %s\n",SDLNet_GetError()); SDLNet_Quit(); SDL_Quit(); exit(7); } pack.type = CONNECTION; pack.message = name; /* login with a name */ char* out = PacketToCharArray(pack); printf("Sent %s\n", out); if(!TCPSend(serverSock, out)) { SDLNet_TCP_Close(serverSock); exit(8); } mName = name; std::cout << "Logged in as " << mName << std::endl; connected = true; } std::string NetworkManagerClient::getPlayerScores() { return scores; //"name,score;" } void NetworkManagerClient::resetReadyState() { Packet outgoing; outgoing.type = READY; outgoing.message = const_cast<char*>("RESET"); TCPSend(serverSock, PacketToCharArray(outgoing)); } void NetworkManagerClient::sendPlayerInput(ISpaceShipController* controller) { Packet outgoing; bool left = controller->left(); bool right = controller->right(); bool up = controller->up(); bool down = controller->down(); bool forward = controller->forward(); bool back = controller->back(); bool shoot = controller->shoot(); char result = left; result = (result << 1) + right; result = (result << 1) + up; result = (result << 1) + down; result = (result << 1) + forward; result = (result << 1) + back; result = (result << 1) + shoot; outgoing.type = PLAYERINPUT; outgoing.message = &result; char *out = PacketToCharArray(outgoing); if(!TCPSend(serverSock, out)) connected = false; } bool NetworkManagerClient::isOnline() { return connected; } void NetworkManagerClient::quit() { Packet outgoing; outgoing.type = CONNECTION; outgoing.message = const_cast<char*>("QUIT"); while(!TCPSend(serverSock, PacketToCharArray(outgoing))); // FIXME: what if server crashed? connected = false; } void NetworkManagerClient::sendPlayerScore(double score) { std::stringstream ss; std::string s; ss << score; s = ss.str(); Packet outgoing; outgoing.type = SCORE; outgoing.message = const_cast<char*>(s.c_str()); char *incoming = NULL; char *out = PacketToCharArray(outgoing); if(TCPSend(serverSock, out) && TCPReceive(serverSock, &incoming)) { printf("Receving: %s\n", incoming); Packet pack = charArrayToPacket(incoming); if(pack.type != SCORE) { printf("Error in sendPlayerScore() in NetworkManagerClient.cpp. Score not received from server.\n"); scores = ""; } else{ printf("Received message: %s\n", pack.message); scores = pack.message; } } else { connected = false; scores = ""; } } void NetworkManagerClient::receiveData(Ogre::SceneManager* sceneManager, SoundManager* sound, std::vector<Mineral*>& minerals, std::vector<SpaceShip*>& spaceships, std::vector<GameObject*>& walls) { int packs; Packet outgoing; outgoing.type = STATE; outgoing.message = "NONE"; char* incoming = NULL; char *out = PacketToCharArray(outgoing); ////std::cout << "We are sending state request and trying to receive initial response." << std::endl; if(TCPSend(serverSock, out) && TCPReceive(serverSock, &incoming)) { ////std::cout << "Received initial response." << std::endl; Packet numPackets = charArrayToPacket(incoming); packs = atoi(numPackets.message); ////std::cout << "We are expecting to receive " << packs << " number of packets" << std::endl; } else { connected = false; return; } for(int i = 0; i < packs; ++i) { //std::cout << "We are about to receive packet number " << i << "." << std::endl; if(!TCPReceive(serverSock, &incoming)) { connected = false; break;} //std::cout << "We received packet number " << i << "." << std::endl; Packet in = charArrayToPacket(incoming); if(in.type == MINERAL) { //std::cout << "It was a mineral." << std::endl; std::string message(in.message); //std::cout << "The mineral's message is " << message << std::endl; std::string name = message.substr(0, message.find(",")); message = message.substr(message.find(",") + 1); double pos_x = atof(message.substr(0, message.find(",")).c_str()); message = message.substr(message.find(",") + 1); double pos_y = atof(message.substr(0, message.find(",")).c_str()); message = message.substr(message.find(",") + 1); double pos_z = atof(message.substr(0, message.find(",")).c_str()); message = message.substr(message.find(",") + 1); double vel_x = atof(message.substr(0, message.find(",")).c_str()); message = message.substr(message.find(",") + 1); double vel_y = atof(message.substr(0, message.find(",")).c_str()); message = message.substr(message.find(",") + 1); double vel_z = atof(message.substr(0, message.find(",")).c_str()); message = message.substr(message.find(",") + 1); double rot_w = atof(message.substr(0, message.find(",")).c_str()); message = message.substr(message.find(",") + 1); double rot_x = atof(message.substr(0, message.find(",")).c_str()); message = message.substr(message.find(",") + 1); double rot_y = atof(message.substr(0, message.find(",")).c_str()); message = message.substr(message.find(",") + 1); double rot_z = atof(message.substr(0, message.find(",")).c_str()); message = message.substr(message.find(",") + 1); double radius = atof(message.substr(0, message.find(",")).c_str()); //std::cout << "We parsed that message." << message << std::endl; // FIXME: THIS IS BAD, oh well bool found = false; for(int j = 0; j < minerals.size(); ++j) { //std::cout << "Checking to see if " << name << " already exists." << std::endl; if(minerals[j]->getName() == name) { //std::cout << "Exists." << std::endl; found = true; minerals[j]->getSceneNode()->setPosition(pos_x, pos_y, pos_z); minerals[j]->getSceneNode()->setOrientation(rot_w, rot_x, rot_y, rot_z); break; } } if(!found) { //std::cout << "Doesn't exist, create it." << std::endl; minerals.push_back(new Mineral(name, sound, sceneManager->getRootSceneNode(), pos_x, pos_y, pos_z, radius)); minerals.back()->getSceneNode()->setOrientation(rot_w, rot_x, rot_y, rot_z); } //std::cout << "Got the Mineral!" << std::endl; } else if(in.type == SPACESHIP) { //std::cout << "It was a spaceship." << std::endl; std::string message(in.message); std::string name = message.substr(0, message.find(",")); message = message.substr(message.find(",") + 1); double pos_x = atof(message.substr(0, message.find(",")).c_str()); message = message.substr(message.find(",") + 1); double pos_y = atof(message.substr(0, message.find(",")).c_str()); message = message.substr(message.find(",") + 1); double pos_z = atof(message.substr(0, message.find(",")).c_str()); message = message.substr(message.find(",") + 1); double vel_x = atof(message.substr(0, message.find(",")).c_str()); message = message.substr(message.find(",") + 1); double vel_y = atof(message.substr(0, message.find(",")).c_str()); message = message.substr(message.find(",") + 1); double vel_z = atof(message.substr(0, message.find(",")).c_str()); message = message.substr(message.find(",") + 1); double rot_w = atof(message.substr(0, message.find(",")).c_str()); message = message.substr(message.find(",") + 1); double rot_x = atof(message.substr(0, message.find(",")).c_str()); message = message.substr(message.find(",") + 1); double rot_y = atof(message.substr(0, message.find(",")).c_str()); message = message.substr(message.find(",") + 1); double rot_z = atof(message.substr(0, message.find(",")).c_str()); message = message.substr(message.find(",") + 1); double size = atof(message.substr(0, message.find(",")).c_str()); // FIXME: THIS IS BAD, oh well bool found = false; if(name == mName) { spaceships[0]->getSceneNode()->setPosition(pos_x, pos_y, pos_z); spaceships[0]->getSceneNode()->setOrientation(rot_w, rot_x, rot_y, rot_z); break; } for(int j = 1; j < spaceships.size(); ++j) { if(spaceships[j]->getName() == name) { found = true; spaceships[j]->getSceneNode()->setPosition(pos_x, pos_y, pos_z); spaceships[j]->getSceneNode()->setOrientation(rot_w, rot_x, rot_y, rot_z); break; } } if(!found) { ISpaceShipController* controller = new ClientSpaceShipController(); spaceships.push_back(new SpaceShip(name, sound, controller, sceneManager->getRootSceneNode()->createChildSceneNode(),size)); spaceships.back()->getSceneNode()->getParentSceneNode()->setPosition(pos_x, pos_y, pos_z); spaceships.back()->getSceneNode()->setOrientation(rot_w, rot_x, rot_y, rot_z); } //std::cout << "Got the SpaceShip!" << std::endl; } else if(in.type == WALL) { //std::cout << "It was a wall." << std::endl; } } } <commit_msg>Work, you<commit_after>#include "NetworkManagerClient.h" #include <string.h> #include <sys/types.h> #include <stdlib.h> #ifndef WIN32 #include <unistd.h> #include <sys/time.h> #else #include <windows.h> #include <time.h> #endif NetworkManagerClient::NetworkManagerClient(void) : connected(false), scores() { if(SDL_Init(0) != 0){ printf("SDL_Init done goofed: %s\n", SDL_GetError()); exit(1); } if(SDLNet_Init() != 0){ printf("SDLNet_Init done goofed: %s\n",SDLNet_GetError()); } } NetworkManagerClient::~NetworkManagerClient(void) { SDLNet_Quit(); SDL_Quit(); } //main method from tcpmulticlient.c in the SDLNet demos int NetworkManagerClient::TCPConnect(char *host, long portNo, char *name) { IPaddress ip; // TCPsocket sock; char message[MAXLEN]; int numready; SDLNet_SocketSet set; fd_set fdset; int result; char *str; struct timeval tv; Uint16 port = (Uint16)portNo; Packet pack; set = SDLNet_AllocSocketSet(1); if(!set) { printf("SDLNet_AllocSocketSet done goofed: %s\n", SDLNet_GetError()); SDLNet_Quit(); SDL_Quit(); exit(4); /*most of the time this is a major error, but do what you want. */ } /* Resolve the argument into an IPaddress type */ printf("Connecting to %s port %d\n", host, port); if(SDLNet_ResolveHost(&ip, host, port)==-1) { printf("SDLNet_ResolveHost done goofed: %s\n",SDLNet_GetError()); std::string exception = "fail_to_connect"; throw exception; } printf("Opening server socket.\n"); /* open the server socket */ serverSock = SDLNet_TCP_Open(&ip); if(!serverSock) { printf("SDLNet_TCP_Open done goofed: %s\n",SDLNet_GetError()); SDLNet_Quit(); SDL_Quit(); std::string exception = "fail_to_connect"; throw exception; } if(SDLNet_TCP_AddSocket(set,serverSock) == -1) { printf("SDLNet_TCP_AddSocket done goofed: %s\n",SDLNet_GetError()); SDLNet_Quit(); SDL_Quit(); exit(7); } pack.type = CONNECTION; pack.message = name; /* login with a name */ char* out = PacketToCharArray(pack); printf("Sent %s\n", out); if(!TCPSend(serverSock, out)) { SDLNet_TCP_Close(serverSock); exit(8); } mName = name; std::cout << "Logged in as " << mName << std::endl; connected = true; } std::string NetworkManagerClient::getPlayerScores() { return scores; //"name,score;" } void NetworkManagerClient::resetReadyState() { Packet outgoing; outgoing.type = READY; outgoing.message = const_cast<char*>("RESET"); TCPSend(serverSock, PacketToCharArray(outgoing)); } void NetworkManagerClient::sendPlayerInput(ISpaceShipController* controller) { Packet outgoing; bool left = controller->left(); bool right = controller->right(); bool up = controller->up(); bool down = controller->down(); bool forward = controller->forward(); bool back = controller->back(); bool shoot = controller->shoot(); char result = left; result = (result << 1) + right; result = (result << 1) + up; result = (result << 1) + down; result = (result << 1) + forward; result = (result << 1) + back; result = (result << 1) + shoot; outgoing.type = PLAYERINPUT; outgoing.message = &result; char *out = PacketToCharArray(outgoing); if(!TCPSend(serverSock, out)) connected = false; } bool NetworkManagerClient::isOnline() { return connected; } void NetworkManagerClient::quit() { Packet outgoing; outgoing.type = CONNECTION; outgoing.message = const_cast<char*>("QUIT"); while(!TCPSend(serverSock, PacketToCharArray(outgoing))); // FIXME: what if server crashed? connected = false; } void NetworkManagerClient::sendPlayerScore(double score) { std::stringstream ss; std::string s; ss << score; s = ss.str(); Packet outgoing; outgoing.type = SCORE; outgoing.message = const_cast<char*>(s.c_str()); char *incoming = NULL; char *out = PacketToCharArray(outgoing); if(TCPSend(serverSock, out) && TCPReceive(serverSock, &incoming)) { printf("Receving: %s\n", incoming); Packet pack = charArrayToPacket(incoming); if(pack.type != SCORE) { printf("Error in sendPlayerScore() in NetworkManagerClient.cpp. Score not received from server.\n"); scores = ""; } else{ printf("Received message: %s\n", pack.message); scores = pack.message; } } else { connected = false; scores = ""; } } void NetworkManagerClient::receiveData(Ogre::SceneManager* sceneManager, SoundManager* sound, std::vector<Mineral*>& minerals, std::vector<SpaceShip*>& spaceships, std::vector<GameObject*>& walls) { int packs; Packet outgoing; outgoing.type = STATE; outgoing.message = "NONE"; char* incoming = NULL; char *out = PacketToCharArray(outgoing); ////std::cout << "We are sending state request and trying to receive initial response." << std::endl; if(TCPSend(serverSock, out) && TCPReceive(serverSock, &incoming)) { ////std::cout << "Received initial response." << std::endl; Packet numPackets = charArrayToPacket(incoming); packs = atoi(numPackets.message); ////std::cout << "We are expecting to receive " << packs << " number of packets" << std::endl; } else { connected = false; return; } for(int i = 0; i < packs; ++i) { //std::cout << "We are about to receive packet number " << i << "." << std::endl; if(!TCPReceive(serverSock, &incoming)) { connected = false; break;} //std::cout << "We received packet number " << i << "." << std::endl; Packet in = charArrayToPacket(incoming); if(in.type == MINERAL) { //std::cout << "It was a mineral." << std::endl; std::string message(in.message); //std::cout << "The mineral's message is " << message << std::endl; std::string name = message.substr(0, message.find(",")); message = message.substr(message.find(",") + 1); double pos_x = atof(message.substr(0, message.find(",")).c_str()); message = message.substr(message.find(",") + 1); double pos_y = atof(message.substr(0, message.find(",")).c_str()); message = message.substr(message.find(",") + 1); double pos_z = atof(message.substr(0, message.find(",")).c_str()); message = message.substr(message.find(",") + 1); double vel_x = atof(message.substr(0, message.find(",")).c_str()); message = message.substr(message.find(",") + 1); double vel_y = atof(message.substr(0, message.find(",")).c_str()); message = message.substr(message.find(",") + 1); double vel_z = atof(message.substr(0, message.find(",")).c_str()); message = message.substr(message.find(",") + 1); double rot_w = atof(message.substr(0, message.find(",")).c_str()); message = message.substr(message.find(",") + 1); double rot_x = atof(message.substr(0, message.find(",")).c_str()); message = message.substr(message.find(",") + 1); double rot_y = atof(message.substr(0, message.find(",")).c_str()); message = message.substr(message.find(",") + 1); double rot_z = atof(message.substr(0, message.find(",")).c_str()); message = message.substr(message.find(",") + 1); double radius = atof(message.substr(0, message.find(",")).c_str()); //std::cout << "We parsed that message." << message << std::endl; // FIXME: THIS IS BAD, oh well bool found = false; for(int j = 0; j < minerals.size(); ++j) { //std::cout << "Checking to see if " << name << " already exists." << std::endl; if(minerals[j]->getName() == name) { //std::cout << "Exists." << std::endl; found = true; minerals[j]->getSceneNode()->setPosition(pos_x, pos_y, pos_z); minerals[j]->getSceneNode()->setOrientation(rot_w, rot_x, rot_y, rot_z); break; } } if(!found) { //std::cout << "Doesn't exist, create it." << std::endl; minerals.push_back(new Mineral(name, sound, sceneManager->getRootSceneNode(), pos_x, pos_y, pos_z, radius)); minerals.back()->getSceneNode()->setOrientation(rot_w, rot_x, rot_y, rot_z); } //std::cout << "Got the Mineral!" << std::endl; } else if(in.type == SPACESHIP) { //std::cout << "It was a spaceship." << std::endl; std::string message(in.message); std::string name = message.substr(0, message.find(",")); message = message.substr(message.find(",") + 1); double pos_x = atof(message.substr(0, message.find(",")).c_str()); message = message.substr(message.find(",") + 1); double pos_y = atof(message.substr(0, message.find(",")).c_str()); message = message.substr(message.find(",") + 1); double pos_z = atof(message.substr(0, message.find(",")).c_str()); message = message.substr(message.find(",") + 1); double vel_x = atof(message.substr(0, message.find(",")).c_str()); message = message.substr(message.find(",") + 1); double vel_y = atof(message.substr(0, message.find(",")).c_str()); message = message.substr(message.find(",") + 1); double vel_z = atof(message.substr(0, message.find(",")).c_str()); message = message.substr(message.find(",") + 1); double rot_w = atof(message.substr(0, message.find(",")).c_str()); message = message.substr(message.find(",") + 1); double rot_x = atof(message.substr(0, message.find(",")).c_str()); message = message.substr(message.find(",") + 1); double rot_y = atof(message.substr(0, message.find(",")).c_str()); message = message.substr(message.find(",") + 1); double rot_z = atof(message.substr(0, message.find(",")).c_str()); message = message.substr(message.find(",") + 1); double size = atof(message.substr(0, message.find(",")).c_str()); // FIXME: THIS IS BAD, oh well bool found = false; if(name == mName) { spaceships[0]->getSceneNode()->getParentSceneNode()->setPosition(pos_x, pos_y, pos_z); spaceships[0]->getSceneNode()->setOrientation(rot_w, rot_x, rot_y, rot_z); break; } for(int j = 1; j < spaceships.size(); ++j) { if(spaceships[j]->getName() == name) { found = true; spaceships[j]->getSceneNode()->setPosition(pos_x, pos_y, pos_z); spaceships[j]->getSceneNode()->setOrientation(rot_w, rot_x, rot_y, rot_z); break; } } if(!found) { ISpaceShipController* controller = new ClientSpaceShipController(); spaceships.push_back(new SpaceShip(name, sound, controller, sceneManager->getRootSceneNode()->createChildSceneNode(),size)); spaceships.back()->getSceneNode()->getParentSceneNode()->setPosition(pos_x, pos_y, pos_z); spaceships.back()->getSceneNode()->setOrientation(rot_w, rot_x, rot_y, rot_z); } //std::cout << "Got the SpaceShip!" << std::endl; } else if(in.type == WALL) { //std::cout << "It was a wall." << std::endl; } } } <|endoftext|>
<commit_before>/* * Copyright (c) 2015 Cryptonomex, Inc., and contributors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * 1. Any modified source or binaries are used only with the BitShares network. * * 2. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * 3. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <graphene/db/object_database.hpp> #include <graphene/db/undo_database.hpp> #include <fc/reflect/variant.hpp> namespace graphene { namespace db { void undo_database::enable() { _disabled = false; } void undo_database::disable() { _disabled = true; } undo_database::session undo_database::start_undo_session( bool force_enable ) { if( _disabled && !force_enable ) return session(*this); bool disable_on_exit = _disabled && force_enable; if( force_enable ) _disabled = false; while( size() > max_size() ) _stack.pop_front(); _stack.emplace_back(); ++_active_sessions; return session(*this, disable_on_exit ); } void undo_database::on_create( const object& obj ) { if( _disabled ) return; if( _stack.empty() ) _stack.emplace_back(); auto& state = _stack.back(); auto index_id = object_id_type( obj.id.space(), obj.id.type(), 0 ); auto itr = state.old_index_next_ids.find( index_id ); if( itr == state.old_index_next_ids.end() ) state.old_index_next_ids[index_id] = obj.id; state.new_ids.insert(obj.id); } void undo_database::on_modify( const object& obj ) { if( _disabled ) return; if( _stack.empty() ) _stack.emplace_back(); auto& state = _stack.back(); if( state.new_ids.find(obj.id) != state.new_ids.end() ) return; auto itr = state.old_values.find(obj.id); if( itr != state.old_values.end() ) return; state.old_values[obj.id] = obj.clone(); } void undo_database::on_remove( const object& obj ) { if( _disabled ) return; if( _stack.empty() ) _stack.emplace_back(); undo_state& state = _stack.back(); if( state.new_ids.count(obj.id) ) { state.new_ids.erase(obj.id); return; } if( state.old_values.count(obj.id) ) { state.removed[obj.id] = std::move(state.old_values[obj.id]); state.old_values.erase(obj.id); return; } if( state.removed.count(obj.id) ) return; state.removed[obj.id] = obj.clone(); } void undo_database::undo() { try { FC_ASSERT( !_disabled ); FC_ASSERT( _active_sessions > 0 ); disable(); auto& state = _stack.back(); for( auto& item : state.old_values ) { _db.modify( _db.get_object( item.second->id ), [&]( object& obj ){ obj.move_from( *item.second ); } ); } for( auto ritr = state.new_ids.begin(); ritr != state.new_ids.end(); ++ritr ) { _db.remove( _db.get_object(*ritr) ); } for( auto& item : state.old_index_next_ids ) { _db.get_mutable_index( item.first.space(), item.first.type() ).set_next_id( item.second ); } for( auto& item : state.removed ) _db.insert( std::move(*item.second) ); _stack.pop_back(); if( _stack.empty() ) _stack.emplace_back(); enable(); --_active_sessions; } FC_CAPTURE_AND_RETHROW() } void undo_database::merge() { FC_ASSERT( _active_sessions > 0 ); FC_ASSERT( _stack.size() >=2 ); auto& state = _stack.back(); auto& prev_state = _stack[_stack.size()-2]; // An object's relationship to a state can be: // in new_ids : new // in old_values (was=X) : upd(was=X) // in removed (was=X) : del(was=X) // not in any of above : nop // // When merging A=prev_state and B=state we have a 4x4 matrix of all possibilities: // // |--------------------- B ----------------------| // // +------------+------------+------------+------------+ // | new | upd(was=Y) | del(was=Y) | nop | // +------------+------------+------------+------------+------------+ // / | new | N/A | new A| nop C| new A| // | +------------+------------+------------+------------+------------+ // | | upd(was=X) | N/A | upd(was=X)A| del(was=X)C| upd(was=X)A| // A +------------+------------+------------+------------+------------+ // | | del(was=X) | N/A | N/A | N/A | del(was=X)A| // | +------------+------------+------------+------------+------------+ // \ | nop | new B| upd(was=Y)B| del(was=Y)B| nop AB| // +------------+------------+------------+------------+------------+ // // Each entry was composed by labelling what should occur in the given case. // // Type A means the composition of states contains the same entry as the first of the two merged states for that object. // Type B means the composition of states contains the same entry as the second of the two merged states for that object. // Type C means the composition of states contains an entry different from either of the merged states for that object. // Type N/A means the composition of states violates causal timing. // Type AB means both type A and type B simultaneously. // // The merge() operation is defined as modifying prev_state in-place to be the state object which represents the composition of // state A and B. // // Type A (and AB) can be implemented as a no-op; prev_state already contains the correct value for the merged state. // Type B (and AB) can be implemented by copying from state to prev_state. // Type C needs special case-by-case logic. // Type N/A can be ignored or assert(false) as it can only occur if prev_state and state have illegal values // (a serious logic error which should never happen). // // We can only be outside type A/AB (the nop path) if B is not nop, so it suffices to iterate through B's three containers. // *+upd for( auto& obj : state.old_values ) { if( prev_state.new_ids.find(obj.second->id) != prev_state.new_ids.end() ) { // new+upd -> new, type A continue; } if( prev_state.old_values.find(obj.second->id) != prev_state.old_values.end() ) { // upd(was=X) + upd(was=Y) -> upd(was=X), type A continue; } // nop+upd(was=Y) -> upd(was=Y), type B prev_state.old_values[obj.second->id] = std::move(obj.second); } // *+new, but we assume the N/A cases don't happen, leaving type B nop+new -> new for( auto id : state.new_ids ) prev_state.new_ids.insert(id); // old_index_next_ids can only be updated, iterate over *+upd cases for( auto& item : state.old_index_next_ids ) { if( prev_state.old_index_next_ids.find( item.first ) == prev_state.old_index_next_ids.end() ) { // nop+upd(was=Y) -> upd(was=Y), type B prev_state.old_index_next_ids[item.first] = item.second; continue; } else { // upd(was=X)+upd(was=Y) -> upd(was=X), type A // type A implementation is a no-op, as discussed above, so there is no code here continue; } } // *+del for( auto& obj : state.removed ) { if( prev_state.new_ids.find(obj.second->id) != prev_state.new_ids.end() ) { // new + del -> nop (type C) prev_state.new_ids.erase(obj.second->id); continue; } // nop + del(was=Y) -> del(was=Y) prev_state.removed[obj.second->id] = std::move(obj.second); } _stack.pop_back(); --_active_sessions; } void undo_database::commit() { FC_ASSERT( _active_sessions > 0 ); --_active_sessions; } void undo_database::pop_commit() { FC_ASSERT( _active_sessions == 0 ); FC_ASSERT( !_stack.empty() ); disable(); try { auto& state = _stack.back(); for( auto& item : state.old_values ) { _db.modify( _db.get_object( item.second->id ), [&]( object& obj ){ obj.move_from( *item.second ); } ); } for( auto ritr = state.new_ids.begin(); ritr != state.new_ids.end(); ++ritr ) { _db.remove( _db.get_object(*ritr) ); } for( auto& item : state.old_index_next_ids ) { _db.get_mutable_index( item.first.space(), item.first.type() ).set_next_id( item.second ); } for( auto& item : state.removed ) _db.insert( std::move(*item.second) ); _stack.pop_back(); } catch ( const fc::exception& e ) { elog( "error popping commit ${e}", ("e", e.to_detail_string() ) ); enable(); throw; } enable(); } const undo_state& undo_database::head()const { FC_ASSERT( !_stack.empty() ); return _stack.back(); } } } // graphene::db <commit_msg>undo_database.cpp: Handle unimplemented upd+del case<commit_after>/* * Copyright (c) 2015 Cryptonomex, Inc., and contributors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * 1. Any modified source or binaries are used only with the BitShares network. * * 2. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * 3. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <graphene/db/object_database.hpp> #include <graphene/db/undo_database.hpp> #include <fc/reflect/variant.hpp> namespace graphene { namespace db { void undo_database::enable() { _disabled = false; } void undo_database::disable() { _disabled = true; } undo_database::session undo_database::start_undo_session( bool force_enable ) { if( _disabled && !force_enable ) return session(*this); bool disable_on_exit = _disabled && force_enable; if( force_enable ) _disabled = false; while( size() > max_size() ) _stack.pop_front(); _stack.emplace_back(); ++_active_sessions; return session(*this, disable_on_exit ); } void undo_database::on_create( const object& obj ) { if( _disabled ) return; if( _stack.empty() ) _stack.emplace_back(); auto& state = _stack.back(); auto index_id = object_id_type( obj.id.space(), obj.id.type(), 0 ); auto itr = state.old_index_next_ids.find( index_id ); if( itr == state.old_index_next_ids.end() ) state.old_index_next_ids[index_id] = obj.id; state.new_ids.insert(obj.id); } void undo_database::on_modify( const object& obj ) { if( _disabled ) return; if( _stack.empty() ) _stack.emplace_back(); auto& state = _stack.back(); if( state.new_ids.find(obj.id) != state.new_ids.end() ) return; auto itr = state.old_values.find(obj.id); if( itr != state.old_values.end() ) return; state.old_values[obj.id] = obj.clone(); } void undo_database::on_remove( const object& obj ) { if( _disabled ) return; if( _stack.empty() ) _stack.emplace_back(); undo_state& state = _stack.back(); if( state.new_ids.count(obj.id) ) { state.new_ids.erase(obj.id); return; } if( state.old_values.count(obj.id) ) { state.removed[obj.id] = std::move(state.old_values[obj.id]); state.old_values.erase(obj.id); return; } if( state.removed.count(obj.id) ) return; state.removed[obj.id] = obj.clone(); } void undo_database::undo() { try { FC_ASSERT( !_disabled ); FC_ASSERT( _active_sessions > 0 ); disable(); auto& state = _stack.back(); for( auto& item : state.old_values ) { _db.modify( _db.get_object( item.second->id ), [&]( object& obj ){ obj.move_from( *item.second ); } ); } for( auto ritr = state.new_ids.begin(); ritr != state.new_ids.end(); ++ritr ) { _db.remove( _db.get_object(*ritr) ); } for( auto& item : state.old_index_next_ids ) { _db.get_mutable_index( item.first.space(), item.first.type() ).set_next_id( item.second ); } for( auto& item : state.removed ) _db.insert( std::move(*item.second) ); _stack.pop_back(); if( _stack.empty() ) _stack.emplace_back(); enable(); --_active_sessions; } FC_CAPTURE_AND_RETHROW() } void undo_database::merge() { FC_ASSERT( _active_sessions > 0 ); FC_ASSERT( _stack.size() >=2 ); auto& state = _stack.back(); auto& prev_state = _stack[_stack.size()-2]; // An object's relationship to a state can be: // in new_ids : new // in old_values (was=X) : upd(was=X) // in removed (was=X) : del(was=X) // not in any of above : nop // // When merging A=prev_state and B=state we have a 4x4 matrix of all possibilities: // // |--------------------- B ----------------------| // // +------------+------------+------------+------------+ // | new | upd(was=Y) | del(was=Y) | nop | // +------------+------------+------------+------------+------------+ // / | new | N/A | new A| nop C| new A| // | +------------+------------+------------+------------+------------+ // | | upd(was=X) | N/A | upd(was=X)A| del(was=X)C| upd(was=X)A| // A +------------+------------+------------+------------+------------+ // | | del(was=X) | N/A | N/A | N/A | del(was=X)A| // | +------------+------------+------------+------------+------------+ // \ | nop | new B| upd(was=Y)B| del(was=Y)B| nop AB| // +------------+------------+------------+------------+------------+ // // Each entry was composed by labelling what should occur in the given case. // // Type A means the composition of states contains the same entry as the first of the two merged states for that object. // Type B means the composition of states contains the same entry as the second of the two merged states for that object. // Type C means the composition of states contains an entry different from either of the merged states for that object. // Type N/A means the composition of states violates causal timing. // Type AB means both type A and type B simultaneously. // // The merge() operation is defined as modifying prev_state in-place to be the state object which represents the composition of // state A and B. // // Type A (and AB) can be implemented as a no-op; prev_state already contains the correct value for the merged state. // Type B (and AB) can be implemented by copying from state to prev_state. // Type C needs special case-by-case logic. // Type N/A can be ignored or assert(false) as it can only occur if prev_state and state have illegal values // (a serious logic error which should never happen). // // We can only be outside type A/AB (the nop path) if B is not nop, so it suffices to iterate through B's three containers. // *+upd for( auto& obj : state.old_values ) { if( prev_state.new_ids.find(obj.second->id) != prev_state.new_ids.end() ) { // new+upd -> new, type A continue; } if( prev_state.old_values.find(obj.second->id) != prev_state.old_values.end() ) { // upd(was=X) + upd(was=Y) -> upd(was=X), type A continue; } // del+upd -> N/A assert( prev_state.removed.find(obj.second->id) == prev_state.removed.end() ); // nop+upd(was=Y) -> upd(was=Y), type B prev_state.old_values[obj.second->id] = std::move(obj.second); } // *+new, but we assume the N/A cases don't happen, leaving type B nop+new -> new for( auto id : state.new_ids ) prev_state.new_ids.insert(id); // old_index_next_ids can only be updated, iterate over *+upd cases for( auto& item : state.old_index_next_ids ) { if( prev_state.old_index_next_ids.find( item.first ) == prev_state.old_index_next_ids.end() ) { // nop+upd(was=Y) -> upd(was=Y), type B prev_state.old_index_next_ids[item.first] = item.second; continue; } else { // upd(was=X)+upd(was=Y) -> upd(was=X), type A // type A implementation is a no-op, as discussed above, so there is no code here continue; } } // *+del for( auto& obj : state.removed ) { if( prev_state.new_ids.find(obj.second->id) != prev_state.new_ids.end() ) { // new + del -> nop (type C) prev_state.new_ids.erase(obj.second->id); continue; } auto it = prev_state.old_values.find(obj.second->id); if( it != prev_state.old_values.end() ) { // upd(was=X) + del(was=Y) -> del(was=X) prev_state.removed[obj.second->id] = std::move(it->second); prev_state.old_values.erase(obj.second->id); continue; } // del + del -> N/A assert( prev_state.removed.find( obj.second->id ) == prev_state.removed.end() ); // nop + del(was=Y) -> del(was=Y) prev_state.removed[obj.second->id] = std::move(obj.second); } _stack.pop_back(); --_active_sessions; } void undo_database::commit() { FC_ASSERT( _active_sessions > 0 ); --_active_sessions; } void undo_database::pop_commit() { FC_ASSERT( _active_sessions == 0 ); FC_ASSERT( !_stack.empty() ); disable(); try { auto& state = _stack.back(); for( auto& item : state.old_values ) { _db.modify( _db.get_object( item.second->id ), [&]( object& obj ){ obj.move_from( *item.second ); } ); } for( auto ritr = state.new_ids.begin(); ritr != state.new_ids.end(); ++ritr ) { _db.remove( _db.get_object(*ritr) ); } for( auto& item : state.old_index_next_ids ) { _db.get_mutable_index( item.first.space(), item.first.type() ).set_next_id( item.second ); } for( auto& item : state.removed ) _db.insert( std::move(*item.second) ); _stack.pop_back(); } catch ( const fc::exception& e ) { elog( "error popping commit ${e}", ("e", e.to_detail_string() ) ); enable(); throw; } enable(); } const undo_state& undo_database::head()const { FC_ASSERT( !_stack.empty() ); return _stack.back(); } } } // graphene::db <|endoftext|>
<commit_before>/* Copyright (C) 2005 by Jorrit Tyberghein (C) 2005 by Frank Richter (C) 2009 by Marten Svanfeldt This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "cssysdef.h" #include "csgeom/math.h" #include "csutil/sysfunc.h" #include "csutil/threadjobqueue.h" #include "csutil/randomgen.h" namespace { static CS::Threading::Mutex rgenLock; static csRandomGen rgen; } namespace CS { namespace Threading { ThreadedJobQueue::ThreadedJobQueue (size_t numWorkers, ThreadPriority priority, const char* name) : scfImplementationType (this), numWorkerThreads (numWorkers), outstandingJobs (0), name (name) { if (this->name.IsEmpty()) this->name.Format ("Queue [%p]", this); allThreadState = new csRef<ThreadState>[numWorkerThreads]; // Start up the threads for (unsigned int i = 0; i < numWorkerThreads; ++i) { allThreadState[i].AttachNew (new ThreadState (this, i)); allThreadState[i]->threadObject->SetPriority(priority); allThreads.Add (allThreadState[i]->threadObject); } allThreads.StartAll (); } ThreadedJobQueue::~ThreadedJobQueue () { // Kill all threads, friendly for(size_t i = 0; i < numWorkerThreads; ++i) { CS::Threading::AtomicOperations::Set ( &(allThreadState[i]->runnable->shutdownQueue), 0xff); allThreadState[i]->tsNewJob.NotifyAll (); } allThreads.WaitAll (); // Deallocate for (size_t i = 0; i < numWorkerThreads; ++i) { allThreadState[i]->runnable.Invalidate(); } delete[] allThreadState; } void ThreadedJobQueue::Enqueue (iJob* job) { if (!job) return; while (true) { // Find a thread (on random) to add it to size_t targetThread = rgen.Get ((uint32)numWorkerThreads); // Lock, add and notify ThreadState* ts = allThreadState[targetThread]; // Might be contended, so try next if locked if (ts->tsMutex.TryLock ()) { ts->jobQueue.Push (job); CS::Threading::AtomicOperations::Increment (&outstandingJobs); ts->tsMutex.Unlock (); ts->tsNewJob.NotifyAll (); return; } } } iJobQueue::JobStatus ThreadedJobQueue::Dequeue (iJob* job, bool waitForCompletion) { // Check all the thread queues bool removedJob = PullFromQueues (job); if (!removedJob) { return Dequeued; } else { return CheckCompletion (job, waitForCompletion); } // Nothing return NotEnqueued; } iJobQueue::JobStatus ThreadedJobQueue::PullAndRun (iJob* job, bool waitForCompletion) { bool removedJob = PullFromQueues (job); if (removedJob) { job->Run (); return Dequeued; } else { return CheckCompletion (job, waitForCompletion); } // Nothing return NotEnqueued; } iJobQueue::JobStatus ThreadedJobQueue::CheckCompletion (iJob* job, bool waitForCompletion) { // Check if it is running, then wait ThreadState *ownerTs = 0; for (size_t i = 0; i < numWorkerThreads; ++i) { ThreadState* ts = allThreadState[i]; ts->tsMutex.Lock (); if (ts->currentJob == job) { ownerTs = ts; break; } ts->tsMutex.Unlock (); // Unlock if not right } if (ownerTs) { JobStatus result; if (waitForCompletion) { // Always enter here with ownerTs->tsMutex locked! while (ownerTs->currentJob == job) { ownerTs->tsJobFinished.Wait (ownerTs->tsMutex); } result = Dequeued; } else result = Pending; ownerTs->tsMutex.Unlock (); // Unlock if right return result; } else return NotEnqueued; // All mutex that have been locked are unlocked! } void ThreadedJobQueue::WaitAll () { while(!IsFinished ()) { for (size_t i = 0; i < numWorkerThreads; ++i) { ThreadState* ts = allThreadState[i]; MutexScopedLock l (ts->tsMutex); if(ts->currentJob || ts->jobQueue.GetSize() > 0) { // Have a job, wait for it ts->tsJobFinished.Wait (ts->tsMutex); } } } } bool ThreadedJobQueue::IsFinished () { int32 c = CS::Threading::AtomicOperations::Read (&outstandingJobs); return c == 0; } int32 ThreadedJobQueue::GetQueueCount() { return CS::Threading::AtomicOperations::Read(&outstandingJobs); } bool ThreadedJobQueue::PullFromQueues (iJob* job) { // Check all the thread queues for (size_t i = 0; i < numWorkerThreads; ++i) { ThreadState* ts = allThreadState[i]; MutexScopedLock l (ts->tsMutex); bool removedJob = ts->jobQueue.Delete (job); if (removedJob) { CS::Threading::AtomicOperations::Decrement(&outstandingJobs); return true; } } return false; } ThreadedJobQueue::QueueRunnable::QueueRunnable (ThreadedJobQueue* queue, ThreadState* ts, unsigned int id) : ownerQueue (queue), shutdownQueue (0), threadState (ts) { name.Format ("#%u %s", id, queue->GetName()); } void ThreadedJobQueue::QueueRunnable::Run () { // Forcibly keep QueueRunnable object alive until we got a shutdown this->IncRef(); while (CS::Threading::AtomicOperations::Read(&(/*ownerQueue->*/shutdownQueue)) == 0x0) { // Get a job csRef<iJob> currentJob; // Try our own list first // We need to hold this until currentJob is set, otherwise something might slip through in "wait" threadState->tsMutex.Lock (); if (threadState->jobQueue.GetSize () > 0) { currentJob = threadState->jobQueue.PopTop (); } if (!currentJob) { // If we couldn't get any job, try to steal. At most try to steal once // from each of the other threads size_t start; { MutexScopedLock l (rgenLock); start = rgen.Get ((uint32)ownerQueue->numWorkerThreads); } for (size_t i = 0, index = start; i < ownerQueue->numWorkerThreads; ++i, index = (index + 1) % ownerQueue->numWorkerThreads ) { ThreadState* foreignTS = ownerQueue->allThreadState[index]; if (foreignTS == threadState) continue; // Try to lock it, but never wait for a lock if (foreignTS->tsMutex.TryLock ()) // Lock foreign object A { // Get the job if (foreignTS->jobQueue.GetSize() > 0) { currentJob = foreignTS->jobQueue.PopBottom (); foreignTS->tsMutex.Unlock (); // Unlock foreign object A if success break; } foreignTS->tsMutex.Unlock (); // Unlock foreign object A if unsuccessful } } } if (currentJob) { // Got one, execute threadState->currentJob = currentJob; threadState->tsMutex.Unlock (); // Unlock our own TS after getting a job currentJob->Run (); /* Release reference to job only until after the last access of the thread manager. This is a cautionary measure: the _job_ may keep the last ref to the TM; releasing the job will also release the TM, causing segfaults upon accesses to it. Thus keep it until after having accessed the TM for the last time. */ csRef<iJob> justKeepCurrentJobRefALittleLonger (currentJob); { MutexScopedLock l (threadState->tsMutex); threadState->currentJob = 0; currentJob = 0; } CS::Threading::AtomicOperations::Decrement(&(ownerQueue->outstandingJobs)); threadState->tsJobFinished.NotifyAll (); } else { // Couldn't get one, wait for a newly added job threadState->tsNewJob.Wait (threadState->tsMutex); threadState->tsMutex.Unlock (); } } // There is a circular ref between ThreadState and QueueRunnable, break it up threadState.Invalidate(); this->DecRef(); } const char* ThreadedJobQueue::QueueRunnable::GetName () const { return name.GetDataSafe (); } } } <commit_msg>threadqueue: When some queues are 'underfilled', wake up all threads, to facilitate job stealing<commit_after>/* Copyright (C) 2005 by Jorrit Tyberghein (C) 2005 by Frank Richter (C) 2009 by Marten Svanfeldt This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "cssysdef.h" #include "csgeom/math.h" #include "csutil/sysfunc.h" #include "csutil/threadjobqueue.h" #include "csutil/randomgen.h" namespace { static CS::Threading::Mutex rgenLock; static csRandomGen rgen; } namespace CS { namespace Threading { ThreadedJobQueue::ThreadedJobQueue (size_t numWorkers, ThreadPriority priority, const char* name) : scfImplementationType (this), numWorkerThreads (numWorkers), outstandingJobs (0), name (name) { if (this->name.IsEmpty()) this->name.Format ("Queue [%p]", this); allThreadState = new csRef<ThreadState>[numWorkerThreads]; // Start up the threads for (unsigned int i = 0; i < numWorkerThreads; ++i) { allThreadState[i].AttachNew (new ThreadState (this, i)); allThreadState[i]->threadObject->SetPriority(priority); allThreads.Add (allThreadState[i]->threadObject); } allThreads.StartAll (); } ThreadedJobQueue::~ThreadedJobQueue () { // Kill all threads, friendly for(size_t i = 0; i < numWorkerThreads; ++i) { CS::Threading::AtomicOperations::Set ( &(allThreadState[i]->runnable->shutdownQueue), 0xff); allThreadState[i]->tsNewJob.NotifyAll (); } allThreads.WaitAll (); // Deallocate for (size_t i = 0; i < numWorkerThreads; ++i) { allThreadState[i]->runnable.Invalidate(); } delete[] allThreadState; } void ThreadedJobQueue::Enqueue (iJob* job) { if (!job) return; while (true) { // Find a thread (on random) to add it to size_t targetThread = rgen.Get ((uint32)numWorkerThreads); // Lock, add and notify ThreadState* ts = allThreadState[targetThread]; // Might be contended, so try next if locked if (ts->tsMutex.TryLock ()) { ts->jobQueue.Push (job); size_t jobCount (CS::Threading::AtomicOperations::Increment (&outstandingJobs)); ts->tsMutex.Unlock (); if ((jobCount > 1) && (jobCount < numWorkerThreads)) { /* There must be some empty queues, so notify all queues so one * might possible steal the job just added if it happened to go into * a non-empty queue */ for (size_t i = 0; i < numWorkerThreads; ++i) { ThreadState* ts = allThreadState[(targetThread + i) % numWorkerThreads]; ts->tsNewJob.NotifyAll (); } } else { /* Queues are generally filled, just notify the thread we gave to * job to */ ts->tsNewJob.NotifyAll (); } return; } } } iJobQueue::JobStatus ThreadedJobQueue::Dequeue (iJob* job, bool waitForCompletion) { // Check all the thread queues bool removedJob = PullFromQueues (job); if (!removedJob) { return Dequeued; } else { return CheckCompletion (job, waitForCompletion); } // Nothing return NotEnqueued; } iJobQueue::JobStatus ThreadedJobQueue::PullAndRun (iJob* job, bool waitForCompletion) { bool removedJob = PullFromQueues (job); if (removedJob) { job->Run (); return Dequeued; } else { return CheckCompletion (job, waitForCompletion); } // Nothing return NotEnqueued; } iJobQueue::JobStatus ThreadedJobQueue::CheckCompletion (iJob* job, bool waitForCompletion) { // Check if it is running, then wait ThreadState *ownerTs = 0; for (size_t i = 0; i < numWorkerThreads; ++i) { ThreadState* ts = allThreadState[i]; ts->tsMutex.Lock (); if (ts->currentJob == job) { ownerTs = ts; break; } ts->tsMutex.Unlock (); // Unlock if not right } if (ownerTs) { JobStatus result; if (waitForCompletion) { // Always enter here with ownerTs->tsMutex locked! while (ownerTs->currentJob == job) { ownerTs->tsJobFinished.Wait (ownerTs->tsMutex); } result = Dequeued; } else result = Pending; ownerTs->tsMutex.Unlock (); // Unlock if right return result; } else return NotEnqueued; // All mutex that have been locked are unlocked! } void ThreadedJobQueue::WaitAll () { while(!IsFinished ()) { for (size_t i = 0; i < numWorkerThreads; ++i) { ThreadState* ts = allThreadState[i]; MutexScopedLock l (ts->tsMutex); if(ts->currentJob || ts->jobQueue.GetSize() > 0) { // Have a job, wait for it ts->tsJobFinished.Wait (ts->tsMutex); } } } } bool ThreadedJobQueue::IsFinished () { int32 c = CS::Threading::AtomicOperations::Read (&outstandingJobs); return c == 0; } int32 ThreadedJobQueue::GetQueueCount() { return CS::Threading::AtomicOperations::Read(&outstandingJobs); } bool ThreadedJobQueue::PullFromQueues (iJob* job) { // Check all the thread queues for (size_t i = 0; i < numWorkerThreads; ++i) { ThreadState* ts = allThreadState[i]; MutexScopedLock l (ts->tsMutex); bool removedJob = ts->jobQueue.Delete (job); if (removedJob) { CS::Threading::AtomicOperations::Decrement(&outstandingJobs); return true; } } return false; } ThreadedJobQueue::QueueRunnable::QueueRunnable (ThreadedJobQueue* queue, ThreadState* ts, unsigned int id) : ownerQueue (queue), shutdownQueue (0), threadState (ts) { name.Format ("#%u %s", id, queue->GetName()); } void ThreadedJobQueue::QueueRunnable::Run () { // Forcibly keep QueueRunnable object alive until we got a shutdown this->IncRef(); while (CS::Threading::AtomicOperations::Read(&(/*ownerQueue->*/shutdownQueue)) == 0x0) { // Get a job csRef<iJob> currentJob; // Try our own list first // We need to hold this until currentJob is set, otherwise something might slip through in "wait" threadState->tsMutex.Lock (); if (threadState->jobQueue.GetSize () > 0) { currentJob = threadState->jobQueue.PopTop (); } if (!currentJob) { // If we couldn't get any job, try to steal. At most try to steal once // from each of the other threads size_t start; { MutexScopedLock l (rgenLock); start = rgen.Get ((uint32)ownerQueue->numWorkerThreads); } for (size_t i = 0, index = start; i < ownerQueue->numWorkerThreads; ++i, index = (index + 1) % ownerQueue->numWorkerThreads ) { ThreadState* foreignTS = ownerQueue->allThreadState[index]; if (foreignTS == threadState) continue; // Try to lock it, but never wait for a lock if (foreignTS->tsMutex.TryLock ()) // Lock foreign object A { // Get the job if (foreignTS->jobQueue.GetSize() > 0) { currentJob = foreignTS->jobQueue.PopBottom (); foreignTS->tsMutex.Unlock (); // Unlock foreign object A if success break; } foreignTS->tsMutex.Unlock (); // Unlock foreign object A if unsuccessful } } } if (currentJob) { // Got one, execute threadState->currentJob = currentJob; threadState->tsMutex.Unlock (); // Unlock our own TS after getting a job currentJob->Run (); /* Release reference to job only until after the last access of the thread manager. This is a cautionary measure: the _job_ may keep the last ref to the TM; releasing the job will also release the TM, causing segfaults upon accesses to it. Thus keep it until after having accessed the TM for the last time. */ csRef<iJob> justKeepCurrentJobRefALittleLonger (currentJob); { MutexScopedLock l (threadState->tsMutex); threadState->currentJob = 0; currentJob = 0; } CS::Threading::AtomicOperations::Decrement(&(ownerQueue->outstandingJobs)); threadState->tsJobFinished.NotifyAll (); } else { // Couldn't get one, wait for a newly added job threadState->tsNewJob.Wait (threadState->tsMutex); threadState->tsMutex.Unlock (); } } // There is a circular ref between ThreadState and QueueRunnable, break it up threadState.Invalidate(); this->DecRef(); } const char* ThreadedJobQueue::QueueRunnable::GetName () const { return name.GetDataSafe (); } } } <|endoftext|>
<commit_before>/* +---------------------------------------------------------------------------+ | The Mobile Robot Programming Toolkit (MRPT) | | | | http://www.mrpt.org/ | | | | Copyright (c) 2005-2013, Individual contributors, see AUTHORS file | | Copyright (c) 2005-2013, MAPIR group, University of Malaga | | Copyright (c) 2012-2013, University of Almeria | | 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 HOLDERS 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 <mrpt/hwdrivers.h> // Precompiled headers #include <mrpt/hwdrivers/CRaePID.h> #include <iostream> #include <sstream> using namespace mrpt::utils; using namespace mrpt::hwdrivers; IMPLEMENTS_GENERIC_SENSOR(CRaePID,mrpt::hwdrivers) /* ----------------------------------------------------- Constructor ----------------------------------------------------- */ CRaePID::CRaePID() { m_sensorLabel = "RAE_PID"; } /* ----------------------------------------------------- loadConfig_sensorSpecific ----------------------------------------------------- */ void CRaePID::loadConfig_sensorSpecific( const mrpt::utils::CConfigFileBase &configSource, const std::string &iniSection ) { #ifdef MRPT_OS_WINDOWS com_port = configSource.read_string(iniSection, "COM_port_PID", "COM1", true ) ; #else com_port = configSource.read_string(iniSection, "COM_port_PID", "/dev/tty0", true ); #endif com_bauds = configSource.read_int( iniSection, "baudRate",9600, false ); pose_x = configSource.read_float(iniSection,"pose_x",0,true); pose_y = configSource.read_float(iniSection,"pose_y",0,true); pose_z = configSource.read_float(iniSection,"pose_z",0,true); pose_roll = configSource.read_float(iniSection,"pose_roll",0,true); pose_pitch = configSource.read_float(iniSection,"pose_pitch",0,true); pose_yaw = configSource.read_float(iniSection,"pose_yaw",0,true); } /* ----------------------------------------------------- tryToOpenTheCOM ----------------------------------------------------- */ bool CRaePID::tryToOpenTheCOM() { if (COM.isOpen()) return true; // Already open if (m_verbose) cout << "[CRaePID] Opening " << com_port << " @ " <<com_bauds << endl; try { COM.open(com_port); // Config: COM.setConfig( com_bauds, 0, 8, 1 ); //COM.setTimeouts( 1, 0, 1, 1, 1 ); COM.setTimeouts(50,1,100, 1,20); //mrpt::system::sleep(10); COM.purgeBuffers(); //mrpt::system::sleep(10); return true; // All OK! } catch (std::exception &e) { std::cerr << "[CRaePID::tryToOpenTheCOM] Error opening or configuring the serial port:" << std::endl << e.what(); COM.close(); return false; } catch (...) { std::cerr << "[CRaePID::tryToOpenTheCOM] Error opening or configuring the serial port." << std::endl; COM.close(); return false; } } /* ----------------------------------------------------- doProcess ----------------------------------------------------- */ void CRaePID::doProcess() { // Is the COM open? if (!tryToOpenTheCOM()) { m_state = ssError; THROW_EXCEPTION("Cannot open the serial port"); } bool have_reading = false; std::string power_reading; bool time_out = false; while (!have_reading) { // Send command to PID to request a measurement COM.purgeBuffers(); COM.Write("R",1); // Read PID response power_reading = COM.ReadString(500,&time_out); if (time_out) { cout << "[CRaePID] " << com_port << " @ " <<com_bauds << " - measurement Timed-Out" << endl; sleep(10); } else have_reading = true; } cout << "[CRaePID] " << com_port << " @ " <<com_bauds << " - measurement -> " << power_reading << endl; // Convert the text to a number (ppm) const float readnum = atof(power_reading.c_str()); const float val_ppm = readnum/1000; // Fill the observation mrpt::slam::CObservationGasSensors::TObservationENose obs; obs.readingsVoltage.push_back(val_ppm); obs.sensorTypes.push_back(0xFFFF); CObservationGasSensors obsG; obsG.sensorLabel = this->getSensorLabel(); obsG.m_readings.push_back(obs); obsG.timestamp = now(); appendObservation(CObservationGasSensorsPtr(new CObservationGasSensors(obsG))); } std::string CRaePID::getFirmware() { // Send the command cout << "Firmware version: " << endl; COM.purgeBuffers(); size_t B_written = COM.Write("F",1); // Read the returned text bool time_out = false; std::string s_read = COM.ReadString(2000,&time_out); if (time_out) s_read = "Time_out"; return s_read; } std::string CRaePID::getModel() { // Send the command COM.purgeBuffers(); COM.Write("M",1); // Read the returned text return COM.ReadString(); } std::string CRaePID::getSerialNumber() { // Send the command COM.purgeBuffers(); COM.Write("S",1); // Read the returned text return COM.ReadString(); } std::string CRaePID::getName() { // Send the command COM.purgeBuffers(); COM.Write("N",1); // Read the returned text return COM.ReadString(); } bool CRaePID::switchPower() { // Send the command COM.purgeBuffers(); COM.Write("P",1); // Read the returned text std::string reading; reading = COM.ReadString(); if (strcmp(reading.c_str(),"Sleep...")==0) return true; else return false; } CObservationGasSensors CRaePID::getFullInfo() { // Send the command COM.purgeBuffers(); COM.Write("C",1); // Read the returned text std::string reading; reading = COM.ReadString(); // Iterate over each information component (tokenize first) // construct a stream from the string (as seen in http://stackoverflow.com/a/53921) std::stringstream readings_str(reading); // use stream iterators to copy the stream to the vector as whitespace separated strings std::istream_iterator<std::string> it(readings_str); std::istream_iterator<std::string> endit; std::vector<std::string> measurements_text(it, endit); // Convert the text to a number (ppm) mrpt::slam::CObservationGasSensors::TObservationENose obs; CObservationGasSensors obsG; for (size_t k=0; k < measurements_text.size(); k++) { const float readnum = atof(measurements_text[k].c_str()); const float val_ppm = readnum/1000.f; // Fill the observation obs.readingsVoltage.push_back(val_ppm); obsG.m_readings.push_back(obs); } obsG.sensorLabel = this->getSensorLabel(); obsG.timestamp = now(); return obsG; } bool CRaePID::errorStatus(std::string &errorString) { // Send the command COM.purgeBuffers(); COM.Write("E",1); // Read the returned text std::string reading; reading = COM.ReadString(); // Tokenize to separate the two components: // construct a stream from the string (as seen in http://stackoverflow.com/a/53921) std::stringstream readings_str(reading); // use stream iterators to copy the stream to the vector as whitespace separated strings std::istream_iterator<std::string> it(readings_str); std::istream_iterator<std::string> endit; std::vector<std::string> errors_text(it, endit); // Take the first part and check the possible error condition if((strcmp(errors_text[0].c_str(),"0")==0) && (strcmp(errors_text[1].c_str(),"0")==0)) // no error { return false; } else { // By the moment, return the raw error; note that if necessary a detailed description of the error can be obtained analyzing the two error strings separately errorString = reading; return true; } } void CRaePID::getLimits(float &min, float &max) { // Send the command COM.purgeBuffers(); COM.Write("L",1); // Read the returned text std::string reading; reading = COM.ReadString(); // Tokenize to separate the two components: // construct a stream from the string (as seen in http://stackoverflow.com/a/53921) std::stringstream readings_str(reading); // use stream iterators to copy the stream to the vector as whitespace separated strings std::istream_iterator<std::string> it(readings_str); std::istream_iterator<std::string> endit; std::vector<std::string> readings_text(it, endit); // read min and max max = atof(readings_text[0].c_str()); min = atof(readings_text[1].c_str()); } <commit_msg>CRaePID: fixed GCC warning<commit_after>/* +---------------------------------------------------------------------------+ | The Mobile Robot Programming Toolkit (MRPT) | | | | http://www.mrpt.org/ | | | | Copyright (c) 2005-2013, Individual contributors, see AUTHORS file | | Copyright (c) 2005-2013, MAPIR group, University of Malaga | | Copyright (c) 2012-2013, University of Almeria | | 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 HOLDERS 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 <mrpt/hwdrivers.h> // Precompiled headers #include <mrpt/hwdrivers/CRaePID.h> #include <iostream> #include <sstream> using namespace mrpt::utils; using namespace mrpt::hwdrivers; IMPLEMENTS_GENERIC_SENSOR(CRaePID,mrpt::hwdrivers) /* ----------------------------------------------------- Constructor ----------------------------------------------------- */ CRaePID::CRaePID() { m_sensorLabel = "RAE_PID"; } /* ----------------------------------------------------- loadConfig_sensorSpecific ----------------------------------------------------- */ void CRaePID::loadConfig_sensorSpecific( const mrpt::utils::CConfigFileBase &configSource, const std::string &iniSection ) { #ifdef MRPT_OS_WINDOWS com_port = configSource.read_string(iniSection, "COM_port_PID", "COM1", true ) ; #else com_port = configSource.read_string(iniSection, "COM_port_PID", "/dev/tty0", true ); #endif com_bauds = configSource.read_int( iniSection, "baudRate",9600, false ); pose_x = configSource.read_float(iniSection,"pose_x",0,true); pose_y = configSource.read_float(iniSection,"pose_y",0,true); pose_z = configSource.read_float(iniSection,"pose_z",0,true); pose_roll = configSource.read_float(iniSection,"pose_roll",0,true); pose_pitch = configSource.read_float(iniSection,"pose_pitch",0,true); pose_yaw = configSource.read_float(iniSection,"pose_yaw",0,true); } /* ----------------------------------------------------- tryToOpenTheCOM ----------------------------------------------------- */ bool CRaePID::tryToOpenTheCOM() { if (COM.isOpen()) return true; // Already open if (m_verbose) cout << "[CRaePID] Opening " << com_port << " @ " <<com_bauds << endl; try { COM.open(com_port); // Config: COM.setConfig( com_bauds, 0, 8, 1 ); //COM.setTimeouts( 1, 0, 1, 1, 1 ); COM.setTimeouts(50,1,100, 1,20); //mrpt::system::sleep(10); COM.purgeBuffers(); //mrpt::system::sleep(10); return true; // All OK! } catch (std::exception &e) { std::cerr << "[CRaePID::tryToOpenTheCOM] Error opening or configuring the serial port:" << std::endl << e.what(); COM.close(); return false; } catch (...) { std::cerr << "[CRaePID::tryToOpenTheCOM] Error opening or configuring the serial port." << std::endl; COM.close(); return false; } } /* ----------------------------------------------------- doProcess ----------------------------------------------------- */ void CRaePID::doProcess() { // Is the COM open? if (!tryToOpenTheCOM()) { m_state = ssError; THROW_EXCEPTION("Cannot open the serial port"); } bool have_reading = false; std::string power_reading; bool time_out = false; while (!have_reading) { // Send command to PID to request a measurement COM.purgeBuffers(); COM.Write("R",1); // Read PID response power_reading = COM.ReadString(500,&time_out); if (time_out) { cout << "[CRaePID] " << com_port << " @ " <<com_bauds << " - measurement Timed-Out" << endl; sleep(10); } else have_reading = true; } cout << "[CRaePID] " << com_port << " @ " <<com_bauds << " - measurement -> " << power_reading << endl; // Convert the text to a number (ppm) const float readnum = atof(power_reading.c_str()); const float val_ppm = readnum/1000; // Fill the observation mrpt::slam::CObservationGasSensors::TObservationENose obs; obs.readingsVoltage.push_back(val_ppm); obs.sensorTypes.push_back(0xFFFF); CObservationGasSensors obsG; obsG.sensorLabel = this->getSensorLabel(); obsG.m_readings.push_back(obs); obsG.timestamp = now(); appendObservation(CObservationGasSensorsPtr(new CObservationGasSensors(obsG))); } std::string CRaePID::getFirmware() { // Send the command cout << "Firmware version: " << endl; COM.purgeBuffers(); size_t B_written = COM.Write("F",1); if (!B_written) return std::string("COMMS.ERROR"); // Read the returned text bool time_out = false; std::string s_read = COM.ReadString(2000,&time_out); if (time_out) s_read = "Time_out"; return s_read; } std::string CRaePID::getModel() { // Send the command COM.purgeBuffers(); COM.Write("M",1); // Read the returned text return COM.ReadString(); } std::string CRaePID::getSerialNumber() { // Send the command COM.purgeBuffers(); COM.Write("S",1); // Read the returned text return COM.ReadString(); } std::string CRaePID::getName() { // Send the command COM.purgeBuffers(); COM.Write("N",1); // Read the returned text return COM.ReadString(); } bool CRaePID::switchPower() { // Send the command COM.purgeBuffers(); COM.Write("P",1); // Read the returned text std::string reading; reading = COM.ReadString(); if (strcmp(reading.c_str(),"Sleep...")==0) return true; else return false; } CObservationGasSensors CRaePID::getFullInfo() { // Send the command COM.purgeBuffers(); COM.Write("C",1); // Read the returned text std::string reading; reading = COM.ReadString(); // Iterate over each information component (tokenize first) // construct a stream from the string (as seen in http://stackoverflow.com/a/53921) std::stringstream readings_str(reading); // use stream iterators to copy the stream to the vector as whitespace separated strings std::istream_iterator<std::string> it(readings_str); std::istream_iterator<std::string> endit; std::vector<std::string> measurements_text(it, endit); // Convert the text to a number (ppm) mrpt::slam::CObservationGasSensors::TObservationENose obs; CObservationGasSensors obsG; for (size_t k=0; k < measurements_text.size(); k++) { const float readnum = atof(measurements_text[k].c_str()); const float val_ppm = readnum/1000.f; // Fill the observation obs.readingsVoltage.push_back(val_ppm); obsG.m_readings.push_back(obs); } obsG.sensorLabel = this->getSensorLabel(); obsG.timestamp = now(); return obsG; } bool CRaePID::errorStatus(std::string &errorString) { // Send the command COM.purgeBuffers(); COM.Write("E",1); // Read the returned text std::string reading; reading = COM.ReadString(); // Tokenize to separate the two components: // construct a stream from the string (as seen in http://stackoverflow.com/a/53921) std::stringstream readings_str(reading); // use stream iterators to copy the stream to the vector as whitespace separated strings std::istream_iterator<std::string> it(readings_str); std::istream_iterator<std::string> endit; std::vector<std::string> errors_text(it, endit); // Take the first part and check the possible error condition if((strcmp(errors_text[0].c_str(),"0")==0) && (strcmp(errors_text[1].c_str(),"0")==0)) // no error { return false; } else { // By the moment, return the raw error; note that if necessary a detailed description of the error can be obtained analyzing the two error strings separately errorString = reading; return true; } } void CRaePID::getLimits(float &min, float &max) { // Send the command COM.purgeBuffers(); COM.Write("L",1); // Read the returned text std::string reading; reading = COM.ReadString(); // Tokenize to separate the two components: // construct a stream from the string (as seen in http://stackoverflow.com/a/53921) std::stringstream readings_str(reading); // use stream iterators to copy the stream to the vector as whitespace separated strings std::istream_iterator<std::string> it(readings_str); std::istream_iterator<std::string> endit; std::vector<std::string> readings_text(it, endit); // read min and max max = atof(readings_text[0].c_str()); min = atof(readings_text[1].c_str()); } <|endoftext|>
<commit_before>#include "ui/socket_item.h" #include <QApplication> #include <QCursor> #include <QDebug> #include <QDrag> #include <QGraphicsSceneMouseEvent> #include <QGraphicsWidget> #include <QMimeData> #include <QWidget> #include "elements/package.h" #include "ui/colors.h" #include "ui/link_item.h" #include "ui/package_view.h" SocketItem::SocketItem(Type a_type, QGraphicsItem *const a_parent) : QGraphicsItem{ a_parent } , m_type{ a_type } { m_font.setFamily("Consolas"); m_font.setPointSize(12); setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsFocusable | QGraphicsItem::ItemSendsScenePositionChanges); setAcceptHoverEvents(true); setAcceptedMouseButtons(Qt::LeftButton); setZValue(1); if (a_type == Type::eOutput) setCursor(Qt::OpenHandCursor); else setAcceptDrops(true); } QRectF SocketItem::boundingRect() const { return QRectF{ -(static_cast<qreal>(SIZE) / 2.), 0, static_cast<qreal>(SIZE), static_cast<qreal>(SIZE) }; } void SocketItem::paint(QPainter *a_painter, const QStyleOptionGraphicsItem *a_option, QWidget *a_widget) { Q_UNUSED(a_option); Q_UNUSED(a_widget); QRectF const rect{ boundingRect() }; QPen pen{ get_color(Color::eSocketBorder) }; pen.setWidth(2); QBrush brush{}; if (m_isHover) brush.setColor(get_color(Color::eSocketHover)); else if (m_isDrop) brush.setColor(get_color(Color::eSocketDrop)); else if (m_isSignalOn) brush.setColor(m_colorSignalOn); else if (!m_isSignalOn) brush.setColor(m_colorSignalOff); // else if (m_type == Type::eInput) // brush.setColor(config.getColor(Config::Color::eSocketInput)); // else if (m_type == Type::eOutput) // brush.setColor(config.getColor(Config::Color::eSocketOutput)); brush.setStyle(Qt::SolidPattern); a_painter->setPen(pen); a_painter->setBrush(brush); a_painter->drawEllipse(rect); if (m_used) { a_painter->save(); a_painter->setPen(Qt::NoPen); a_painter->setBrush(pen.color()); a_painter->drawEllipse(rect.adjusted(4, 4, -4, -4)); a_painter->restore(); } if (!m_nameHidden) { pen.setColor(get_color(Color::eFontName)); a_painter->setPen(pen); QFont font{ a_painter->font() }; font.setPointSize(12); a_painter->setFont(font); QFontMetrics const metrics{ font }; if (m_type == Type::eInput) a_painter->drawText(static_cast<int>(rect.width()) - 2, 13, m_name); else a_painter->drawText(-metrics.width(m_name) - 14, 13, m_name); } } void SocketItem::hoverEnterEvent(QGraphicsSceneHoverEvent *a_event) { Q_UNUSED(a_event); m_isHover = true; for (auto const link : m_links) link->setHover(m_isHover); } void SocketItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *a_event) { Q_UNUSED(a_event); m_isHover = false; for (auto const link : m_links) link->setHover(m_isHover); } void SocketItem::dragEnterEvent(QGraphicsSceneDragDropEvent *a_event) { Q_UNUSED(a_event); if (m_used) { a_event->ignore(); return; } PackageView *const view{ reinterpret_cast<PackageView *const>(scene()->views()[0]) }; LinkItem *const linkItem{ view->dragLink() }; if (!linkItem || m_valueType != linkItem->valueType()) { a_event->ignore(); return; } linkItem->setTo(this); m_isDrop = true; } void SocketItem::dragLeaveEvent(QGraphicsSceneDragDropEvent *a_event) { Q_UNUSED(a_event); m_isDrop = false; PackageView *const view{ reinterpret_cast<PackageView *const>(scene()->views()[0]) }; LinkItem *const linkItem{ view->dragLink() }; if (!linkItem) return; linkItem->setTo(nullptr); } void SocketItem::dragMoveEvent(QGraphicsSceneDragDropEvent *a_event) { Q_UNUSED(a_event); } void SocketItem::dropEvent(QGraphicsSceneDragDropEvent *a_event) { Q_UNUSED(a_event); PackageView *const packageView{ reinterpret_cast<PackageView *const>(scene()->views()[0]) }; LinkItem *const linkItem{ packageView->dragLink() }; if (!linkItem) return; m_links.push_back(linkItem); linkItem->setTo(this); m_used = true; m_isDrop = false; packageView->acceptDragLink(); auto const package = packageView->package(); auto const from = linkItem->from(); package->connect(from->elementId(), from->socketId(), m_elementId, m_socketId); setSignal(linkItem->isSignalOn()); } void SocketItem::mousePressEvent(QGraphicsSceneMouseEvent *a_event) { Q_UNUSED(a_event); if (m_type == Type::eInput) return; setCursor(Qt::ClosedHandCursor); } void SocketItem::mouseMoveEvent(QGraphicsSceneMouseEvent *a_event) { Q_UNUSED(a_event); if (m_type == Type::eInput) return; if (QLineF(a_event->screenPos(), a_event->buttonDownScreenPos(Qt::LeftButton)).length() < QApplication::startDragDistance()) return; // QRectF const rect{ boundingRect() }; QDrag *const drag = new QDrag(a_event->widget()); QMimeData *const mime = new QMimeData; // mime->setData("data/x-element", QByteArray()); drag->setMimeData(mime); LinkItem *linkItem{ new LinkItem }; linkItem->setColors(m_colorSignalOff, m_colorSignalOn); linkItem->setFrom(this); scene()->addItem(linkItem); PackageView *const view{ reinterpret_cast<PackageView *const>(scene()->views()[0]) }; view->setDragLink(linkItem); Qt::DropAction const action{ drag->exec() }; if (action == Qt::IgnoreAction) view->cancelDragLink(); else { m_links.push_back(linkItem); m_used = true; } setCursor(Qt::OpenHandCursor); } void SocketItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *a_event) { Q_UNUSED(a_event); if (m_type == Type::eInput) return; setCursor(Qt::OpenHandCursor); } QVariant SocketItem::itemChange(QGraphicsItem::GraphicsItemChange a_change, const QVariant &a_value) { if (a_change == QGraphicsItem::ItemScenePositionHasChanged) { for (LinkItem *const link : m_links) link->trackNodes(); } return QGraphicsItem::itemChange(a_change, a_value); } int SocketItem::nameWidth() const { QFontMetrics const metrics{ m_font }; return metrics.width(m_name); } void SocketItem::setColors(QColor const a_signalOff, QColor const a_signalOn) { m_colorSignalOff = a_signalOff; m_colorSignalOn = a_signalOn; } void SocketItem::setSignal(const bool a_signal) { m_isSignalOn = a_signal; if (m_type == Type::eOutput) for (LinkItem *const link : m_links) link->setSignal(a_signal); } void SocketItem::connect(SocketItem *const a_other) { auto const linkItem = new LinkItem; linkItem->setColors(m_colorSignalOff, m_colorSignalOn); linkItem->setFrom(this); linkItem->setTo(a_other); m_links.push_back(linkItem); m_used = true; a_other->m_links.push_back(linkItem); a_other->m_used = true; a_other->m_isDrop = false; scene()->addItem(linkItem); } <commit_msg>Fix SocketItem::mouseMoveEvent<commit_after>#include "ui/socket_item.h" #include <QApplication> #include <QCursor> #include <QDebug> #include <QDrag> #include <QGraphicsSceneMouseEvent> #include <QGraphicsWidget> #include <QMimeData> #include <QWidget> #include "elements/package.h" #include "ui/colors.h" #include "ui/link_item.h" #include "ui/package_view.h" SocketItem::SocketItem(Type a_type, QGraphicsItem *const a_parent) : QGraphicsItem{ a_parent } , m_type{ a_type } { m_font.setFamily("Consolas"); m_font.setPointSize(12); setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsFocusable | QGraphicsItem::ItemSendsScenePositionChanges); setAcceptHoverEvents(true); setAcceptedMouseButtons(Qt::LeftButton); setZValue(1); if (a_type == Type::eOutput) setCursor(Qt::OpenHandCursor); else setAcceptDrops(true); } QRectF SocketItem::boundingRect() const { return QRectF{ -(static_cast<qreal>(SIZE) / 2.), 0, static_cast<qreal>(SIZE), static_cast<qreal>(SIZE) }; } void SocketItem::paint(QPainter *a_painter, const QStyleOptionGraphicsItem *a_option, QWidget *a_widget) { Q_UNUSED(a_option); Q_UNUSED(a_widget); QRectF const rect{ boundingRect() }; QPen pen{ get_color(Color::eSocketBorder) }; pen.setWidth(2); QBrush brush{}; if (m_isHover) brush.setColor(get_color(Color::eSocketHover)); else if (m_isDrop) brush.setColor(get_color(Color::eSocketDrop)); else if (m_isSignalOn) brush.setColor(m_colorSignalOn); else if (!m_isSignalOn) brush.setColor(m_colorSignalOff); // else if (m_type == Type::eInput) // brush.setColor(config.getColor(Config::Color::eSocketInput)); // else if (m_type == Type::eOutput) // brush.setColor(config.getColor(Config::Color::eSocketOutput)); brush.setStyle(Qt::SolidPattern); a_painter->setPen(pen); a_painter->setBrush(brush); a_painter->drawEllipse(rect); if (m_used) { a_painter->save(); a_painter->setPen(Qt::NoPen); a_painter->setBrush(pen.color()); a_painter->drawEllipse(rect.adjusted(4, 4, -4, -4)); a_painter->restore(); } if (!m_nameHidden) { pen.setColor(get_color(Color::eFontName)); a_painter->setPen(pen); QFont font{ a_painter->font() }; font.setPointSize(12); a_painter->setFont(font); QFontMetrics const metrics{ font }; if (m_type == Type::eInput) a_painter->drawText(static_cast<int>(rect.width()) - 2, 13, m_name); else a_painter->drawText(-metrics.width(m_name) - 14, 13, m_name); } } void SocketItem::hoverEnterEvent(QGraphicsSceneHoverEvent *a_event) { Q_UNUSED(a_event); m_isHover = true; for (auto const link : m_links) link->setHover(m_isHover); } void SocketItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *a_event) { Q_UNUSED(a_event); m_isHover = false; for (auto const link : m_links) link->setHover(m_isHover); } void SocketItem::dragEnterEvent(QGraphicsSceneDragDropEvent *a_event) { Q_UNUSED(a_event); if (m_used) { a_event->ignore(); return; } PackageView *const view{ reinterpret_cast<PackageView *const>(scene()->views()[0]) }; LinkItem *const linkItem{ view->dragLink() }; if (!linkItem || m_valueType != linkItem->valueType()) { a_event->ignore(); return; } linkItem->setTo(this); m_isDrop = true; } void SocketItem::dragLeaveEvent(QGraphicsSceneDragDropEvent *a_event) { Q_UNUSED(a_event); m_isDrop = false; PackageView *const view{ reinterpret_cast<PackageView *const>(scene()->views()[0]) }; LinkItem *const linkItem{ view->dragLink() }; if (!linkItem) return; linkItem->setTo(nullptr); } void SocketItem::dragMoveEvent(QGraphicsSceneDragDropEvent *a_event) { Q_UNUSED(a_event); } void SocketItem::dropEvent(QGraphicsSceneDragDropEvent *a_event) { Q_UNUSED(a_event); PackageView *const packageView{ reinterpret_cast<PackageView *const>(scene()->views()[0]) }; LinkItem *const linkItem{ packageView->dragLink() }; if (!linkItem) return; m_links.push_back(linkItem); linkItem->setTo(this); m_used = true; m_isDrop = false; packageView->acceptDragLink(); auto const package = packageView->package(); auto const from = linkItem->from(); package->connect(from->elementId(), from->socketId(), m_elementId, m_socketId); setSignal(linkItem->isSignalOn()); } void SocketItem::mousePressEvent(QGraphicsSceneMouseEvent *a_event) { Q_UNUSED(a_event); if (m_type == Type::eInput) return; setCursor(Qt::ClosedHandCursor); } void SocketItem::mouseMoveEvent(QGraphicsSceneMouseEvent *a_event) { Q_UNUSED(a_event); if (m_type == Type::eInput) return; if (QLineF(a_event->screenPos(), a_event->buttonDownScreenPos(Qt::LeftButton)).length() < QApplication::startDragDistance()) return; QDrag *const drag = new QDrag(a_event->widget()); QMimeData *const mime = new QMimeData; drag->setMimeData(mime); LinkItem *linkItem{ new LinkItem }; linkItem->setColors(m_colorSignalOff, m_colorSignalOn); linkItem->setValueType(m_valueType); linkItem->setFrom(this); linkItem->setSignal(m_isSignalOn); scene()->addItem(linkItem); m_links.push_back(linkItem); PackageView *const view{ reinterpret_cast<PackageView *const>(scene()->views()[0]) }; view->setDragLink(linkItem); Qt::DropAction const action{ drag->exec() }; if (action == Qt::IgnoreAction) { m_links.removeAll(linkItem); scene()->removeItem(linkItem); view->cancelDragLink(); } else m_used = true; setCursor(Qt::OpenHandCursor); } void SocketItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *a_event) { Q_UNUSED(a_event); if (m_type == Type::eInput) return; setCursor(Qt::OpenHandCursor); } QVariant SocketItem::itemChange(QGraphicsItem::GraphicsItemChange a_change, const QVariant &a_value) { if (a_change == QGraphicsItem::ItemScenePositionHasChanged) { for (LinkItem *const link : m_links) link->trackNodes(); } return QGraphicsItem::itemChange(a_change, a_value); } int SocketItem::nameWidth() const { QFontMetrics const metrics{ m_font }; return metrics.width(m_name); } void SocketItem::setColors(QColor const a_signalOff, QColor const a_signalOn) { m_colorSignalOff = a_signalOff; m_colorSignalOn = a_signalOn; } void SocketItem::setSignal(const bool a_signal) { m_isSignalOn = a_signal; if (m_type == Type::eOutput) for (LinkItem *const link : m_links) link->setSignal(a_signal); } void SocketItem::connect(SocketItem *const a_other) { auto const linkItem = new LinkItem; linkItem->setColors(m_colorSignalOff, m_colorSignalOn); linkItem->setValueType(m_valueType); linkItem->setFrom(this); linkItem->setTo(a_other); m_links.push_back(linkItem); m_used = true; a_other->m_links.push_back(linkItem); a_other->m_used = true; a_other->m_isDrop = false; scene()->addItem(linkItem); } <|endoftext|>
<commit_before>#include <stdexcept> #include <iostream> #include <iomanip> #include <sstream> #include <string> using namespace std; int main() { int n; cin>>n; int countn = 0;double sum = 0.0; for(int i = 0;i < n;i++) { string temps; double tempd; cin>>temps; bool flag = true; try{tempd = stof(temps);} catch(invalid_argument e) {flag = false;} if(flag) { stringstream ss; ss << temps; ss >> tempd; ss.clear(); ss.str(""); if(tempd >= -1000 && tempd <= 1000) { if(tempd*100 - (int)(tempd*100) == 0) { sum += tempd; countn++; } else flag = false; } else flag = false; } if(!flag) cout<<"ERROR: "<<temps<<" is not a legal number"<<endl; } cout.setf(ios::fixed); if(!countn) cout<<"The average of 0 numbers is Undefined"<<endl; else if(countn == 1) cout<<"The average of "<<countn<<" number is "<<setprecision(2)<<sum/countn<<endl; else cout<<"The average of "<<countn<<" numbers is "<<setprecision(2)<<sum/countn<<endl; } <commit_msg>Update 1054.cpp<commit_after>#include <stdexcept> #include <algorithm> #include <iostream> #include <iomanip> #include <string> #include <cctype> using namespace std; int main() { int n; cin>>n; int countn = 0;double sum = 0.0; for(int i = 0;i < n;i++) { string temps; double tempd; cin>>temps; bool flag = true; if(count(temps.begin(),temps.end(),'.') > 1) flag = false; try{tempd = stod(temps);} catch(invalid_argument e) {flag = false;} if((temps.end() - find(temps.begin(),temps.end(),'.')) > 3) flag = false; else if((!isdigit(temps.front()) && temps.front() != '-') || (temps.front() == '-' && !isdigit(*(temps.begin()+1)))) flag = false; if(flag) { tempd = stod(temps); if(tempd >= -1000.00 && tempd <= 1000.00) { sum += tempd; countn++; } else flag = false; } if(!flag) cout<<"ERROR: "<<temps<<" is not a legal number"<<endl; } cout.setf(ios::fixed); if(!countn) cout<<"The average of 0 numbers is Undefined"<<endl; else if(countn == 1) cout<<"The average of "<<countn<<" number is "<<setprecision(2)<<sum/countn<<endl; else cout<<"The average of "<<countn<<" numbers is "<<setprecision(2)<<sum/countn<<endl; } <|endoftext|>
<commit_before>#include <assert.h> #include <stdlib.h> extern "C" void __cxa_pure_virtual(void) { /* Pure C++ virtual call; abort! */ assert(false); } void* __weak operator new(size_t size) { return malloc(size); } void* __weak operator new[](size_t size) { return malloc(size); } void __weak operator delete(void *ptr) { free(ptr); } void __weak operator delete[](void *ptr) { free(ptr); } <commit_msg>Add new operator overloads from new C++ standards (C++11 on onward)<commit_after>#include <assert.h> #include <stdlib.h> extern "C" void __cxa_pure_virtual(void) { /* Pure C++ virtual call; abort! */ assert(false); } void* __weak operator new(size_t size) { return malloc(size); } void* __weak operator new[](size_t size) { return malloc(size); } void __weak operator delete(void* ptr) { free(ptr); } void __weak operator delete[](void* ptr) { free(ptr); } /*- * <https://en.cppreference.com/w/cpp/memory/new/operator_delete> * * Called if a user-defined replacement is provided, except that it's * unspecified whether other overloads or this overload is called when deleting * objects of incomplete type and arrays of non-class and trivially-destructible * class types. * * A memory allocator can use the given size to be more efficient */ void __weak operator delete(void* ptr, unsigned int) { free(ptr); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: spelldsp.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: tl $ $Date: 2001-06-05 11:28:25 $ * * 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 _LINGUISTIC_SPELLDSP_HXX_ #define _LINGUISTIC_SPELLDSP_HXX_ #include "lngopt.hxx" #include "misc.hxx" #include "iprcache.hxx" #include <uno/lbnames.h> // CPPU_CURRENT_LANGUAGE_BINDING_NAME macro, which specify the environment type #include <cppuhelper/implbase1.hxx> // helper for implementations #include <cppuhelper/implbase2.hxx> // helper for implementations #include <cppuhelper/implbase7.hxx> // helper for implementations #ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_ #include <com/sun/star/lang/XComponent.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_ #include <com/sun/star/lang/XInitialization.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEDISPLAYNAME_HPP_ #include <com/sun/star/lang/XServiceDisplayName.hpp> #endif #include <com/sun/star/beans/XPropertySet.hpp> #include <com/sun/star/beans/PropertyValues.hpp> #include <com/sun/star/lang/XServiceInfo.hpp> #include <com/sun/star/linguistic2/XSpellChecker.hpp> #include <com/sun/star/linguistic2/XSpellChecker1.hpp> #include <com/sun/star/linguistic2/XSearchableDictionaryList.hpp> #include <com/sun/star/linguistic2/XLinguServiceEventBroadcaster.hpp> #ifndef _TOOLS_TABLE_HXX #include <tools/table.hxx> #endif class LngSvcMgr; /////////////////////////////////////////////////////////////////////////// class SeqLangSvcEntry_Spell { friend class SpellCheckerDispatcher; friend static BOOL SvcListHasLanguage( const SeqLangSvcEntry_Spell &rEntry, INT16 nLanguage ); ::com::sun::star::uno::Sequence< ::rtl::OUString > aSvcImplNames; ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XSpellChecker > > aSvcRefs; ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XSpellChecker1 > > aSvc1Refs; // INT16 nLang; //used as key in the table SvcFlags aFlags; public: SeqLangSvcEntry_Spell() {} SeqLangSvcEntry_Spell( const ::com::sun::star::uno::Sequence< ::rtl::OUString > &rSvcImplNames ); ~SeqLangSvcEntry_Spell(); BOOL IsAlreadyWarned() const { return aFlags.bAlreadyWarned != 0; } void SetAlreadyWarned(BOOL bVal) { aFlags.bAlreadyWarned = 0 != bVal; } BOOL IsDoWarnAgain() const { return aFlags.bDoWarnAgain != 0; } void SetDoWarnAgain(BOOL bVal) { aFlags.bDoWarnAgain = 0 != bVal; } }; DECLARE_TABLE( SpellSvcList, SeqLangSvcEntry_Spell * ); class SpellCheckerDispatcher : public cppu::WeakImplHelper2 < ::com::sun::star::linguistic2::XSpellChecker, ::com::sun::star::linguistic2::XSpellChecker1 >, public LinguDispatcher { SpellSvcList aSvcList; LinguOptions aOpt; ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > xPropSet; ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XSearchableDictionaryList > xDicList; LngSvcMgr &rMgr; linguistic::IPRSpellCache *pExtCache; // SpellCache for external SpellCheckers // (usually those not called via XSpellChecker1) // One for all of them. // disallow copy-constructor and assignment-operator for now SpellCheckerDispatcher(const SpellCheckerDispatcher &); SpellCheckerDispatcher & operator = (const SpellCheckerDispatcher &); inline linguistic::IPRSpellCache & GetExtCache() const; inline ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > GetPropSet(); inline ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XSearchableDictionaryList > GetDicList(); void ClearSvcList(); BOOL isValid_Impl(const ::rtl::OUString& aWord, INT16 nLanguage, const ::com::sun::star::beans::PropertyValues& aProperties, BOOL bCheckDics) throw( ::com::sun::star::uno::RuntimeException, ::com::sun::star::lang::IllegalArgumentException ); ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XSpellAlternatives > spell_Impl(const ::rtl::OUString& aWord, INT16 nLanguage, const ::com::sun::star::beans::PropertyValues& aProperties, BOOL bCheckDics) throw( ::com::sun::star::uno::RuntimeException, ::com::sun::star::lang::IllegalArgumentException ); BOOL isValidInAny(const ::rtl::OUString& aWord, const ::com::sun::star::uno::Sequence< INT16 >& aLanguages, const ::com::sun::star::beans::PropertyValues& aProperties) throw( ::com::sun::star::uno::RuntimeException, ::com::sun::star::lang::IllegalArgumentException ); com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XSpellAlternatives > spellInAny(const ::rtl::OUString& aWord, const ::com::sun::star::uno::Sequence< INT16 >& aLanguages, const ::com::sun::star::beans::PropertyValues& aProperties, INT16 nPreferredResultLang) throw( ::com::sun::star::uno::RuntimeException, ::com::sun::star::lang::IllegalArgumentException ); public: SpellCheckerDispatcher( LngSvcMgr &rLngSvcMgr ); virtual ~SpellCheckerDispatcher(); // XSupportedLocales (for XSpellChecker) virtual ::com::sun::star::uno::Sequence< ::com::sun::star::lang::Locale > SAL_CALL getLocales() throw(::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL hasLocale( const ::com::sun::star::lang::Locale& aLocale ) throw(::com::sun::star::uno::RuntimeException); // XSpellChecker virtual sal_Bool SAL_CALL isValid( const ::rtl::OUString& aWord, const ::com::sun::star::lang::Locale& aLocale, const ::com::sun::star::beans::PropertyValues& aProperties ) throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XSpellAlternatives > SAL_CALL spell( const ::rtl::OUString& aWord, const ::com::sun::star::lang::Locale& aLocale, const ::com::sun::star::beans::PropertyValues& aProperties ) throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); // XSupportedLanguages (for XSpellChecker1) virtual ::com::sun::star::uno::Sequence< sal_Int16 > SAL_CALL getLanguages() throw(::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL hasLanguage( sal_Int16 nLanguage ) throw(::com::sun::star::uno::RuntimeException); // XSpellChecker1 (same as XSpellChecker but sal_Int16 for language) virtual sal_Bool SAL_CALL isValid( const ::rtl::OUString& aWord, sal_Int16 nLanguage, const ::com::sun::star::beans::PropertyValues& aProperties ) throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XSpellAlternatives > SAL_CALL spell( const ::rtl::OUString& aWord, sal_Int16 nLanguage, const ::com::sun::star::beans::PropertyValues& aProperties ) throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); // LinguDispatcher virtual void SetServiceList( const ::com::sun::star::lang::Locale &rLocale, const ::com::sun::star::uno::Sequence< rtl::OUString > &rSvcImplNames ); virtual ::com::sun::star::uno::Sequence< rtl::OUString > GetServiceList( const ::com::sun::star::lang::Locale &rLocale ) const; virtual DspType GetDspType() const; }; inline linguistic::IPRSpellCache & SpellCheckerDispatcher::GetExtCache() const { return pExtCache ? *pExtCache : * new linguistic::IPRSpellCache( 997 ); } inline ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > SpellCheckerDispatcher::GetPropSet() { return xPropSet.is() ? xPropSet : xPropSet = linguistic::GetLinguProperties(); } inline ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XSearchableDictionaryList > SpellCheckerDispatcher::GetDicList() { return xDicList.is() ? xDicList : xDicList = linguistic::GetSearchableDictionaryList(); } /////////////////////////////////////////////////////////////////////////// #endif <commit_msg>#87772# static modifier removed from friend declaration<commit_after>/************************************************************************* * * $RCSfile: spelldsp.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: tl $ $Date: 2001-06-05 13:54:51 $ * * 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 _LINGUISTIC_SPELLDSP_HXX_ #define _LINGUISTIC_SPELLDSP_HXX_ #include "lngopt.hxx" #include "misc.hxx" #include "iprcache.hxx" #include <uno/lbnames.h> // CPPU_CURRENT_LANGUAGE_BINDING_NAME macro, which specify the environment type #include <cppuhelper/implbase1.hxx> // helper for implementations #include <cppuhelper/implbase2.hxx> // helper for implementations #include <cppuhelper/implbase7.hxx> // helper for implementations #ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_ #include <com/sun/star/lang/XComponent.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_ #include <com/sun/star/lang/XInitialization.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEDISPLAYNAME_HPP_ #include <com/sun/star/lang/XServiceDisplayName.hpp> #endif #include <com/sun/star/beans/XPropertySet.hpp> #include <com/sun/star/beans/PropertyValues.hpp> #include <com/sun/star/lang/XServiceInfo.hpp> #include <com/sun/star/linguistic2/XSpellChecker.hpp> #include <com/sun/star/linguistic2/XSpellChecker1.hpp> #include <com/sun/star/linguistic2/XSearchableDictionaryList.hpp> #include <com/sun/star/linguistic2/XLinguServiceEventBroadcaster.hpp> #ifndef _TOOLS_TABLE_HXX #include <tools/table.hxx> #endif class LngSvcMgr; /////////////////////////////////////////////////////////////////////////// class SeqLangSvcEntry_Spell { friend class SpellCheckerDispatcher; friend BOOL SvcListHasLanguage( const SeqLangSvcEntry_Spell &rEntry, INT16 nLanguage ); ::com::sun::star::uno::Sequence< ::rtl::OUString > aSvcImplNames; ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XSpellChecker > > aSvcRefs; ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XSpellChecker1 > > aSvc1Refs; // INT16 nLang; //used as key in the table SvcFlags aFlags; public: SeqLangSvcEntry_Spell() {} SeqLangSvcEntry_Spell( const ::com::sun::star::uno::Sequence< ::rtl::OUString > &rSvcImplNames ); ~SeqLangSvcEntry_Spell(); BOOL IsAlreadyWarned() const { return aFlags.bAlreadyWarned != 0; } void SetAlreadyWarned(BOOL bVal) { aFlags.bAlreadyWarned = 0 != bVal; } BOOL IsDoWarnAgain() const { return aFlags.bDoWarnAgain != 0; } void SetDoWarnAgain(BOOL bVal) { aFlags.bDoWarnAgain = 0 != bVal; } }; DECLARE_TABLE( SpellSvcList, SeqLangSvcEntry_Spell * ); class SpellCheckerDispatcher : public cppu::WeakImplHelper2 < ::com::sun::star::linguistic2::XSpellChecker, ::com::sun::star::linguistic2::XSpellChecker1 >, public LinguDispatcher { SpellSvcList aSvcList; LinguOptions aOpt; ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > xPropSet; ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XSearchableDictionaryList > xDicList; LngSvcMgr &rMgr; linguistic::IPRSpellCache *pExtCache; // SpellCache for external SpellCheckers // (usually those not called via XSpellChecker1) // One for all of them. // disallow copy-constructor and assignment-operator for now SpellCheckerDispatcher(const SpellCheckerDispatcher &); SpellCheckerDispatcher & operator = (const SpellCheckerDispatcher &); inline linguistic::IPRSpellCache & GetExtCache() const; inline ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > GetPropSet(); inline ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XSearchableDictionaryList > GetDicList(); void ClearSvcList(); BOOL isValid_Impl(const ::rtl::OUString& aWord, INT16 nLanguage, const ::com::sun::star::beans::PropertyValues& aProperties, BOOL bCheckDics) throw( ::com::sun::star::uno::RuntimeException, ::com::sun::star::lang::IllegalArgumentException ); ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XSpellAlternatives > spell_Impl(const ::rtl::OUString& aWord, INT16 nLanguage, const ::com::sun::star::beans::PropertyValues& aProperties, BOOL bCheckDics) throw( ::com::sun::star::uno::RuntimeException, ::com::sun::star::lang::IllegalArgumentException ); BOOL isValidInAny(const ::rtl::OUString& aWord, const ::com::sun::star::uno::Sequence< INT16 >& aLanguages, const ::com::sun::star::beans::PropertyValues& aProperties) throw( ::com::sun::star::uno::RuntimeException, ::com::sun::star::lang::IllegalArgumentException ); com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XSpellAlternatives > spellInAny(const ::rtl::OUString& aWord, const ::com::sun::star::uno::Sequence< INT16 >& aLanguages, const ::com::sun::star::beans::PropertyValues& aProperties, INT16 nPreferredResultLang) throw( ::com::sun::star::uno::RuntimeException, ::com::sun::star::lang::IllegalArgumentException ); public: SpellCheckerDispatcher( LngSvcMgr &rLngSvcMgr ); virtual ~SpellCheckerDispatcher(); // XSupportedLocales (for XSpellChecker) virtual ::com::sun::star::uno::Sequence< ::com::sun::star::lang::Locale > SAL_CALL getLocales() throw(::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL hasLocale( const ::com::sun::star::lang::Locale& aLocale ) throw(::com::sun::star::uno::RuntimeException); // XSpellChecker virtual sal_Bool SAL_CALL isValid( const ::rtl::OUString& aWord, const ::com::sun::star::lang::Locale& aLocale, const ::com::sun::star::beans::PropertyValues& aProperties ) throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XSpellAlternatives > SAL_CALL spell( const ::rtl::OUString& aWord, const ::com::sun::star::lang::Locale& aLocale, const ::com::sun::star::beans::PropertyValues& aProperties ) throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); // XSupportedLanguages (for XSpellChecker1) virtual ::com::sun::star::uno::Sequence< sal_Int16 > SAL_CALL getLanguages() throw(::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL hasLanguage( sal_Int16 nLanguage ) throw(::com::sun::star::uno::RuntimeException); // XSpellChecker1 (same as XSpellChecker but sal_Int16 for language) virtual sal_Bool SAL_CALL isValid( const ::rtl::OUString& aWord, sal_Int16 nLanguage, const ::com::sun::star::beans::PropertyValues& aProperties ) throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XSpellAlternatives > SAL_CALL spell( const ::rtl::OUString& aWord, sal_Int16 nLanguage, const ::com::sun::star::beans::PropertyValues& aProperties ) throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); // LinguDispatcher virtual void SetServiceList( const ::com::sun::star::lang::Locale &rLocale, const ::com::sun::star::uno::Sequence< rtl::OUString > &rSvcImplNames ); virtual ::com::sun::star::uno::Sequence< rtl::OUString > GetServiceList( const ::com::sun::star::lang::Locale &rLocale ) const; virtual DspType GetDspType() const; }; inline linguistic::IPRSpellCache & SpellCheckerDispatcher::GetExtCache() const { return pExtCache ? *pExtCache : * new linguistic::IPRSpellCache( 997 ); } inline ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > SpellCheckerDispatcher::GetPropSet() { return xPropSet.is() ? xPropSet : xPropSet = linguistic::GetLinguProperties(); } inline ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XSearchableDictionaryList > SpellCheckerDispatcher::GetDicList() { return xDicList.is() ? xDicList : xDicList = linguistic::GetSearchableDictionaryList(); } /////////////////////////////////////////////////////////////////////////// #endif <|endoftext|>
<commit_before>void geom_cms_playback() { TRecorder r("http://mtadel.home.cern.ch/mtadel/geom_cms_recording.root"); } <commit_msg>Use new instead of normal constructor for TRecorder.<commit_after>void geom_cms_playback() { TRecorder* r = new TRecorder("http://mtadel.home.cern.ch/mtadel/geom_cms_recording.root"); } <|endoftext|>
<commit_before>/* parse_bam.cc -- Example BAM parser Copyright (c) 2015, The Griffith Lab Author: Avinash Ramu <aramu@genome.wustl.edu> 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 <iostream> #include "hts.h" #include "sam.h" using namespace std; int usage() { cerr << "./parse_bam example.bam"; return 0; } int main(int argc, char* argv[]) { if(argc < 2) { return usage(); } string bam = string(argv[1]); string region_ = ""; if(argc > 2) { region_ = string(argv[2]); } if(!bam.empty()) { //open BAM for reading samFile *in = sam_open(bam.c_str(), "r"); if(in == NULL) { throw runtime_error("Unable to open BAM/SAM file."); } //Load the index hts_idx_t *idx = sam_index_load(in, bam.c_str()); if(idx == NULL) { throw runtime_error("Unable to open BAM/SAM index." " Make sure alignments are indexed"); } //Get the header bam_hdr_t *header = sam_hdr_read(in); //Initialize iterator hts_itr_t *iter = NULL; //Move the iterator to the region we are interested in iter = sam_itr_querys(idx, header, region_.c_str()); if(header == NULL || iter == NULL) { sam_close(in); throw runtime_error("Unable to iterate to region within BAM."); } //Initiate the alignment record bam1_t *aln = bam_init1(); while(sam_itr_next(in, iter, aln) >= 0) { cout << endl << aln->core.tid; cout << endl << aln->core.pos; } hts_itr_destroy(iter); hts_idx_destroy(idx); bam_destroy1(aln); bam_hdr_destroy(header); sam_close(in); } return 0; } <commit_msg>Copyright stuff<commit_after>/* parse_bam.cc -- Example BAM parser using the htslib API Copyright (c) 2015, Washington University Author: Avinash Ramu <avinash3003@yahoo.co.in> 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 <iostream> #include "hts.h" #include "sam.h" using namespace std; int usage() { cerr << "./parse_bam example.bam"; return 0; } int main(int argc, char* argv[]) { if(argc < 2) { return usage(); } string bam = string(argv[1]); string region_ = ""; if(argc > 2) { region_ = string(argv[2]); } if(!bam.empty()) { //open BAM for reading samFile *in = sam_open(bam.c_str(), "r"); if(in == NULL) { throw runtime_error("Unable to open BAM/SAM file."); } //Load the index hts_idx_t *idx = sam_index_load(in, bam.c_str()); if(idx == NULL) { throw runtime_error("Unable to open BAM/SAM index." " Make sure alignments are indexed"); } //Get the header bam_hdr_t *header = sam_hdr_read(in); //Initialize iterator hts_itr_t *iter = NULL; //Move the iterator to the region we are interested in iter = sam_itr_querys(idx, header, region_.c_str()); if(header == NULL || iter == NULL) { sam_close(in); throw runtime_error("Unable to iterate to region within BAM."); } //Initiate the alignment record bam1_t *aln = bam_init1(); while(sam_itr_next(in, iter, aln) >= 0) { cout << endl << aln->core.tid; cout << endl << aln->core.pos; } hts_itr_destroy(iter); hts_idx_destroy(idx); bam_destroy1(aln); bam_hdr_destroy(header); sam_close(in); } return 0; } <|endoftext|>
<commit_before>#include <iostream> #include <stdint.h> #include <map> #include <vector> #include <string> #include "api/BamReader.h" #include "utils/bamtools_pileup_engine.h" #include "utils/bamtools_fasta.h" #include "model.h" using namespace std; using namespace BamTools; typedef vector< string > SampleNames; typedef map < string, int> ChrMap; string get_sample(string& tag){ string res; for(size_t i = 0; tag[i] != '_'; i++) { res.push_back(tag[i]); } return(res); } int find_sample_index(string s, SampleNames sv){ for (size_t i=0; i < sv.size(); i++){ if(s.compare(sv[i])==0){ return i; } } cerr << "didn't find name " << s << endl; return(13); //TODO refactor this to update sample in place } //int get_id_by_name(string chr, const Fasta& refseq){ // int result = find_if(begin(refseq.FastaPrivate.Index), // end(refseq.FastaPrivate.Index), // [&](const FastaIndexData &fid) {fid.Name == chr}); // return result; //} uint16_t base_index(char b){ switch(b){//TODO best 'null/npos' result for a short int? case 'A': case 'a': return 0; case 'T': case 't': return 3; case 'C': case 'c': return 1; case 'G': case 'g': return 2; case '-': case 'N': return 4; default: cerr << "Don't know what to make of base" << b <<endl; return 4; }; } class VariantVisitor : public PileupVisitor{ public: VariantVisitor(const RefVector& bam_references, const Fasta fasta_references, SampleNames samples, const ModelParams& p, BamAlignment& ali, int q =13, double prob_cutoff=0.1): PileupVisitor(), m_idx_ref(fasta_references), m_bam_ref(bam_references), m_samples(samples), m_q(q), m_params(p), m_ali(ali) { nsamp = m_samples.size(); } ~VariantVisitor(void) { } public: void Visit(const PileupPosition& pileupData) { string chr = m_bam_ref[pileupData.RefId].RefName; uint64_t pos = pileupData.Position; // int chr_idx = get_id_by_name(pileupData.RefId, m_idx_ref); m_idx_ref.GetBase(pileupData.RefId, pos, current_base); ReadDataVector bcalls (nsamp, ReadData{{ 0,0,0,0 }}); //fill constructor string tag_id; for(auto it = begin(pileupData.PileupAlignments); it != end(pileupData.PileupAlignments); ++it){ int const *pos = &it->PositionInAlignment; if (it->Alignment.Qualities[*pos] - 33 > m_q){ it->Alignment.GetTag("RG", tag_id); int sindex = find_sample_index(get_sample(tag_id), m_samples); size_t bindex = base_index(it->Alignment.AlignedBases[*pos]); if (bindex < 4){ bcalls[sindex].reads[bindex] += 1; } } } ModelInput d = {"", 1, base_index(current_base), bcalls}; double prob = TetMAProbability(m_params,d); if(prob >= 0.0){//NOTE: Probablity cut off is hard-coded atm cout << chr << '\t' << pos << '\t' << current_base << '\t' << prob << '\t' << TetMAProbOneMutation(m_params,d) << endl; } } private: Fasta m_idx_ref; RefVector m_bam_ref; SampleNames m_samples; int m_q; int nsamp; ModelParams m_params; BamAlignment& m_ali; char current_base; uint64_t chr_index; }; int main(){ BamReader myBam; myBam.Open("test/test.bam"); RefVector references = myBam.GetReferenceData(); cerr << "buliding fasta index..." << endl; Fasta reference_genome; reference_genome.Open("test/test.fasta"); reference_genome.CreateIndex("test/test.fai"); // ifstream idx ("test/test.fai"); //bamtools api makes the actual index private //only public acess to a sequence is via it ID (index) //so need to make a map of them // string idx_line; // ChrMap idx_map; // // while(getline(idx, idx_line)){ // size_t i = 0; // string name; // int counter = 0; // for(; L[i] != '\t', i++){ // name.push_back(L[i]) // } // idx_map[name] = counter; // counter += 1; // } // reference_genome.Close(); reference_genome.Open("test/test.fasta", "test/test.fai"); SampleNames all_samples {"M0", "M19", "M20", "M28","M25", "M29", "M40", "M44","M47", "M50","M51", "M531"}; ModelParams p = { 0.001, {0.25, 0.25, 0.25, 0.25}, 1.0e-8, 0.01, 0.001, 0.001, }; BamAlignment ali; PileupEngine pileup; VariantVisitor *v = new VariantVisitor(references, reference_genome, all_samples,p, ali); pileup.AddVisitor(v); cerr << "calling variants" << endl; while( myBam.GetNextAlignment(ali)){ pileup.AddAlignment(ali); }; pileup.Flush(); return 0; } <commit_msg>pass references by ref<commit_after>#include <iostream> #include <stdint.h> #include <map> #include <vector> #include <string> #include "api/BamReader.h" #include "utils/bamtools_pileup_engine.h" #include "utils/bamtools_fasta.h" #include "model.h" using namespace std; using namespace BamTools; typedef vector< string > SampleNames; typedef map < string, int> ChrMap; string get_sample(string& tag){ string res; for(size_t i = 0; tag[i] != '_'; i++) { res.push_back(tag[i]); } return(res); } int find_sample_index(string s, SampleNames sv){ for (size_t i=0; i < sv.size(); i++){ if(s.compare(sv[i])==0){ return i; } } cerr << "didn't find name " << s << endl; return(13); //TODO refactor this to update sample in place } //int get_id_by_name(string chr, const Fasta& refseq){ // int result = find_if(begin(refseq.FastaPrivate.Index), // end(refseq.FastaPrivate.Index), // [&](const FastaIndexData &fid) {fid.Name == chr}); // return result; //} uint16_t base_index(char b){ switch(b){//TODO best 'null/npos' result for a short int? case 'A': case 'a': return 0; case 'T': case 't': return 3; case 'C': case 'c': return 1; case 'G': case 'g': return 2; case '-': case 'N': return 4; default: cerr << "Don't know what to make of base" << b <<endl; return 4; }; } class VariantVisitor : public PileupVisitor{ public: VariantVisitor(const RefVector& bam_references, const Fasta& fasta_references, SampleNames samples, const ModelParams& p, BamAlignment& ali, int q =13, double prob_cutoff=0.1): PileupVisitor(), m_idx_ref(fasta_references), m_bam_ref(bam_references), m_samples(samples), m_q(q), m_params(p), m_ali(ali) { nsamp = m_samples.size(); } ~VariantVisitor(void) { } public: void Visit(const PileupPosition& pileupData) { string chr = m_bam_ref[pileupData.RefId].RefName; uint64_t pos = pileupData.Position; // int chr_idx = get_id_by_name(pileupData.RefId, m_idx_ref); m_idx_ref.GetBase(pileupData.RefId, pos, current_base); ReadDataVector bcalls (nsamp, ReadData{{ 0,0,0,0 }}); //fill constructor string tag_id; for(auto it = begin(pileupData.PileupAlignments); it != end(pileupData.PileupAlignments); ++it){ int const *pos = &it->PositionInAlignment; if (it->Alignment.Qualities[*pos] - 33 > m_q){ it->Alignment.GetTag("RG", tag_id); int sindex = find_sample_index(get_sample(tag_id), m_samples); size_t bindex = base_index(it->Alignment.AlignedBases[*pos]); if (bindex < 4){ bcalls[sindex].reads[bindex] += 1; } } } ModelInput d = {"", 1, base_index(current_base), bcalls}; double prob = TetMAProbability(m_params,d); if(prob >= 0.0){//NOTE: Probablity cut off is hard-coded atm cout << chr << '\t' << pos << '\t' << current_base << '\t' << prob << '\t' << TetMAProbOneMutation(m_params,d) << endl; } } private: Fasta m_idx_ref; RefVector m_bam_ref; SampleNames m_samples; int m_q; int nsamp; ModelParams m_params; BamAlignment& m_ali; char current_base; uint64_t chr_index; }; int main(){ BamReader myBam; myBam.Open("test/test.bam"); RefVector references = myBam.GetReferenceData(); cerr << "buliding fasta index..." << endl; Fasta reference_genome; reference_genome.Open("test/test.fasta"); reference_genome.CreateIndex("test/test.fai"); // ifstream idx ("test/test.fai"); //bamtools api makes the actual index private //only public acess to a sequence is via it ID (index) //so need to make a map of them // string idx_line; // ChrMap idx_map; // // while(getline(idx, idx_line)){ // size_t i = 0; // string name; // int counter = 0; // for(; L[i] != '\t', i++){ // name.push_back(L[i]) // } // idx_map[name] = counter; // counter += 1; // } // reference_genome.Close(); reference_genome.Open("test/test.fasta", "test/test.fai"); SampleNames all_samples {"M0", "M19", "M20", "M28","M25", "M29", "M40", "M44","M47", "M50","M51", "M531"}; ModelParams p = { 0.001, {0.25, 0.25, 0.25, 0.25}, 1.0e-8, 0.01, 0.001, 0.001, }; BamAlignment ali; PileupEngine pileup; VariantVisitor *v = new VariantVisitor(references, reference_genome, all_samples,p, ali); pileup.AddVisitor(v); cerr << "calling variants" << endl; while( myBam.GetNextAlignment(ali)){ pileup.AddAlignment(ali); }; pileup.Flush(); return 0; } <|endoftext|>
<commit_before>#include <boost/test/unit_test.hpp> #include <index-manager/IndexManager.h> #include <search-manager/AllDocumentIterator.h> using namespace sf1r; using namespace izenelib::ir::indexmanager; BOOST_AUTO_TEST_SUITE( AllDocumentIterator_Suite ) static unsigned maxDoc = 100; BOOST_AUTO_TEST_CASE(alldociter_test) { { boost::shared_ptr<IndexManager::FilterBitmapT> pFilterIdSet(new IndexManager::FilterBitmapT); pFilterIdSet->set(1); pFilterIdSet->set(2); pFilterIdSet->set(3); pFilterIdSet->set(4); pFilterIdSet->set(5); pFilterIdSet->set(6); pFilterIdSet->set(10); pFilterIdSet->set(20); pFilterIdSet->set(30); pFilterIdSet->set(33); pFilterIdSet->set(40); pFilterIdSet->set(50); pFilterIdSet->set(100); IndexManager::FilterTermDocFreqsT* pFilterTermDocFreqs = new IndexManager::FilterTermDocFreqsT(pFilterIdSet); AllDocumentIterator* pIterator = new AllDocumentIterator(pFilterTermDocFreqs, maxDoc); //pIterator->next(); unsigned doc = pIterator->skipTo(2); BOOST_CHECK_EQUAL(doc, 7U); doc = pIterator->skipTo(3); BOOST_CHECK_EQUAL(doc, 7U); doc = pIterator->skipTo(4); BOOST_CHECK_EQUAL(doc, 7U); doc = pIterator->skipTo(5); BOOST_CHECK_EQUAL(doc, 7); doc = pIterator->skipTo(6); BOOST_CHECK_EQUAL(doc, 7U); doc = pIterator->skipTo(8); BOOST_CHECK_EQUAL(doc, 9U); doc = pIterator->skipTo(9); BOOST_CHECK_EQUAL(doc, 11U); doc = pIterator->skipTo(10); BOOST_CHECK_EQUAL(doc, 11U); doc = pIterator->skipTo(20); BOOST_CHECK_EQUAL(doc, 21U); doc = pIterator->skipTo(30); BOOST_CHECK_EQUAL(doc, 31U); doc = pIterator->skipTo(40); BOOST_CHECK_EQUAL(doc, 41U); doc = pIterator->skipTo(50); BOOST_CHECK_EQUAL(doc, 51U); doc = pIterator->skipTo(60); BOOST_CHECK_EQUAL(doc, 61U); doc = pIterator->skipTo(98); BOOST_CHECK_EQUAL(doc, 99U); doc = pIterator->skipTo(99); BOOST_CHECK_EQUAL(doc, -1U); doc = pIterator->skipTo(100); BOOST_CHECK_EQUAL(doc, -1U); } { boost::shared_ptr<IndexManager::FilterBitmapT> pFilterIdSet(new IndexManager::FilterBitmapT); pFilterIdSet->set(1); pFilterIdSet->set(2); pFilterIdSet->set(3); pFilterIdSet->set(4); pFilterIdSet->set(5); pFilterIdSet->set(6); pFilterIdSet->set(10); pFilterIdSet->set(20); pFilterIdSet->set(30); pFilterIdSet->set(33); pFilterIdSet->set(40); pFilterIdSet->set(50); pFilterIdSet->set(100); IndexManager::FilterTermDocFreqsT* pFilterTermDocFreqs = new IndexManager::FilterTermDocFreqsT(pFilterIdSet); AllDocumentIterator* pIterator = new AllDocumentIterator(pFilterTermDocFreqs, maxDoc); while(pIterator->next()) { std::cout<<"doc "<<pIterator->doc()<<std::endl; } } } BOOST_AUTO_TEST_SUITE_END() <commit_msg>refactor t_AllDocumentIterator.cpp<commit_after>#include <boost/test/unit_test.hpp> #include <index-manager/IndexManager.h> #include <search-manager/AllDocumentIterator.h> #include <algorithm> // std::set_difference using namespace sf1r; namespace { static const sf1r::docid_t MAX_DOCID = 100; static const sf1r::docid_t DELETE_DOCIDS[] = { 1, 2, 3, 4, 5, 6, 10, 20, 30, 33, 40, 50, 100 }; static const std::size_t DELETE_DOCIDS_NUM = sizeof(DELETE_DOCIDS) / sizeof(DELETE_DOCIDS[0]); AllDocumentIterator* createAllDocumentIterator() { boost::shared_ptr<IndexManager::FilterBitmapT> pFilterIdSet( new IndexManager::FilterBitmapT); for (std::size_t i = 0; i < DELETE_DOCIDS_NUM; ++i) { pFilterIdSet->set(DELETE_DOCIDS[i]); } IndexManager::FilterTermDocFreqsT* pFilterTermDocFreqs = new IndexManager::FilterTermDocFreqsT(pFilterIdSet); return new AllDocumentIterator(pFilterTermDocFreqs, MAX_DOCID); } } BOOST_AUTO_TEST_SUITE(AllDocumentIterator_Suite) BOOST_AUTO_TEST_CASE(testSkipTo) { const sf1r::docid_t skipTestData[][2] = { {2, 7}, {3, 7}, {4, 7}, {5, 7}, {6, 7}, {8, 9}, {9, 11}, {10, 11}, {20, 21}, {30, 31}, {40, 41}, {50, 51}, {60, 61}, {98, 99}, {99, -1}, {100, -1} }; const int num = sizeof(skipTestData) / sizeof(skipTestData[0]); AllDocumentIterator* pIterator = createAllDocumentIterator(); for (int i = 0; i < num; ++i) { sf1r::docid_t target = skipTestData[i][0]; sf1r::docid_t gold = skipTestData[i][1]; BOOST_TEST_MESSAGE("target: " << target << ", gold: " << gold); BOOST_CHECK_EQUAL(pIterator->skipTo(target), gold); } delete pIterator; } BOOST_AUTO_TEST_CASE(testNext) { std::vector<sf1r::docid_t> allDocIds; for (sf1r::docid_t docId = 1; docId <= MAX_DOCID; ++docId) { allDocIds.push_back(docId); } std::vector<sf1r::docid_t> existDocIds(allDocIds.size() - DELETE_DOCIDS_NUM); std::set_difference(allDocIds.begin(), allDocIds.end(), DELETE_DOCIDS, DELETE_DOCIDS + DELETE_DOCIDS_NUM, existDocIds.begin()); AllDocumentIterator* pIterator = createAllDocumentIterator(); for (std::vector<sf1r::docid_t>::const_iterator it = existDocIds.begin(); it != existDocIds.end(); ++it) { BOOST_CHECK(pIterator->next()); BOOST_CHECK_EQUAL(pIterator->doc(), *it); BOOST_TEST_MESSAGE("next doc: " << pIterator->doc()); } delete pIterator; } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>#include <test/unit/math/test_ad.hpp> TEST(MathMixMatFun, quadFormSym) { auto f = [](const auto& x, const auto& y) { return stan::math::quad_form_sym(x, y); }; Eigen::MatrixXd a00; Eigen::MatrixXd a11(1, 1); a11 << 1; Eigen::MatrixXd b11(1, 1); b11 << -2; Eigen::MatrixXd a22(2, 2); a22 << 1, 2, 3, 4; Eigen::MatrixXd b22(2, 2); a22 << -3, -2, -10, 112; Eigen::MatrixXd a23(2, 3); a23 << 1, 2, 3, 4, 5, 6; Eigen::MatrixXd a42(4, 2); a42 << 100, 10, 0, 1, -3, -3, 5, 2; Eigen::MatrixXd a44(4, 4); a44 << 2, 3, 4, 5, 6, 10, 2, 2, 7, 2, 7, 1, 8, 2, 1, 112; Eigen::VectorXd v0(0); Eigen::VectorXd v1(1); v1 << 42; Eigen::VectorXd v2(2); v2 << -3, 13; Eigen::VectorXd v4(4); v4 << 100, 0, -3, 5; stan::test::expect_ad(f, a00, a00); stan::test::expect_ad(f, a11, b11); stan::test::expect_ad(f, a22, b22); stan::test::expect_ad(f, a44, a42); stan::test::expect_ad(f, a00, v0); stan::test::expect_ad(f, a11, v1); stan::test::expect_ad(f, a22, v2); stan::test::expect_ad(f, a44, v4); // asymmetric case should thorw Eigen::MatrixXd u(4, 4); u << 2, 3, 4, 5, 6, 10, 2, 2, 7, 2, 7, 1, 8, 2, 1, 112; Eigen::MatrixXd v(4, 2); v << 100, 10, 0, 1, -3, -3, 5, 2; stan::test::expect_ad(f, u, v); } <commit_msg>Fix quad_form_sym mix tests<commit_after>#include <test/unit/math/test_ad.hpp> #include <test/unit/math/ad_tolerances.hpp> TEST(MathMixMatFun, quadFormSym) { auto f = [](const auto& x, const auto& y) { // symmetrize the input matrix auto x_sym = ((x + x.transpose()) * 0.5).eval(); return stan::math::quad_form_sym(x_sym, y); }; Eigen::MatrixXd a00; Eigen::MatrixXd a11(1, 1); a11 << 1; Eigen::MatrixXd b11(1, 1); b11 << -2; Eigen::MatrixXd a22(2, 2); a22 << 1, 2, 3, 4; Eigen::MatrixXd b22(2, 2); b22 << -3, -2, -10, 112; Eigen::MatrixXd b23(2, 3); b23 << 1, 2, 3, 4, 5, 6; Eigen::MatrixXd b42(4, 2); b42 << 100, 10, 0, 1, -3, -3, 5, 2; Eigen::MatrixXd a44(4, 4); a44 << 2, 3, 4, 5, 6, 10, 2, 2, 7, 2, 7, 1, 8, 2, 1, 112; Eigen::VectorXd v0(0); Eigen::VectorXd v1(1); v1 << 42; Eigen::VectorXd v2(2); v2 << -3, 13; Eigen::VectorXd v4(4); v4 << 100, 0, -3, 5; stan::test::ad_tolerances tols; tols.hessian_hessian_ = 2e-1; tols.hessian_fvar_hessian_ = 2e-1; stan::test::expect_ad(f, a00, a00); stan::test::expect_ad(f, a11, b11); stan::test::expect_ad(tols, f, a22, b22); stan::test::expect_ad(f, a22, b23); stan::test::expect_ad(tols, f, a44, b42); stan::test::expect_ad(f, a00, v0); stan::test::expect_ad(f, a11, v1); stan::test::expect_ad(f, a22, v2); stan::test::expect_ad(tols, f, a44, v4); // asymmetric case should throw auto g = [](const auto& x, const auto& y) { return stan::math::quad_form_sym(x, y); }; Eigen::MatrixXd u(4, 4); u << 2, 3, 4, 5, 6, 10, 2, 2, 7, 2, 7, 1, 8, 2, 1, 112; Eigen::MatrixXd v(4, 2); v << 100, 10, 0, 1, -3, -3, 5, 2; stan::test::expect_ad(g, u, v); } <|endoftext|>
<commit_before>//----------------------------------------------------------------------------// // █ █ // // ████████ // // ██ ██ // // ███ █ █ ███ CCBNodeLoader.cpp // // █ █ █ █ MonsterFramework // // ████████████ // // █ █ Copyright (c) 2015 AmazingCow // // █ █ █ █ www.AmazingCow.com // // █ █ █ █ // // █ █ N2OMatt - n2omatt@amazingcow.com // // ████████████ www.amazingcow.com/n2omatt // // // // // // This software is licensed as BSD-3 // // CHECK THE COPYING FILE TO MORE DETAILS // // // // Permission is granted to anyone to use this software for any purpose, // // including commercial applications, and to alter it and redistribute it // // freely, subject to the following restrictions: // // // // 0. You **CANNOT** change the type of the license. // // 1. The origin of this software must not be misrepresented; // // you must not claim that you wrote the original software. // // 2. If you use this software in a product, an acknowledgment in the // // product IS HIGHLY APPRECIATED, both in source and binary forms. // // (See opensource.AmazingCow.com/acknowledgment.html for details). // // If you will not acknowledge, just send us a email. We'll be // // *VERY* happy to see our work being used by other people. :) // // The email is: acknowledgment.opensource@AmazingCow.com // // 3. Altered source versions must be plainly marked as such, // // and must notbe misrepresented as being the original software. // // 4. This notice may not be removed or altered from any source // // distribution. // // 5. Most important, you must have fun. ;) // // // // Visit opensource.amazingcow.com for more open-source projects. // // // // Enjoy :) // //----------------------------------------------------------------------------// //Header #include "CCBNodeLoader.h" //std #include <string> //MonsterFramework #include "MonsterFramework/include/Graphics/ILoadResolver.h" #include "MonsterFramework/src/Graphics/private/CCBNodeLoader_Decoders.h" #include "MonsterFramework/src/Graphics/private/CCBNodeLoader_PropertySetters.h" //Usings USING_NS_STD_CC_CD_MF // MACROS // #define _SET_PROPERTY_FUNCTION(_target_name_, _name_, _obj_, _value_) \ if(_name_ == #_target_name_) { \ _set_ ## _target_name_(_obj_, _value_); \ } // Public Methods // void CCBNodeLoader::load(const cc::ValueMap &map, cc::Node *parent, mf::ILoadResolver *pResolver) { //Retrieve the values auto baseClass = map.at("baseClass" ).asString(); auto customClass = map.at("customClass" ).asString(); auto children = map.at("children" ).asValueVector(); auto memberVarAssignmentName = map.at("memberVarAssignmentName").asString(); auto properties = map.at("properties" ).asValueVector(); cc::ValueVector customProperties; auto customPropertiesIt = map.find("customProperties"); if(customPropertiesIt != end(map)) customProperties = map.at("customProperties").asValueVector(); //LOG // MF_LOG("Loading a Node with BaseClass:(%s) with CustomClass:(%s) and MemberVarAssignment:(%s)", // baseClass.c_str(), customClass.c_str(), memberVarAssignmentName.c_str()); //Create the node and assign its properties. cc::Node *node = nullptr; if(baseClass == "CCBFile") { auto ccbFilename = findCCBFilename(properties); node = pResolver->resolveCustomClass(ccbFilename); } else if(customClass.empty()) { node = resolveDefaultClasses(baseClass); } else { node = resolveCustomClasses(customClass, pResolver, customProperties); } MF_ASSERT(node, "CCBNodeLoader - Node is null (%s)", baseClass.c_str()); parent->addChild(node); assignProperties(node, properties, pResolver); //Resolve Custom Class. //Resolve Member Var Assignment pResolver->resolveVarAssignment(memberVarAssignmentName, node); //Create the Node's children. for(const auto &childItem : children) { CCBNodeLoader nodeLoader; nodeLoader.load(childItem.asValueMap(), node, pResolver); } } void CCBNodeLoader::loadNodeGraph(const cc::ValueMap &map, cc::Node *parent, mf::ILoadResolver *pResolver) { auto children = map.at("children" ).asValueVector(); auto properties = map.at("properties").asValueVector(); assignProperties(parent, properties, pResolver); //Create the Node's children. for(const auto &childItem : children) { CCBNodeLoader nodeLoader; nodeLoader.load(childItem.asValueMap(), parent, pResolver); } } // Private Methods // std::string CCBNodeLoader::findCCBFilename(const cc::ValueVector &properties) { //Search for a property named ccbFile and return its value //if found, otherwise just return an empty string. for(auto it = begin(properties); it != end(properties); ++it) { const auto &item = it->asValueMap(); if(item.at("name").asString() == "ccbFile") return item.at("value").asString(); } return ""; } cc::Node* CCBNodeLoader::assignProperties(cc::Node *obj, const cc::ValueVector &properties, ILoadResolver *pResolver) { //Iterate for all properties. for(auto it = begin(properties); it != end(properties); ++it) { //Get the item. const auto &item = it->asValueMap(); //Get the name/value pair. const auto &name = item.at("name" ).asString(); const auto &value = item.at("value"); // MF_LOG("CCBNodeLoader - %s", name.c_str()); //Check if the name of property matches and set the property. _SET_PROPERTY_FUNCTION(anchorPoint, name, obj, value); _SET_PROPERTY_FUNCTION(scale, name, obj, value); _SET_PROPERTY_FUNCTION(ignoreAnchorPointForPosition, name, obj, value); _SET_PROPERTY_FUNCTION(isTouchEnabled, name, obj, value); _SET_PROPERTY_FUNCTION(isAccelerometerEnabled, name, obj, value); _SET_PROPERTY_FUNCTION(position, name, obj, value); _SET_PROPERTY_FUNCTION(displayFrame, name, obj, value); _SET_PROPERTY_FUNCTION(isEnabled, name, obj, value); _SET_PROPERTY_FUNCTION(normalSpriteFrame, name, obj, value); _SET_PROPERTY_FUNCTION(selectedSpriteFrame, name, obj, value); _SET_PROPERTY_FUNCTION(selectedSpriteFrame, name, obj, value); _SET_PROPERTY_FUNCTION(color, name, obj, value); _SET_PROPERTY_FUNCTION(contentSize, name, obj, value); _SET_PROPERTY_FUNCTION(rotation, name, obj, value); _SET_PROPERTY_FUNCTION(fontName, name, obj, value); _SET_PROPERTY_FUNCTION(fontSize, name, obj, value); _SET_PROPERTY_FUNCTION(string, name, obj, value); _SET_PROPERTY_FUNCTION(opacity, name, obj, value); //Block is special, because we need the ILoadResolver //to communicate with the object owner class. if(name == "block") _set_block(obj, value, pResolver); } return obj; } cc::Node* CCBNodeLoader::resolveDefaultClasses(const std::string &baseClass) { cc::Node *node; //Layer. if(baseClass == "CCLayer") node = cc::Layer::create(); //LayerColor //COWTODO:: This is very strange. With we don't set a color here at craetion //of the LayerColor, later the object will not set any color. So any color //set in CCB won't be applied. I don't know why this behaviour is occurring //but know works in this way. else if(baseClass == "CCLayerColor") node = cc::LayerColor::create(cc::Color4B::BLUE); //Sprite else if(baseClass == "CCSprite") node = cc::Sprite::create(); //Menu else if(baseClass == "CCMenu") node = cc::Menu::create(); //MenuItem else if(baseClass == "CCMenuItemImage") node = cc::MenuItemSprite::create(nullptr, nullptr); //LabelTTF else if(baseClass == "CCLabelTTF") node = cc::Label::create(); return node; } cc::Node* CCBNodeLoader::resolveCustomClasses(const std::string &customClass, mf::ILoadResolver *pResolver, const cc::ValueVector &customProperties) { // cc::Node *node = nullptr; // if(customClass == "MFSpriteBatch") // { // auto imageName = customProperties.at(0).asValueMap().at("value").asString(); // MF_LOG("%s", imageName.c_str()); // auto texture = cc::SpriteFrameCache::getInstance()->addSpriteFramesWithFile(imageName); // node = cc::SpriteBatchNode::createWithTexture(texture); // } // return node; return pResolver->resolveCustomClass(customClass); } #undef _SET_PROPERTY_FUNCTION <commit_msg>Initialize the pointer with nullptr<commit_after>//----------------------------------------------------------------------------// // █ █ // // ████████ // // ██ ██ // // ███ █ █ ███ CCBNodeLoader.cpp // // █ █ █ █ MonsterFramework // // ████████████ // // █ █ Copyright (c) 2015 AmazingCow // // █ █ █ █ www.AmazingCow.com // // █ █ █ █ // // █ █ N2OMatt - n2omatt@amazingcow.com // // ████████████ www.amazingcow.com/n2omatt // // // // // // This software is licensed as BSD-3 // // CHECK THE COPYING FILE TO MORE DETAILS // // // // Permission is granted to anyone to use this software for any purpose, // // including commercial applications, and to alter it and redistribute it // // freely, subject to the following restrictions: // // // // 0. You **CANNOT** change the type of the license. // // 1. The origin of this software must not be misrepresented; // // you must not claim that you wrote the original software. // // 2. If you use this software in a product, an acknowledgment in the // // product IS HIGHLY APPRECIATED, both in source and binary forms. // // (See opensource.AmazingCow.com/acknowledgment.html for details). // // If you will not acknowledge, just send us a email. We'll be // // *VERY* happy to see our work being used by other people. :) // // The email is: acknowledgment.opensource@AmazingCow.com // // 3. Altered source versions must be plainly marked as such, // // and must notbe misrepresented as being the original software. // // 4. This notice may not be removed or altered from any source // // distribution. // // 5. Most important, you must have fun. ;) // // // // Visit opensource.amazingcow.com for more open-source projects. // // // // Enjoy :) // //----------------------------------------------------------------------------// //Header #include "CCBNodeLoader.h" //std #include <string> //MonsterFramework #include "MonsterFramework/include/Graphics/ILoadResolver.h" #include "MonsterFramework/src/Graphics/private/CCBNodeLoader_Decoders.h" #include "MonsterFramework/src/Graphics/private/CCBNodeLoader_PropertySetters.h" //Usings USING_NS_STD_CC_CD_MF // MACROS // #define _SET_PROPERTY_FUNCTION(_target_name_, _name_, _obj_, _value_) \ if(_name_ == #_target_name_) { \ _set_ ## _target_name_(_obj_, _value_); \ } // Public Methods // void CCBNodeLoader::load(const cc::ValueMap &map, cc::Node *parent, mf::ILoadResolver *pResolver) { //Retrieve the values auto baseClass = map.at("baseClass" ).asString(); auto customClass = map.at("customClass" ).asString(); auto children = map.at("children" ).asValueVector(); auto memberVarAssignmentName = map.at("memberVarAssignmentName").asString(); auto properties = map.at("properties" ).asValueVector(); cc::ValueVector customProperties; auto customPropertiesIt = map.find("customProperties"); if(customPropertiesIt != end(map)) customProperties = map.at("customProperties").asValueVector(); //LOG // MF_LOG("Loading a Node with BaseClass:(%s) with CustomClass:(%s) and MemberVarAssignment:(%s)", // baseClass.c_str(), customClass.c_str(), memberVarAssignmentName.c_str()); //Create the node and assign its properties. cc::Node *node = nullptr; if(baseClass == "CCBFile") { auto ccbFilename = findCCBFilename(properties); node = pResolver->resolveCustomClass(ccbFilename); } else if(customClass.empty()) { node = resolveDefaultClasses(baseClass); } else { node = resolveCustomClasses(customClass, pResolver, customProperties); } MF_ASSERT(node, "CCBNodeLoader - Node is null (%s)", baseClass.c_str()); parent->addChild(node); assignProperties(node, properties, pResolver); //Resolve Custom Class. //Resolve Member Var Assignment pResolver->resolveVarAssignment(memberVarAssignmentName, node); //Create the Node's children. for(const auto &childItem : children) { CCBNodeLoader nodeLoader; nodeLoader.load(childItem.asValueMap(), node, pResolver); } } void CCBNodeLoader::loadNodeGraph(const cc::ValueMap &map, cc::Node *parent, mf::ILoadResolver *pResolver) { auto children = map.at("children" ).asValueVector(); auto properties = map.at("properties").asValueVector(); assignProperties(parent, properties, pResolver); //Create the Node's children. for(const auto &childItem : children) { CCBNodeLoader nodeLoader; nodeLoader.load(childItem.asValueMap(), parent, pResolver); } } // Private Methods // std::string CCBNodeLoader::findCCBFilename(const cc::ValueVector &properties) { //Search for a property named ccbFile and return its value //if found, otherwise just return an empty string. for(auto it = begin(properties); it != end(properties); ++it) { const auto &item = it->asValueMap(); if(item.at("name").asString() == "ccbFile") return item.at("value").asString(); } return ""; } cc::Node* CCBNodeLoader::assignProperties(cc::Node *obj, const cc::ValueVector &properties, ILoadResolver *pResolver) { //Iterate for all properties. for(auto it = begin(properties); it != end(properties); ++it) { //Get the item. const auto &item = it->asValueMap(); //Get the name/value pair. const auto &name = item.at("name" ).asString(); const auto &value = item.at("value"); // MF_LOG("CCBNodeLoader - %s", name.c_str()); //Check if the name of property matches and set the property. _SET_PROPERTY_FUNCTION(anchorPoint, name, obj, value); _SET_PROPERTY_FUNCTION(scale, name, obj, value); _SET_PROPERTY_FUNCTION(ignoreAnchorPointForPosition, name, obj, value); _SET_PROPERTY_FUNCTION(isTouchEnabled, name, obj, value); _SET_PROPERTY_FUNCTION(isAccelerometerEnabled, name, obj, value); _SET_PROPERTY_FUNCTION(position, name, obj, value); _SET_PROPERTY_FUNCTION(displayFrame, name, obj, value); _SET_PROPERTY_FUNCTION(isEnabled, name, obj, value); _SET_PROPERTY_FUNCTION(normalSpriteFrame, name, obj, value); _SET_PROPERTY_FUNCTION(selectedSpriteFrame, name, obj, value); _SET_PROPERTY_FUNCTION(selectedSpriteFrame, name, obj, value); _SET_PROPERTY_FUNCTION(color, name, obj, value); _SET_PROPERTY_FUNCTION(contentSize, name, obj, value); _SET_PROPERTY_FUNCTION(rotation, name, obj, value); _SET_PROPERTY_FUNCTION(fontName, name, obj, value); _SET_PROPERTY_FUNCTION(fontSize, name, obj, value); _SET_PROPERTY_FUNCTION(string, name, obj, value); _SET_PROPERTY_FUNCTION(opacity, name, obj, value); //Block is special, because we need the ILoadResolver //to communicate with the object owner class. if(name == "block") _set_block(obj, value, pResolver); } return obj; } cc::Node* CCBNodeLoader::resolveDefaultClasses(const std::string &baseClass) { cc::Node *node = nullptr; //Layer. if(baseClass == "CCLayer") node = cc::Layer::create(); //LayerColor //COWTODO: Bug? //This is very strange. With we don't set a color here at craetion //of the LayerColor, later the object will not set any color. So any color //set in CCB won't be applied. I don't know why this behaviour is occurring //but know works in this way. else if(baseClass == "CCLayerColor") node = cc::LayerColor::create(cc::Color4B::BLUE); //Sprite else if(baseClass == "CCSprite") node = cc::Sprite::create(); //Menu else if(baseClass == "CCMenu") node = cc::Menu::create(); //MenuItem else if(baseClass == "CCMenuItemImage") node = cc::MenuItemSprite::create(nullptr, nullptr); //LabelTTF else if(baseClass == "CCLabelTTF") node = cc::Label::create(); return node; } cc::Node* CCBNodeLoader::resolveCustomClasses(const std::string &customClass, mf::ILoadResolver *pResolver, const cc::ValueVector &customProperties) { // cc::Node *node = nullptr; // if(customClass == "MFSpriteBatch") // { // auto imageName = customProperties.at(0).asValueMap().at("value").asString(); // MF_LOG("%s", imageName.c_str()); // auto texture = cc::SpriteFrameCache::getInstance()->addSpriteFramesWithFile(imageName); // node = cc::SpriteBatchNode::createWithTexture(texture); // } // return node; return pResolver->resolveCustomClass(customClass); } #undef _SET_PROPERTY_FUNCTION <|endoftext|>
<commit_before>#include "evpp/inner_pre.h" #include "evpp/event_loop_thread_pool.h" #include "evpp/event_loop.h" namespace evpp { EventLoopThreadPool::EventLoopThreadPool(EventLoop* base_loop, uint32_t thread_number) : base_loop_(base_loop), started_(false), thread_num_(thread_number), next_(0) {} EventLoopThreadPool::~EventLoopThreadPool() { assert(thread_num_ == threads_.size()); for (uint32_t i = 0; i < thread_num_; i++) { assert(threads_[i]->IsStopped()); } threads_.clear(); } bool EventLoopThreadPool::Start(bool wait_until_thread_started) { assert(!started_); if (started_) { return true; } for (uint32_t i = 0; i < thread_num_; ++i) { std::stringstream ss; ss << "EventLoopThreadPool-thread-" << i << "th"; EventLoopThreadPtr t(new EventLoopThread()); if (!t->Start(wait_until_thread_started)) { //FIXME error process LOG_ERROR << "start thread failed!"; return false; } t->SetName(ss.str()); threads_.push_back(t); } started_ = true; return true; } void EventLoopThreadPool::Stop(bool wait_thread_exit) { for (uint32_t i = 0; i < thread_num_; ++i) { EventLoopThreadPtr& t = threads_[i]; t->Stop(wait_thread_exit); } if (thread_num_ > 0 && wait_thread_exit) { while (!IsStopped()) { usleep(1); } } started_ = false; } bool EventLoopThreadPool::IsRunning() const { for (uint32_t i = 0; i < thread_num_; ++i) { const EventLoopThreadPtr& t = threads_[i]; if (!t->IsRunning()) { return false; } } return started_; } bool EventLoopThreadPool::IsStopped() const { if (thread_num_ == 0) { return !started_; } for (uint32_t i = 0; i < thread_num_; ++i) { const EventLoopThreadPtr& t = threads_[i]; if (!t->IsStopped()) { return false; } } return true; } EventLoop* EventLoopThreadPool::GetNextLoop() { EventLoop* loop = base_loop_; if (!threads_.empty()) { // No need to lock here int64_t next = next_.fetch_add(1); next = next % threads_.size(); loop = (threads_[next])->event_loop(); } return loop; } EventLoop* EventLoopThreadPool::GetNextLoopWithHash(uint64_t hash) { EventLoop* loop = base_loop_; if (!threads_.empty()) { uint64_t next = hash % threads_.size(); loop = (threads_[next])->event_loop(); } return loop; } uint32_t EventLoopThreadPool::thread_num() const { return thread_num_; } } <commit_msg>Fix EventLoopThreadPool::IsRunning() bug when it is not started<commit_after>#include "evpp/inner_pre.h" #include "evpp/event_loop_thread_pool.h" #include "evpp/event_loop.h" namespace evpp { EventLoopThreadPool::EventLoopThreadPool(EventLoop* base_loop, uint32_t thread_number) : base_loop_(base_loop), started_(false), thread_num_(thread_number), next_(0) {} EventLoopThreadPool::~EventLoopThreadPool() { assert(thread_num_ == threads_.size()); for (uint32_t i = 0; i < thread_num_; i++) { assert(threads_[i]->IsStopped()); } threads_.clear(); } bool EventLoopThreadPool::Start(bool wait_until_thread_started) { assert(!started_); if (started_) { return true; } for (uint32_t i = 0; i < thread_num_; ++i) { std::stringstream ss; ss << "EventLoopThreadPool-thread-" << i << "th"; EventLoopThreadPtr t(new EventLoopThread()); if (!t->Start(wait_until_thread_started)) { //FIXME error process LOG_ERROR << "start thread failed!"; return false; } t->SetName(ss.str()); threads_.push_back(t); } started_ = true; return true; } void EventLoopThreadPool::Stop(bool wait_thread_exit) { for (uint32_t i = 0; i < thread_num_; ++i) { EventLoopThreadPtr& t = threads_[i]; t->Stop(wait_thread_exit); } if (thread_num_ > 0 && wait_thread_exit) { while (!IsStopped()) { usleep(1); } } started_ = false; } bool EventLoopThreadPool::IsRunning() const { if (!started_) { return false; } for (uint32_t i = 0; i < thread_num_; ++i) { const EventLoopThreadPtr& t = threads_[i]; if (!t->IsRunning()) { return false; } } return started_; } bool EventLoopThreadPool::IsStopped() const { if (thread_num_ == 0) { return !started_; } for (uint32_t i = 0; i < thread_num_; ++i) { const EventLoopThreadPtr& t = threads_[i]; if (!t->IsStopped()) { return false; } } return true; } EventLoop* EventLoopThreadPool::GetNextLoop() { EventLoop* loop = base_loop_; if (!threads_.empty()) { // No need to lock here int64_t next = next_.fetch_add(1); next = next % threads_.size(); loop = (threads_[next])->event_loop(); } return loop; } EventLoop* EventLoopThreadPool::GetNextLoopWithHash(uint64_t hash) { EventLoop* loop = base_loop_; if (!threads_.empty()) { uint64_t next = hash % threads_.size(); loop = (threads_[next])->event_loop(); } return loop; } uint32_t EventLoopThreadPool::thread_num() const { return thread_num_; } } <|endoftext|>
<commit_before>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (directui@nokia.com) ** ** This file is part of libmeegotouch. ** ** If you have questions regarding the use of this file, please contact ** Nokia at directui@nokia.com. ** ** 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 ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include "ft_mscalableimage.h" #include "mapplication.h" #include <corelib/theme/mtheme.h> #include <corelib/painting/mscalableimage.h> #include <QtTest> #include <QPainter> QVector<QPixmap *> pixmaps; const int BLOCK_SIZE = 10; QString COLOR_TOPLEFT("#00ff00"); QString COLOR_TOP("#ff0000"); QString COLOR_TOPRIGHT("#00ff00"); QString COLOR_LEFT("#ff0000"); QString COLOR_CENTER("#0000ff"); QString COLOR_RIGHT("#ff0000"); QString COLOR_BOTTOMLEFT("#00ff00"); QString COLOR_BOTTOM("#ff0000"); QString COLOR_BOTTOMRIGHT("#00ff00"); // Override mtheme pixmap, to provide our own test pixmaps const QPixmap *createPixmap(const QString &id, const QSize &size) { if (id == "single_image") { QSize image_size = size.isValid() ? size : QSize(512, 512); QPixmap *pixmap = new QPixmap(image_size); int center_width = image_size.width() - 2 * BLOCK_SIZE; int center_height = image_size.height() - 2 * BLOCK_SIZE; QPainter painter(pixmap); painter.setRenderHint(QPainter::SmoothPixmapTransform, false); painter.fillRect(0, 0, BLOCK_SIZE, BLOCK_SIZE, QColor(COLOR_TOPLEFT)); painter.fillRect(BLOCK_SIZE, 0, center_width, BLOCK_SIZE, QColor(COLOR_TOP)); painter.fillRect(BLOCK_SIZE + center_width, 0, BLOCK_SIZE, BLOCK_SIZE, QColor(COLOR_TOPRIGHT)); painter.fillRect(0, BLOCK_SIZE, BLOCK_SIZE, center_height, QColor(COLOR_LEFT)); painter.fillRect(BLOCK_SIZE, BLOCK_SIZE, center_width, center_height, QColor(COLOR_CENTER)); painter.fillRect(BLOCK_SIZE + center_width, BLOCK_SIZE, BLOCK_SIZE, center_height, QColor(COLOR_RIGHT)); painter.fillRect(0, BLOCK_SIZE + center_height, BLOCK_SIZE, BLOCK_SIZE, QColor(COLOR_BOTTOMLEFT)); painter.fillRect(BLOCK_SIZE, BLOCK_SIZE + center_height, center_width, BLOCK_SIZE, QColor(COLOR_BOTTOM)); painter.fillRect(BLOCK_SIZE + center_width, BLOCK_SIZE + center_height, BLOCK_SIZE, BLOCK_SIZE, QColor(COLOR_BOTTOMRIGHT)); // debug //pixmap->save("test2.png"); return pixmap; } else { QPixmap *pixmap = new QPixmap(size.isValid() ? size : QSize(BLOCK_SIZE, BLOCK_SIZE)); pixmap->fill(QColor(id)); pixmaps.push_back(pixmap); return pixmap; } } Ft_MScalableImage::Ft_MScalableImage() { } void Ft_MScalableImage::init() { m_subject = new MScalableImage(); } void Ft_MScalableImage::cleanup() { for (int i = 0; i < pixmaps.size(); i++) { delete pixmaps[i]; } pixmaps.clear(); delete m_subject; } MApplication *app; void Ft_MScalableImage::initTestCase() { static int argc = 1; static char *app_name[1] = { (char *) "./Ft_MScalableImage" }; app = new MApplication(argc, app_name); } void Ft_MScalableImage::cleanupTestCase() { delete app; } bool isImageBlockColor(const QImage &image, const QRect &rect, const QString &colorid) { QColor color(colorid); QImage copy = image.copy(rect); for (int y = 0; y < copy.height(); y++) { for (int x = 0; x < copy.width(); x++) { if (copy.pixel(x, y) != color.rgb()) { return false; } } } return true; } void Ft_MScalableImage::test_construction() { // topleft, topright, bottomleft, bottomright, top, left, bottom, right, center const QPixmap *pm = createPixmap("single_image", QSize(-1, -1)); m_subject->setPixmap(pm); m_subject->setBorders(BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE); // adjust these to draw different size images to different location QSize image_size = QSize(512, 512); QPoint paint_offset = QPoint(6, 6); QSize paint_size = QSize(256, 256); QPixmap canvas(image_size); canvas.fill(Qt::black); QPainter painter(&canvas); painter.setRenderHint(QPainter::SmoothPixmapTransform, false); // draw from image-offset to the edge of the canvas m_subject->draw(paint_offset, paint_size, &painter); // save, debug //canvas.save("/tmp/test.png"); // check that the image looks proper, // clip only the part that should contain the drawn data QRect fillRegion(paint_offset, paint_size); QImage image = canvas.toImage().copy(fillRegion); // calculate the size for the center block int center_width = paint_size.width() - 2 * BLOCK_SIZE; int center_height = paint_size.height() - 2 * BLOCK_SIZE; // corners QCOMPARE(isImageBlockColor(image, QRect(0, 0, BLOCK_SIZE, BLOCK_SIZE), COLOR_TOPLEFT), true); QCOMPARE(isImageBlockColor(image, QRect(BLOCK_SIZE + center_width, 0, BLOCK_SIZE, BLOCK_SIZE), COLOR_TOPRIGHT), true); QCOMPARE(isImageBlockColor(image, QRect(0, BLOCK_SIZE + center_height, BLOCK_SIZE, BLOCK_SIZE), COLOR_BOTTOMLEFT), true); QCOMPARE(isImageBlockColor(image, QRect(BLOCK_SIZE + center_width, BLOCK_SIZE + center_height, BLOCK_SIZE, BLOCK_SIZE), COLOR_BOTTOMRIGHT), true); // edges QCOMPARE(isImageBlockColor(image, QRect(BLOCK_SIZE, 0, center_width, BLOCK_SIZE), COLOR_TOP), true); QCOMPARE(isImageBlockColor(image, QRect(0, BLOCK_SIZE, BLOCK_SIZE, center_height), COLOR_LEFT), true); QCOMPARE(isImageBlockColor(image, QRect(BLOCK_SIZE, BLOCK_SIZE + center_height, center_width, BLOCK_SIZE), COLOR_BOTTOM), true); QCOMPARE(isImageBlockColor(image, QRect(BLOCK_SIZE + center_width, BLOCK_SIZE, BLOCK_SIZE, center_height), COLOR_RIGHT), true); // center QCOMPARE(isImageBlockColor(image, QRect(BLOCK_SIZE, BLOCK_SIZE, center_width, center_height), COLOR_CENTER), true); } QTEST_APPLESS_MAIN(Ft_MScalableImage) <commit_msg>Changes: Fixed failing ft_mscalableimage.<commit_after>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (directui@nokia.com) ** ** This file is part of libmeegotouch. ** ** If you have questions regarding the use of this file, please contact ** Nokia at directui@nokia.com. ** ** 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 ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include "ft_mscalableimage.h" #include "mapplication.h" #include <corelib/theme/mtheme.h> #include <corelib/painting/mscalableimage.h> #include <QtTest> #include <QPainter> QVector<QPixmap *> pixmaps; const int BLOCK_SIZE = 10; QString COLOR_TOPLEFT("#00ff00"); QString COLOR_TOP("#ff0000"); QString COLOR_TOPRIGHT("#00ff00"); QString COLOR_LEFT("#ff0000"); QString COLOR_CENTER("#0000ff"); QString COLOR_RIGHT("#ff0000"); QString COLOR_BOTTOMLEFT("#00ff00"); QString COLOR_BOTTOM("#ff0000"); QString COLOR_BOTTOMRIGHT("#00ff00"); // Override mtheme pixmap, to provide our own test pixmaps const QPixmap *createPixmap(const QString &id, const QSize &size) { if (id == "single_image") { QSize image_size = size.isValid() ? size : QSize(512, 512); QPixmap *pixmap = new QPixmap(image_size); int center_width = image_size.width() - 2 * BLOCK_SIZE; int center_height = image_size.height() - 2 * BLOCK_SIZE; QPainter painter(pixmap); painter.setRenderHint(QPainter::SmoothPixmapTransform, false); painter.fillRect(0, 0, BLOCK_SIZE, BLOCK_SIZE, QColor(COLOR_TOPLEFT)); painter.fillRect(BLOCK_SIZE, 0, center_width, BLOCK_SIZE, QColor(COLOR_TOP)); painter.fillRect(BLOCK_SIZE + center_width, 0, BLOCK_SIZE, BLOCK_SIZE, QColor(COLOR_TOPRIGHT)); painter.fillRect(0, BLOCK_SIZE, BLOCK_SIZE, center_height, QColor(COLOR_LEFT)); painter.fillRect(BLOCK_SIZE, BLOCK_SIZE, center_width, center_height, QColor(COLOR_CENTER)); painter.fillRect(BLOCK_SIZE + center_width, BLOCK_SIZE, BLOCK_SIZE, center_height, QColor(COLOR_RIGHT)); painter.fillRect(0, BLOCK_SIZE + center_height, BLOCK_SIZE, BLOCK_SIZE, QColor(COLOR_BOTTOMLEFT)); painter.fillRect(BLOCK_SIZE, BLOCK_SIZE + center_height, center_width, BLOCK_SIZE, QColor(COLOR_BOTTOM)); painter.fillRect(BLOCK_SIZE + center_width, BLOCK_SIZE + center_height, BLOCK_SIZE, BLOCK_SIZE, QColor(COLOR_BOTTOMRIGHT)); // debug //pixmap->save("test2.png"); return pixmap; } else { QPixmap *pixmap = new QPixmap(size.isValid() ? size : QSize(BLOCK_SIZE, BLOCK_SIZE)); pixmap->fill(QColor(id)); pixmaps.push_back(pixmap); return pixmap; } } Ft_MScalableImage::Ft_MScalableImage() { } void Ft_MScalableImage::init() { m_subject = new MScalableImage(); } void Ft_MScalableImage::cleanup() { for (int i = 0; i < pixmaps.size(); i++) { delete pixmaps[i]; } pixmaps.clear(); delete m_subject; } MApplication *app; void Ft_MScalableImage::initTestCase() { static int argc = 1; static char *app_name[1] = { (char *) "./Ft_MScalableImage" }; app = new MApplication(argc, app_name); } void Ft_MScalableImage::cleanupTestCase() { delete app; } bool isImageBlockColor(const QImage &image, const QRect &rect, const QString &colorid) { QColor color(colorid); QImage copy = image.copy(rect); for (int y = 0; y < copy.height(); y++) { for (int x = 0; x < copy.width(); x++) { if (copy.pixel(x, y) != color.rgb()) { return false; } } } return true; } void Ft_MScalableImage::test_construction() { // topleft, topright, bottomleft, bottomright, top, left, bottom, right, center const QPixmap *pm = createPixmap("single_image", QSize(-1, -1)); m_subject->setPixmap(pm); m_subject->setBorders(BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE); // adjust these to draw different size images to different location QSize image_size = QSize(512, 512); QPoint paint_offset = QPoint(6, 6); QSize paint_size = QSize(256, 256); QPixmap canvas(image_size); canvas.fill(Qt::black); QPainter painter(&canvas); painter.setRenderHint(QPainter::SmoothPixmapTransform, false); // draw from image-offset to the edge of the canvas m_subject->draw(paint_offset, paint_size, &painter); // save, debug //canvas.save("/tmp/test.png"); // check that the image looks proper, // clip only the part that should contain the drawn data QRect fillRegion(paint_offset, paint_size); QImage image = canvas.toImage().copy(fillRegion); // calculate the size for the center block int center_width = paint_size.width() - 2 * BLOCK_SIZE; int center_height = paint_size.height() - 2 * BLOCK_SIZE; // corners QCOMPARE(isImageBlockColor(image, QRect(2, 2, BLOCK_SIZE-2, BLOCK_SIZE-2), COLOR_TOPLEFT), true); QCOMPARE(isImageBlockColor(image, QRect(BLOCK_SIZE + center_width + 2, 2, BLOCK_SIZE-2, BLOCK_SIZE-2), COLOR_TOPRIGHT), true); QCOMPARE(isImageBlockColor(image, QRect(2, BLOCK_SIZE + center_height + 2, BLOCK_SIZE-2, BLOCK_SIZE-2), COLOR_BOTTOMLEFT), true); QCOMPARE(isImageBlockColor(image, QRect(BLOCK_SIZE + center_width + 2, BLOCK_SIZE + center_height + 2, BLOCK_SIZE - 2, BLOCK_SIZE - 2), COLOR_BOTTOMRIGHT), true); // edges QCOMPARE(isImageBlockColor(image, QRect(BLOCK_SIZE+2, 2, center_width-2, BLOCK_SIZE-2), COLOR_TOP), true); QCOMPARE(isImageBlockColor(image, QRect(2, BLOCK_SIZE+2, BLOCK_SIZE-2, center_height-2), COLOR_LEFT), true); QCOMPARE(isImageBlockColor(image, QRect(BLOCK_SIZE+2, BLOCK_SIZE + center_height + 2, center_width-2, BLOCK_SIZE-2), COLOR_BOTTOM), true); QCOMPARE(isImageBlockColor(image, QRect(BLOCK_SIZE + center_width + 2, BLOCK_SIZE + 2, BLOCK_SIZE-2, center_height-2), COLOR_RIGHT), true); // center QCOMPARE(isImageBlockColor(image, QRect(BLOCK_SIZE, BLOCK_SIZE, center_width, center_height), COLOR_CENTER), true); } QTEST_APPLESS_MAIN(Ft_MScalableImage) <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2007-2008, 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 <algorithm> #include <cassert> #include <stdio.h> #include <iostream> #include <fstream> #include <setjmp.h> #include "IECore/JPEGImageReader.h" #include "IECore/SimpleTypedData.h" #include "IECore/VectorTypedData.h" #include "IECore/ByteOrder.h" #include "IECore/MessageHandler.h" #include "IECore/ImagePrimitive.h" #include "IECore/FileNameParameter.h" #include "IECore/BoxOps.h" #include "boost/format.hpp" extern "C" { #include "jpeglib.h" } using namespace IECore; using namespace boost; using namespace Imath; using namespace std; const Reader::ReaderDescription <JPEGImageReader> JPEGImageReader::m_readerDescription ("jpeg jpg"); JPEGImageReader::JPEGImageReader() : ImageReader( "JPEGImageReader", "Reads Joint Photographic Experts Group (JPEG) files" ) { } JPEGImageReader::JPEGImageReader(const string & fileName) : ImageReader( "JPEGImageReader", "Reads Joint Photographic Experts Group (JPEG) files" ) { m_fileNameParameter->setTypedValue( fileName ); } JPEGImageReader::~JPEGImageReader() { } bool JPEGImageReader::canRead( const string &fileName ) { // attempt to open the file ifstream in(fileName.c_str()); if (!in.is_open()) { return false; } // check the magic number of the input file // a jpeg should have 0xffd8ffe0 from offset 0 unsigned int magic; in.seekg(0, ios_base::beg); in.read((char *) &magic, sizeof(unsigned int)); return magic == 0xe0ffd8ff || magic == 0xffd8ffe0 || magic == 0xe1ffd8ff || magic == 0xffd8ffe1 ; } void JPEGImageReader::channelNames( vector<string> &names ) { open( true ); names.clear(); if ( m_numChannels == 3 ) { names.push_back("R"); names.push_back("G"); names.push_back("B"); } else { assert ( m_numChannels == 1 ); names.push_back("Y"); } } bool JPEGImageReader::isComplete() { return open( false ); } Imath::Box2i JPEGImageReader::dataWindow() { open( true ); return Box2i( V2i( 0, 0 ), V2i( m_bufferWidth - 1, m_bufferHeight - 1 ) ); } Imath::Box2i JPEGImageReader::displayWindow() { return dataWindow(); } DataPtr JPEGImageReader::readChannel( const std::string &name, const Imath::Box2i &dataWindow ) { open( true ); int channelOffset = 0; if ( name == "R" ) { channelOffset = 0; } else if ( name == "G" ) { channelOffset = 1; } else if ( name == "B" ) { channelOffset = 2; } else if ( name == "Y" ) { channelOffset = 0; } else { throw IOException( ( boost::format( "JPEGImageReader: Could not find channel \"%s\" while reading %s" ) % name % m_bufferFileName ).str() ); } assert( channelOffset < m_numChannels ); HalfVectorDataPtr dataContainer = new HalfVectorData(); HalfVectorData::ValueType &data = dataContainer->writable(); int area = ( dataWindow.size().x + 1 ) * ( dataWindow.size().y + 1 ); assert( area >= 0 ); data.resize( area ); int dataWidth = 1 + dataWindow.size().x; int dataY = 0; for ( int y = dataWindow.min.y; y <= dataWindow.max.y; ++y, ++dataY ) { HalfVectorData::ValueType::size_type dataOffset = dataY * dataWidth; for ( int x = dataWindow.min.x; x <= dataWindow.max.x; ++x, ++dataOffset ) { assert( dataOffset < data.size() ); data[dataOffset] = m_buffer[ m_numChannels * ( y * m_bufferWidth + x ) + channelOffset ] / 255.0f; } } return dataContainer; } struct JPEGReaderErrorHandler : public jpeg_error_mgr { jmp_buf m_jmpBuffer; char m_errorMessage[JMSG_LENGTH_MAX]; static void errorExit ( j_common_ptr cinfo ) { assert( cinfo ); assert( cinfo->err ); JPEGReaderErrorHandler* errorHandler = static_cast< JPEGReaderErrorHandler* >( cinfo->err ); ( *cinfo->err->format_message )( cinfo, errorHandler->m_errorMessage ); longjmp( errorHandler->m_jmpBuffer, 1 ); } }; bool JPEGImageReader::open( bool throwOnFailure ) { if ( fileName() == m_bufferFileName ) { return true; } m_bufferFileName = fileName(); m_buffer.clear(); FILE *inFile = 0; try { // open the file inFile = fopen( m_bufferFileName.c_str(), "rb" ); if ( !inFile ) { throw IOException( ( boost::format( "JPEGImageReader: Could not open file %s" ) % m_bufferFileName ).str() ); } struct jpeg_decompress_struct cinfo; try { JPEGReaderErrorHandler errorHandler; /// Setup error handler cinfo.err = jpeg_std_error( &errorHandler ); /// Override fatal error and warning handlers errorHandler.error_exit = JPEGReaderErrorHandler::errorExit; errorHandler.output_message = JPEGReaderErrorHandler::errorExit; /// If we reach here then libjpeg has called our error handler, in which we've saved a copy of the /// error such that we might throw it as an exception. if ( setjmp( errorHandler.m_jmpBuffer ) ) { throw IOException( std::string( "JPEGImageReader: " ) + errorHandler.m_errorMessage ); } /// Initialize decompressor to read from "inFile" jpeg_create_decompress( &cinfo ); jpeg_stdio_src( &cinfo, inFile ); jpeg_read_header( &cinfo, TRUE ); /// Start decompression jpeg_start_decompress( &cinfo ); m_numChannels = cinfo.output_components; if ( m_numChannels != 1 && m_numChannels != 3 ) { throw IOException( ( boost::format( "JPEGImageReader: Unsupported number of channels (%d) while opening file %s" ) % m_numChannels % m_bufferFileName ).str() ); } if ( cinfo.out_color_space == JCS_GRAYSCALE ) { assert( m_numChannels == 1 ); } else if ( cinfo.out_color_space != JCS_RGB ) { throw IOException( ( boost::format( "JPEGImageReader: Unsupported colorspace (%d) while opening file %s" ) % cinfo.out_color_space % m_bufferFileName ).str() ); } /// Create buffer int rowStride = cinfo.output_width * cinfo.output_components; m_buffer.resize( rowStride * cinfo.output_height, 0 ); ; m_bufferWidth = cinfo.output_width; m_bufferHeight = cinfo.output_height; /// Read scanlines one at a time. while (cinfo.output_scanline < cinfo.output_height) { unsigned char *rowPointer[1] = { &m_buffer[0] + rowStride * cinfo.output_scanline }; jpeg_read_scanlines( &cinfo, rowPointer, 1 ); } /// Finish decompression jpeg_finish_decompress( &cinfo ); jpeg_destroy_decompress( &cinfo ); } catch ( Exception &e ) { jpeg_destroy_decompress( &cinfo ); throw; } catch ( std::exception &e ) { jpeg_destroy_decompress( &cinfo ); throw IOException( ( boost::format( "JPEGImageReader : %s" ) % e.what() ).str() ); } catch ( ... ) { jpeg_destroy_decompress( &cinfo ); throw IOException( "JPEGImageReader: Unexpected error" ); } fclose( inFile ); } catch (...) { if ( inFile ) { fclose( inFile ); } if ( throwOnFailure ) { throw; } else { return false; } } return true; } <commit_msg>Added todo<commit_after>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2007-2008, 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 <algorithm> #include <cassert> #include <stdio.h> #include <iostream> #include <fstream> #include <setjmp.h> #include "IECore/JPEGImageReader.h" #include "IECore/SimpleTypedData.h" #include "IECore/VectorTypedData.h" #include "IECore/ByteOrder.h" #include "IECore/MessageHandler.h" #include "IECore/ImagePrimitive.h" #include "IECore/FileNameParameter.h" #include "IECore/BoxOps.h" #include "boost/format.hpp" extern "C" { #include "jpeglib.h" } using namespace IECore; using namespace boost; using namespace Imath; using namespace std; const Reader::ReaderDescription <JPEGImageReader> JPEGImageReader::m_readerDescription ("jpeg jpg"); JPEGImageReader::JPEGImageReader() : ImageReader( "JPEGImageReader", "Reads Joint Photographic Experts Group (JPEG) files" ) { } JPEGImageReader::JPEGImageReader(const string & fileName) : ImageReader( "JPEGImageReader", "Reads Joint Photographic Experts Group (JPEG) files" ) { m_fileNameParameter->setTypedValue( fileName ); } JPEGImageReader::~JPEGImageReader() { } bool JPEGImageReader::canRead( const string &fileName ) { // attempt to open the file ifstream in(fileName.c_str()); if (!in.is_open()) { return false; } // check the magic number of the input file // a jpeg should have 0xffd8ffe0 from offset 0 unsigned int magic; in.seekg(0, ios_base::beg); in.read((char *) &magic, sizeof(unsigned int)); return magic == 0xe0ffd8ff || magic == 0xffd8ffe0 || magic == 0xe1ffd8ff || magic == 0xffd8ffe1 ; } void JPEGImageReader::channelNames( vector<string> &names ) { open( true ); names.clear(); if ( m_numChannels == 3 ) { names.push_back("R"); names.push_back("G"); names.push_back("B"); } else { assert ( m_numChannels == 1 ); names.push_back("Y"); } } bool JPEGImageReader::isComplete() { return open( false ); } Imath::Box2i JPEGImageReader::dataWindow() { open( true ); return Box2i( V2i( 0, 0 ), V2i( m_bufferWidth - 1, m_bufferHeight - 1 ) ); } Imath::Box2i JPEGImageReader::displayWindow() { return dataWindow(); } DataPtr JPEGImageReader::readChannel( const std::string &name, const Imath::Box2i &dataWindow ) { open( true ); int channelOffset = 0; if ( name == "R" ) { channelOffset = 0; } else if ( name == "G" ) { channelOffset = 1; } else if ( name == "B" ) { channelOffset = 2; } else if ( name == "Y" ) { channelOffset = 0; } else { throw IOException( ( boost::format( "JPEGImageReader: Could not find channel \"%s\" while reading %s" ) % name % m_bufferFileName ).str() ); } assert( channelOffset < m_numChannels ); HalfVectorDataPtr dataContainer = new HalfVectorData(); HalfVectorData::ValueType &data = dataContainer->writable(); int area = ( dataWindow.size().x + 1 ) * ( dataWindow.size().y + 1 ); assert( area >= 0 ); data.resize( area ); int dataWidth = 1 + dataWindow.size().x; int dataY = 0; for ( int y = dataWindow.min.y; y <= dataWindow.max.y; ++y, ++dataY ) { HalfVectorData::ValueType::size_type dataOffset = dataY * dataWidth; for ( int x = dataWindow.min.x; x <= dataWindow.max.x; ++x, ++dataOffset ) { assert( dataOffset < data.size() ); data[dataOffset] = m_buffer[ m_numChannels * ( y * m_bufferWidth + x ) + channelOffset ] / 255.0f; } } return dataContainer; } struct JPEGReaderErrorHandler : public jpeg_error_mgr { jmp_buf m_jmpBuffer; char m_errorMessage[JMSG_LENGTH_MAX]; static void errorExit ( j_common_ptr cinfo ) { assert( cinfo ); assert( cinfo->err ); JPEGReaderErrorHandler* errorHandler = static_cast< JPEGReaderErrorHandler* >( cinfo->err ); ( *cinfo->err->format_message )( cinfo, errorHandler->m_errorMessage ); longjmp( errorHandler->m_jmpBuffer, 1 ); } }; bool JPEGImageReader::open( bool throwOnFailure ) { if ( fileName() == m_bufferFileName ) { return true; } m_bufferFileName = fileName(); m_buffer.clear(); FILE *inFile = 0; try { // open the file inFile = fopen( m_bufferFileName.c_str(), "rb" ); if ( !inFile ) { throw IOException( ( boost::format( "JPEGImageReader: Could not open file %s" ) % m_bufferFileName ).str() ); } struct jpeg_decompress_struct cinfo; try { JPEGReaderErrorHandler errorHandler; /// Setup error handler cinfo.err = jpeg_std_error( &errorHandler ); /// Override fatal error and warning handlers errorHandler.error_exit = JPEGReaderErrorHandler::errorExit; errorHandler.output_message = JPEGReaderErrorHandler::errorExit; /// If we reach here then libjpeg has called our error handler, in which we've saved a copy of the /// error such that we might throw it as an exception. if ( setjmp( errorHandler.m_jmpBuffer ) ) { throw IOException( std::string( "JPEGImageReader: " ) + errorHandler.m_errorMessage ); } /// Initialize decompressor to read from "inFile" jpeg_create_decompress( &cinfo ); jpeg_stdio_src( &cinfo, inFile ); jpeg_read_header( &cinfo, TRUE ); /// Start decompression jpeg_start_decompress( &cinfo ); m_numChannels = cinfo.output_components; if ( m_numChannels != 1 && m_numChannels != 3 ) { throw IOException( ( boost::format( "JPEGImageReader: Unsupported number of channels (%d) while opening file %s" ) % m_numChannels % m_bufferFileName ).str() ); } if ( cinfo.out_color_space == JCS_GRAYSCALE ) { assert( m_numChannels == 1 ); } else if ( cinfo.out_color_space != JCS_RGB ) { throw IOException( ( boost::format( "JPEGImageReader: Unsupported colorspace (%d) while opening file %s" ) % cinfo.out_color_space % m_bufferFileName ).str() ); } /// \todo Add support for JCS_YCbCr encoding, and make sure that we add a parameter that /// species whether we should rescale values 0-255 to 16-235 (Y) and 16-239 (Cb/Cr) - default /// should be true. See http://www.fourcc.org/fccyvrgb.php for further info. /// Create buffer int rowStride = cinfo.output_width * cinfo.output_components; m_buffer.resize( rowStride * cinfo.output_height, 0 ); ; m_bufferWidth = cinfo.output_width; m_bufferHeight = cinfo.output_height; /// Read scanlines one at a time. while (cinfo.output_scanline < cinfo.output_height) { unsigned char *rowPointer[1] = { &m_buffer[0] + rowStride * cinfo.output_scanline }; jpeg_read_scanlines( &cinfo, rowPointer, 1 ); } /// Finish decompression jpeg_finish_decompress( &cinfo ); jpeg_destroy_decompress( &cinfo ); } catch ( Exception &e ) { jpeg_destroy_decompress( &cinfo ); throw; } catch ( std::exception &e ) { jpeg_destroy_decompress( &cinfo ); throw IOException( ( boost::format( "JPEGImageReader : %s" ) % e.what() ).str() ); } catch ( ... ) { jpeg_destroy_decompress( &cinfo ); throw IOException( "JPEGImageReader: Unexpected error" ); } fclose( inFile ); } catch (...) { if ( inFile ) { fclose( inFile ); } if ( throwOnFailure ) { throw; } else { return false; } } return true; } <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <catch2/catch.hpp> #include "libslic3r/TriangleMesh.hpp" using namespace Slic3r; TEST_CASE("Split empty mesh", "[its_split][its]") { using namespace Slic3r; indexed_triangle_set its; std::vector<indexed_triangle_set> res = its_split(its); REQUIRE(res.empty()); } TEST_CASE("Split simple mesh consisting of one part", "[its_split][its]") { using namespace Slic3r; auto cube = its_make_cube(10., 10., 10.); std::vector<indexed_triangle_set> res = its_split(cube); REQUIRE(res.size() == 1); REQUIRE(res.front().indices.size() == cube.indices.size()); REQUIRE(res.front().vertices.size() == cube.vertices.size()); } void debug_write_obj(const std::vector<indexed_triangle_set> &res, const std::string &name) { #ifndef NDEBUG size_t part_idx = 0; for (auto &part_its : res) { its_write_obj(part_its, (name + std::to_string(part_idx++) + ".obj").c_str()); } #endif } TEST_CASE("Split two non-watertight mesh", "[its_split][its]") { using namespace Slic3r; auto cube1 = its_make_cube(10., 10., 10.); cube1.indices.pop_back(); auto cube2 = cube1; its_transform(cube1, identity3f().translate(Vec3f{-5.f, 0.f, 0.f})); its_transform(cube2, identity3f().translate(Vec3f{5.f, 0.f, 0.f})); its_merge(cube1, cube2); std::vector<indexed_triangle_set> res = its_split(cube1); REQUIRE(res.size() == 2); REQUIRE(res[0].indices.size() == res[1].indices.size()); REQUIRE(res[0].indices.size() == cube2.indices.size()); REQUIRE(res[0].vertices.size() == res[1].vertices.size()); REQUIRE(res[0].vertices.size() == cube2.vertices.size()); debug_write_obj(res, "parts_non_watertight"); } TEST_CASE("Split non-manifold mesh", "[its_split][its]") { using namespace Slic3r; auto cube = its_make_cube(10., 10., 10.), cube_low = cube; its_transform(cube_low, identity3f().translate(Vec3f{10.f, 10.f, 10.f})); its_merge(cube, cube_low); its_merge_vertices(cube); std::vector<indexed_triangle_set> res = its_split(cube); REQUIRE(res.size() == 2); REQUIRE(res[0].indices.size() == res[1].indices.size()); REQUIRE(res[0].indices.size() == cube_low.indices.size()); REQUIRE(res[0].vertices.size() == res[1].vertices.size()); REQUIRE(res[0].vertices.size() == cube_low.vertices.size()); debug_write_obj(res, "cubes_non_manifold"); } TEST_CASE("Split two watertight meshes", "[its_split][its]") { using namespace Slic3r; auto sphere1 = its_make_sphere(10., 2 * PI / 200.), sphere2 = sphere1; its_transform(sphere1, identity3f().translate(Vec3f{-5.f, 0.f, 0.f})); its_transform(sphere2, identity3f().translate(Vec3f{5.f, 0.f, 0.f})); its_merge(sphere1, sphere2); std::vector<indexed_triangle_set> res = its_split(sphere1); REQUIRE(res.size() == 2); REQUIRE(res[0].indices.size() == res[1].indices.size()); REQUIRE(res[0].indices.size() == sphere2.indices.size()); REQUIRE(res[0].vertices.size() == res[1].vertices.size()); REQUIRE(res[0].vertices.size() == sphere2.vertices.size()); debug_write_obj(res, "parts_watertight"); } #include <libslic3r/QuadricEdgeCollapse.hpp> TEST_CASE("Reduce one edge by Quadric Edge Collapse", "[its]") { indexed_triangle_set its; its.vertices = {Vec3f(-1.f, 0.f, 0.f), Vec3f(0.f, 1.f, 0.f), Vec3f(1.f, 0.f, 0.f), Vec3f(0.f, 0.f, 1.f), // vertex to be removed Vec3f(0.9f, .1f, -.1f)}; its.indices = {Vec3i(1, 0, 3), Vec3i(2, 1, 3), Vec3i(0, 2, 3), Vec3i(0, 1, 4), Vec3i(1, 2, 4), Vec3i(2, 0, 4)}; // edge to remove is between vertices 2 and 4 on trinagles 4 and 5 indexed_triangle_set its_ = its; // copy // its_write_obj(its, "tetrhedron_in.obj"); size_t wanted_count = its.indices.size() - 1; CHECK(its_quadric_edge_collapse(its, wanted_count)); // its_write_obj(its, "tetrhedron_out.obj"); CHECK(its.indices.size() == 4); CHECK(its.vertices.size() == 4); for (size_t i = 0; i < 3; i++) { CHECK(its.indices[i] == its_.indices[i]); } for (size_t i = 0; i < 4; i++) { if (i == 2) continue; CHECK(its.vertices[i] == its_.vertices[i]); } const Vec3f &v = its.vertices[2]; // new vertex const Vec3f &v2 = its_.vertices[2]; // moved vertex const Vec3f &v4 = its_.vertices[4]; // removed vertex for (size_t i = 0; i < 3; i++) { bool is_between = (v[i] < v4[i] && v[i] > v2[i]) || (v[i] > v4[i] && v[i] < v2[i]); CHECK(is_between); } } #include "test_utils.hpp" TEST_CASE("Symplify mesh by Quadric edge collapse to 5%", "[its]") { TriangleMesh mesh = load_model("frog_legs.obj"); double original_volume = its_volume(mesh.its); size_t wanted_count = mesh.its.indices.size() * 0.05; REQUIRE_FALSE(mesh.empty()); indexed_triangle_set its = mesh.its; // copy its_quadric_edge_collapse(its, wanted_count); // its_write_obj(its, "frog_legs_qec.obj"); CHECK(its.indices.size() <= wanted_count); double volume = its_volume(its); CHECK(fabs(original_volume - volume) < 30.); }<commit_msg>Extend test with checking simplified model distance to original model<commit_after>#include <iostream> #include <fstream> #include <catch2/catch.hpp> #include "libslic3r/TriangleMesh.hpp" using namespace Slic3r; TEST_CASE("Split empty mesh", "[its_split][its]") { using namespace Slic3r; indexed_triangle_set its; std::vector<indexed_triangle_set> res = its_split(its); REQUIRE(res.empty()); } TEST_CASE("Split simple mesh consisting of one part", "[its_split][its]") { using namespace Slic3r; auto cube = its_make_cube(10., 10., 10.); std::vector<indexed_triangle_set> res = its_split(cube); REQUIRE(res.size() == 1); REQUIRE(res.front().indices.size() == cube.indices.size()); REQUIRE(res.front().vertices.size() == cube.vertices.size()); } void debug_write_obj(const std::vector<indexed_triangle_set> &res, const std::string &name) { #ifndef NDEBUG size_t part_idx = 0; for (auto &part_its : res) { its_write_obj(part_its, (name + std::to_string(part_idx++) + ".obj").c_str()); } #endif } TEST_CASE("Split two non-watertight mesh", "[its_split][its]") { using namespace Slic3r; auto cube1 = its_make_cube(10., 10., 10.); cube1.indices.pop_back(); auto cube2 = cube1; its_transform(cube1, identity3f().translate(Vec3f{-5.f, 0.f, 0.f})); its_transform(cube2, identity3f().translate(Vec3f{5.f, 0.f, 0.f})); its_merge(cube1, cube2); std::vector<indexed_triangle_set> res = its_split(cube1); REQUIRE(res.size() == 2); REQUIRE(res[0].indices.size() == res[1].indices.size()); REQUIRE(res[0].indices.size() == cube2.indices.size()); REQUIRE(res[0].vertices.size() == res[1].vertices.size()); REQUIRE(res[0].vertices.size() == cube2.vertices.size()); debug_write_obj(res, "parts_non_watertight"); } TEST_CASE("Split non-manifold mesh", "[its_split][its]") { using namespace Slic3r; auto cube = its_make_cube(10., 10., 10.), cube_low = cube; its_transform(cube_low, identity3f().translate(Vec3f{10.f, 10.f, 10.f})); its_merge(cube, cube_low); its_merge_vertices(cube); std::vector<indexed_triangle_set> res = its_split(cube); REQUIRE(res.size() == 2); REQUIRE(res[0].indices.size() == res[1].indices.size()); REQUIRE(res[0].indices.size() == cube_low.indices.size()); REQUIRE(res[0].vertices.size() == res[1].vertices.size()); REQUIRE(res[0].vertices.size() == cube_low.vertices.size()); debug_write_obj(res, "cubes_non_manifold"); } TEST_CASE("Split two watertight meshes", "[its_split][its]") { using namespace Slic3r; auto sphere1 = its_make_sphere(10., 2 * PI / 200.), sphere2 = sphere1; its_transform(sphere1, identity3f().translate(Vec3f{-5.f, 0.f, 0.f})); its_transform(sphere2, identity3f().translate(Vec3f{5.f, 0.f, 0.f})); its_merge(sphere1, sphere2); std::vector<indexed_triangle_set> res = its_split(sphere1); REQUIRE(res.size() == 2); REQUIRE(res[0].indices.size() == res[1].indices.size()); REQUIRE(res[0].indices.size() == sphere2.indices.size()); REQUIRE(res[0].vertices.size() == res[1].vertices.size()); REQUIRE(res[0].vertices.size() == sphere2.vertices.size()); debug_write_obj(res, "parts_watertight"); } #include <libslic3r/QuadricEdgeCollapse.hpp> static float triangle_area(const Vec3f &v0, const Vec3f &v1, const Vec3f &v2) { Vec3f ab = v1 - v0; Vec3f ac = v2 - v0; return ab.cross(ac).norm() / 2.f; } static float triangle_area(const Vec3crd &triangle_inices, const std::vector<Vec3f> &vertices) { return triangle_area(vertices[triangle_inices[0]], vertices[triangle_inices[1]], vertices[triangle_inices[2]]); } static std::mt19937 create_random_generator() { std::random_device rd; std::mt19937 gen(rd()); return gen; } std::vector<Vec3f> its_sample_surface(const indexed_triangle_set &its, double sample_per_mm2, std::mt19937 &random_generator = create_random_generator()) { std::vector<Vec3f> samples; std::uniform_real_distribution<float> rand01(0.f, 1.f); for (const auto &triangle_indices : its.indices) { float area = triangle_area(triangle_indices, its.vertices); float countf; float fractional = std::modf(area * sample_per_mm2, &countf); int count = static_cast<int>(countf); float generate = rand01(random_generator); if (generate < fractional) ++count; if (count == 0) continue; const Vec3f &v0 = its.vertices[triangle_indices[0]]; const Vec3f &v1 = its.vertices[triangle_indices[1]]; const Vec3f &v2 = its.vertices[triangle_indices[2]]; for (int c = 0; c < count; c++) { // barycentric coordinate Vec3f b; b[0] = rand01(random_generator); b[1] = rand01(random_generator); if ((b[0] + b[1]) > 1.f) { b[0] = 1.f - b[0]; b[1] = 1.f - b[1]; } b[2] = 1.f - b[0] - b[1]; Vec3f pos; for (int i = 0; i < 3; i++) { pos[i] = b[0] * v0[i] + b[1] * v1[i] + b[2] * v2[i]; } samples.push_back(pos); } } return samples; } #include "libslic3r/AABBTreeIndirect.hpp" // return Average abs distance to original float compare(const indexed_triangle_set &original, const indexed_triangle_set &simplified, double sample_per_mm2) { // create ABBTree auto tree = AABBTreeIndirect::build_aabb_tree_over_indexed_triangle_set( original.vertices, original.indices); unsigned int init = 0; std::mt19937 rnd(init); auto samples = its_sample_surface(simplified, sample_per_mm2, rnd); float sumDistance = 0; for (const Vec3f &sample : samples) { size_t hit_idx; Vec3f hit_point; float distance2 = AABBTreeIndirect::squared_distance_to_indexed_triangle_set( original.vertices, original.indices, tree, sample, hit_idx, hit_point); sumDistance += sqrt(distance2); } return sumDistance / samples.size(); } TEST_CASE("Reduce one edge by Quadric Edge Collapse", "[its]") { indexed_triangle_set its; its.vertices = {Vec3f(-1.f, 0.f, 0.f), Vec3f(0.f, 1.f, 0.f), Vec3f(1.f, 0.f, 0.f), Vec3f(0.f, 0.f, 1.f), // vertex to be removed Vec3f(0.9f, .1f, -.1f)}; its.indices = {Vec3i(1, 0, 3), Vec3i(2, 1, 3), Vec3i(0, 2, 3), Vec3i(0, 1, 4), Vec3i(1, 2, 4), Vec3i(2, 0, 4)}; // edge to remove is between vertices 2 and 4 on trinagles 4 and 5 indexed_triangle_set its_ = its; // copy // its_write_obj(its, "tetrhedron_in.obj"); size_t wanted_count = its.indices.size() - 1; CHECK(its_quadric_edge_collapse(its, wanted_count)); // its_write_obj(its, "tetrhedron_out.obj"); CHECK(its.indices.size() == 4); CHECK(its.vertices.size() == 4); for (size_t i = 0; i < 3; i++) { CHECK(its.indices[i] == its_.indices[i]); } for (size_t i = 0; i < 4; i++) { if (i == 2) continue; CHECK(its.vertices[i] == its_.vertices[i]); } const Vec3f &v = its.vertices[2]; // new vertex const Vec3f &v2 = its_.vertices[2]; // moved vertex const Vec3f &v4 = its_.vertices[4]; // removed vertex for (size_t i = 0; i < 3; i++) { bool is_between = (v[i] < v4[i] && v[i] > v2[i]) || (v[i] > v4[i] && v[i] < v2[i]); CHECK(is_between); } float avg_distance = compare(its_, its, 10); CHECK(avg_distance < 8e-3f); } #include "test_utils.hpp" TEST_CASE("Symplify mesh by Quadric edge collapse to 5%", "[its]") { TriangleMesh mesh = load_model("frog_legs.obj"); double original_volume = its_volume(mesh.its); size_t wanted_count = mesh.its.indices.size() * 0.05; REQUIRE_FALSE(mesh.empty()); indexed_triangle_set its = mesh.its; // copy its_quadric_edge_collapse(its, wanted_count); // its_write_obj(its, "frog_legs_qec.obj"); CHECK(its.indices.size() <= wanted_count); double volume = its_volume(its); CHECK(fabs(original_volume - volume) < 30.); float avg_distance = compare(mesh.its, its, 10); CHECK(avg_distance < 0.021f); // 0.02022 | 0.0199614074 }<|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/webui/web_ui.h" #include "base/command_line.h" #include "base/json/json_writer.h" #include "base/stl_util.h" #include "base/utf_string_conversions.h" #include "base/values.h" #include "content/browser/child_process_security_policy.h" #include "content/browser/renderer_host/render_process_host_impl.h" #include "content/browser/renderer_host/render_view_host.h" #include "content/browser/tab_contents/tab_contents.h" #include "content/browser/tab_contents/tab_contents_view.h" #include "content/browser/webui/generic_handler.h" #include "content/common/view_messages.h" #include "content/public/browser/web_ui_controller.h" #include "content/public/common/bindings_policy.h" #include "content/public/common/content_switches.h" using content::WebContents; using content::WebUIController; using content::WebUIMessageHandler; // static string16 WebUI::GetJavascriptCall( const std::string& function_name, const std::vector<const Value*>& arg_list) { string16 parameters; std::string json; for (size_t i = 0; i < arg_list.size(); ++i) { if (i > 0) parameters += char16(','); base::JSONWriter::Write(arg_list[i], false, &json); parameters += UTF8ToUTF16(json); } return ASCIIToUTF16(function_name) + char16('(') + parameters + char16(')') + char16(';'); } WebUI::WebUI(WebContents* contents) : focus_location_bar_by_default_(false), should_hide_url_(false), link_transition_type_(content::PAGE_TRANSITION_LINK), bindings_(content::BINDINGS_POLICY_WEB_UI), register_callback_overwrites_(false), web_contents_(contents) { DCHECK(contents); AddMessageHandler(new GenericHandler()); } WebUI::~WebUI() { // Delete the controller first, since it may also be keeping a pointer to some // of the handlers and can call them at destruction. controller_.reset(); STLDeleteContainerPointers(handlers_.begin(), handlers_.end()); } // WebUI, public: ------------------------------------------------------------- const WebUI::TypeID WebUI::kNoWebUI = NULL; bool WebUI::OnMessageReceived(const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(WebUI, message) IPC_MESSAGE_HANDLER(ViewHostMsg_WebUISend, OnWebUISend) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } void WebUI::OnWebUISend(const GURL& source_url, const std::string& message, const ListValue& args) { if (!ChildProcessSecurityPolicy::GetInstance()-> HasWebUIBindings(web_contents_->GetRenderProcessHost()->GetID())) { NOTREACHED() << "Blocked unauthorized use of WebUIBindings."; return; } if (controller_->OverrideHandleWebUIMessage(source_url, message,args)) return; // Look up the callback for this message. MessageCallbackMap::const_iterator callback = message_callbacks_.find(message); if (callback != message_callbacks_.end()) { // Forward this message and content on. callback->second.Run(&args); } } void WebUI::RenderViewCreated(RenderViewHost* render_view_host) { controller_->RenderViewCreated(render_view_host); // Do not attempt to set the toolkit property if WebUI is not enabled, e.g., // the bookmarks manager page. if (!(bindings_ & content::BINDINGS_POLICY_WEB_UI)) return; #if defined(TOOLKIT_VIEWS) render_view_host->SetWebUIProperty("toolkit", "views"); #elif defined(TOOLKIT_GTK) render_view_host->SetWebUIProperty("toolkit", "GTK"); #endif // defined(TOOLKIT_VIEWS) // Let the WebUI know that we're looking for UI that's optimized for touch // input. // TODO(rbyers) Figure out the right model for enabling touch-optimized UI // (http://crbug.com/105380). if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kTouchOptimizedUI)) render_view_host->SetWebUIProperty("touchOptimized", "true"); } WebContents* WebUI::GetWebContents() const { return web_contents_; } bool WebUI::ShouldHideFavicon() const { return hide_favicon_; } void WebUI::HideFavicon() { hide_favicon_ = true; } bool WebUI::ShouldFocusLocationBarByDefault() const { return focus_location_bar_by_default_; } void WebUI::FocusLocationBarByDefault() { focus_location_bar_by_default_ = true; } bool WebUI::ShouldHideURL() const { return should_hide_url_; } void WebUI::HideURL() { should_hide_url_ = true; } const string16& WebUI::GetOverriddenTitle() const { return overridden_title_; } void WebUI::OverrideTitle(const string16& title) { overridden_title_ = title; } content::PageTransition WebUI::GetLinkTransitionType() const { return link_transition_type_; } void WebUI::SetLinkTransitionType(content::PageTransition type) { link_transition_type_ = type; } int WebUI::GetBindings() const { return bindings_; } void WebUI::SetBindings(int bindings) { bindings_ = bindings; } void WebUI::SetFrameXPath(const std::string& xpath) { frame_xpath_ = xpath; } WebUIController* WebUI::GetController() const { return controller_.get(); } void WebUI::SetController(WebUIController* controller) { controller_.reset(controller); } void WebUI::CallJavascriptFunction(const std::string& function_name) { DCHECK(IsStringASCII(function_name)); string16 javascript = ASCIIToUTF16(function_name + "();"); ExecuteJavascript(javascript); } void WebUI::CallJavascriptFunction(const std::string& function_name, const Value& arg) { DCHECK(IsStringASCII(function_name)); std::vector<const Value*> args; args.push_back(&arg); ExecuteJavascript(WebUI::GetJavascriptCall(function_name, args)); } void WebUI::CallJavascriptFunction( const std::string& function_name, const Value& arg1, const Value& arg2) { DCHECK(IsStringASCII(function_name)); std::vector<const Value*> args; args.push_back(&arg1); args.push_back(&arg2); ExecuteJavascript(WebUI::GetJavascriptCall(function_name, args)); } void WebUI::CallJavascriptFunction( const std::string& function_name, const Value& arg1, const Value& arg2, const Value& arg3) { DCHECK(IsStringASCII(function_name)); std::vector<const Value*> args; args.push_back(&arg1); args.push_back(&arg2); args.push_back(&arg3); ExecuteJavascript(WebUI::GetJavascriptCall(function_name, args)); } void WebUI::CallJavascriptFunction( const std::string& function_name, const Value& arg1, const Value& arg2, const Value& arg3, const Value& arg4) { DCHECK(IsStringASCII(function_name)); std::vector<const Value*> args; args.push_back(&arg1); args.push_back(&arg2); args.push_back(&arg3); args.push_back(&arg4); ExecuteJavascript(WebUI::GetJavascriptCall(function_name, args)); } void WebUI::CallJavascriptFunction( const std::string& function_name, const std::vector<const Value*>& args) { DCHECK(IsStringASCII(function_name)); ExecuteJavascript(WebUI::GetJavascriptCall(function_name, args)); } void WebUI::RegisterMessageCallback(const std::string &message, const MessageCallback& callback) { std::pair<MessageCallbackMap::iterator, bool> result = message_callbacks_.insert(std::make_pair(message, callback)); // Overwrite preexisting message callback mappings. if (!result.second && register_callback_overwrites()) result.first->second = callback; } // WebUI, protected: ---------------------------------------------------------- void WebUI::AddMessageHandler(WebUIMessageHandler* handler) { DCHECK(!handler->web_ui()); handler->set_web_ui(this); handler->RegisterMessages(); handlers_.push_back(handler); } void WebUI::ExecuteJavascript(const string16& javascript) { web_contents_->GetRenderViewHost()->ExecuteJavascriptInWebFrame( ASCIIToUTF16(frame_xpath_), javascript); } <commit_msg>Fix uninitalized varible in WebUI. I was going to remove this out of WebUI, then reverted that change but forgot to initialize it again.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/webui/web_ui.h" #include "base/command_line.h" #include "base/json/json_writer.h" #include "base/stl_util.h" #include "base/utf_string_conversions.h" #include "base/values.h" #include "content/browser/child_process_security_policy.h" #include "content/browser/renderer_host/render_process_host_impl.h" #include "content/browser/renderer_host/render_view_host.h" #include "content/browser/tab_contents/tab_contents.h" #include "content/browser/tab_contents/tab_contents_view.h" #include "content/browser/webui/generic_handler.h" #include "content/common/view_messages.h" #include "content/public/browser/web_ui_controller.h" #include "content/public/common/bindings_policy.h" #include "content/public/common/content_switches.h" using content::WebContents; using content::WebUIController; using content::WebUIMessageHandler; // static string16 WebUI::GetJavascriptCall( const std::string& function_name, const std::vector<const Value*>& arg_list) { string16 parameters; std::string json; for (size_t i = 0; i < arg_list.size(); ++i) { if (i > 0) parameters += char16(','); base::JSONWriter::Write(arg_list[i], false, &json); parameters += UTF8ToUTF16(json); } return ASCIIToUTF16(function_name) + char16('(') + parameters + char16(')') + char16(';'); } WebUI::WebUI(WebContents* contents) : hide_favicon_(false), focus_location_bar_by_default_(false), should_hide_url_(false), link_transition_type_(content::PAGE_TRANSITION_LINK), bindings_(content::BINDINGS_POLICY_WEB_UI), register_callback_overwrites_(false), web_contents_(contents) { DCHECK(contents); AddMessageHandler(new GenericHandler()); } WebUI::~WebUI() { // Delete the controller first, since it may also be keeping a pointer to some // of the handlers and can call them at destruction. controller_.reset(); STLDeleteContainerPointers(handlers_.begin(), handlers_.end()); } // WebUI, public: ------------------------------------------------------------- const WebUI::TypeID WebUI::kNoWebUI = NULL; bool WebUI::OnMessageReceived(const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(WebUI, message) IPC_MESSAGE_HANDLER(ViewHostMsg_WebUISend, OnWebUISend) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } void WebUI::OnWebUISend(const GURL& source_url, const std::string& message, const ListValue& args) { if (!ChildProcessSecurityPolicy::GetInstance()-> HasWebUIBindings(web_contents_->GetRenderProcessHost()->GetID())) { NOTREACHED() << "Blocked unauthorized use of WebUIBindings."; return; } if (controller_->OverrideHandleWebUIMessage(source_url, message,args)) return; // Look up the callback for this message. MessageCallbackMap::const_iterator callback = message_callbacks_.find(message); if (callback != message_callbacks_.end()) { // Forward this message and content on. callback->second.Run(&args); } } void WebUI::RenderViewCreated(RenderViewHost* render_view_host) { controller_->RenderViewCreated(render_view_host); // Do not attempt to set the toolkit property if WebUI is not enabled, e.g., // the bookmarks manager page. if (!(bindings_ & content::BINDINGS_POLICY_WEB_UI)) return; #if defined(TOOLKIT_VIEWS) render_view_host->SetWebUIProperty("toolkit", "views"); #elif defined(TOOLKIT_GTK) render_view_host->SetWebUIProperty("toolkit", "GTK"); #endif // defined(TOOLKIT_VIEWS) // Let the WebUI know that we're looking for UI that's optimized for touch // input. // TODO(rbyers) Figure out the right model for enabling touch-optimized UI // (http://crbug.com/105380). if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kTouchOptimizedUI)) render_view_host->SetWebUIProperty("touchOptimized", "true"); } WebContents* WebUI::GetWebContents() const { return web_contents_; } bool WebUI::ShouldHideFavicon() const { return hide_favicon_; } void WebUI::HideFavicon() { hide_favicon_ = true; } bool WebUI::ShouldFocusLocationBarByDefault() const { return focus_location_bar_by_default_; } void WebUI::FocusLocationBarByDefault() { focus_location_bar_by_default_ = true; } bool WebUI::ShouldHideURL() const { return should_hide_url_; } void WebUI::HideURL() { should_hide_url_ = true; } const string16& WebUI::GetOverriddenTitle() const { return overridden_title_; } void WebUI::OverrideTitle(const string16& title) { overridden_title_ = title; } content::PageTransition WebUI::GetLinkTransitionType() const { return link_transition_type_; } void WebUI::SetLinkTransitionType(content::PageTransition type) { link_transition_type_ = type; } int WebUI::GetBindings() const { return bindings_; } void WebUI::SetBindings(int bindings) { bindings_ = bindings; } void WebUI::SetFrameXPath(const std::string& xpath) { frame_xpath_ = xpath; } WebUIController* WebUI::GetController() const { return controller_.get(); } void WebUI::SetController(WebUIController* controller) { controller_.reset(controller); } void WebUI::CallJavascriptFunction(const std::string& function_name) { DCHECK(IsStringASCII(function_name)); string16 javascript = ASCIIToUTF16(function_name + "();"); ExecuteJavascript(javascript); } void WebUI::CallJavascriptFunction(const std::string& function_name, const Value& arg) { DCHECK(IsStringASCII(function_name)); std::vector<const Value*> args; args.push_back(&arg); ExecuteJavascript(WebUI::GetJavascriptCall(function_name, args)); } void WebUI::CallJavascriptFunction( const std::string& function_name, const Value& arg1, const Value& arg2) { DCHECK(IsStringASCII(function_name)); std::vector<const Value*> args; args.push_back(&arg1); args.push_back(&arg2); ExecuteJavascript(WebUI::GetJavascriptCall(function_name, args)); } void WebUI::CallJavascriptFunction( const std::string& function_name, const Value& arg1, const Value& arg2, const Value& arg3) { DCHECK(IsStringASCII(function_name)); std::vector<const Value*> args; args.push_back(&arg1); args.push_back(&arg2); args.push_back(&arg3); ExecuteJavascript(WebUI::GetJavascriptCall(function_name, args)); } void WebUI::CallJavascriptFunction( const std::string& function_name, const Value& arg1, const Value& arg2, const Value& arg3, const Value& arg4) { DCHECK(IsStringASCII(function_name)); std::vector<const Value*> args; args.push_back(&arg1); args.push_back(&arg2); args.push_back(&arg3); args.push_back(&arg4); ExecuteJavascript(WebUI::GetJavascriptCall(function_name, args)); } void WebUI::CallJavascriptFunction( const std::string& function_name, const std::vector<const Value*>& args) { DCHECK(IsStringASCII(function_name)); ExecuteJavascript(WebUI::GetJavascriptCall(function_name, args)); } void WebUI::RegisterMessageCallback(const std::string &message, const MessageCallback& callback) { std::pair<MessageCallbackMap::iterator, bool> result = message_callbacks_.insert(std::make_pair(message, callback)); // Overwrite preexisting message callback mappings. if (!result.second && register_callback_overwrites()) result.first->second = callback; } // WebUI, protected: ---------------------------------------------------------- void WebUI::AddMessageHandler(WebUIMessageHandler* handler) { DCHECK(!handler->web_ui()); handler->set_web_ui(this); handler->RegisterMessages(); handlers_.push_back(handler); } void WebUI::ExecuteJavascript(const string16& javascript) { web_contents_->GetRenderViewHost()->ExecuteJavascriptInWebFrame( ASCIIToUTF16(frame_xpath_), javascript); } <|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. * ************************************************************************/ #ifndef _LAYOUT_POST_HXX #define _LAYOUT_POST_HXX #if ENABLE_LAYOUT /* Allow re-inclusion for cxx file. */ #undef _LAYOUT_PRE_HXX #undef AdvancedButton #undef ApplyButton #undef Box #undef Button #undef CancelButton #undef CheckBox #undef ComboBox #undef Container #undef Control #undef Dialog #undef Edit #undef ErrorBox #undef FixedImage #undef FixedInfo #undef FixedLine #undef FixedText #undef HBox #undef HelpButton #undef IgnoreButton #undef ImageButton #undef InfoBox #undef ListBox #undef MessBox #undef MessageBox #undef MetricField #undef MetricFormatter #undef MoreButton #undef MultiLineEdit #undef MultiListBox #undef NoButton #undef NumericField #undef NumericFormatter #undef OKButton #undef Plugin #undef ProgressBar #undef PushButton #undef QueryBox #undef RadioButton #undef ResetButton #undef RetryButton #undef SfxTabPage #undef SfxTabDialog #undef SfxTabPage #undef SvxFontListBox #undef SvxLanguageBox #undef SpinField #undef TabDialog #undef TabControl #undef TabPage #undef Table #undef VBox #undef WarningBox #undef YesButton #undef SvxFontListBox #undef SvxLanguageBox #undef ModalDialog #undef ModelessDialog #undef ScExpandedFixedText #undef SfxDialog #undef SfxModalDialog #undef SfxModelessDialog #undef Window #endif /* ENABLE_LAYOUT */ #endif /* _LAYOUT_POST_HXX */ /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>remove dups<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. * ************************************************************************/ #ifndef _LAYOUT_POST_HXX #define _LAYOUT_POST_HXX #if ENABLE_LAYOUT /* Allow re-inclusion for cxx file. */ #undef _LAYOUT_PRE_HXX #undef AdvancedButton #undef ApplyButton #undef Box #undef Button #undef CancelButton #undef CheckBox #undef ComboBox #undef Container #undef Control #undef Dialog #undef Edit #undef ErrorBox #undef FixedImage #undef FixedInfo #undef FixedLine #undef FixedText #undef HBox #undef HelpButton #undef IgnoreButton #undef ImageButton #undef InfoBox #undef ListBox #undef MessBox #undef MessageBox #undef MetricField #undef MetricFormatter #undef MoreButton #undef MultiLineEdit #undef MultiListBox #undef NoButton #undef NumericField #undef NumericFormatter #undef OKButton #undef Plugin #undef ProgressBar #undef PushButton #undef QueryBox #undef RadioButton #undef ResetButton #undef RetryButton #undef SfxTabDialog #undef SfxTabPage #undef SvxFontListBox #undef SvxLanguageBox #undef SpinField #undef TabDialog #undef TabControl #undef TabPage #undef Table #undef VBox #undef WarningBox #undef YesButton #undef SvxFontListBox #undef SvxLanguageBox #undef ModalDialog #undef ModelessDialog #undef ScExpandedFixedText #undef SfxDialog #undef SfxModalDialog #undef SfxModelessDialog #undef Window #endif /* ENABLE_LAYOUT */ #endif /* _LAYOUT_POST_HXX */ /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before><commit_msg>WaE: switch statement contains 'default' but no 'case' labels<commit_after><|endoftext|>
<commit_before><commit_msg>fix up code that checks a firmware version response<commit_after><|endoftext|>
<commit_before>//#define DEBUG // Allow debugging #include <os> #include <net/class_ip6.hpp> #include <net/ip6/icmp6.hpp> #include <net/ip6/udp6.hpp> #include <assert.h> namespace net { IP6::IP6(const IP6::addr& lo) // : local(lo) { int ttt; printf("IP6: stack: %p\n", &ttt); printf("IP6 constructor, addr = %s\n", lo.to_string().c_str()); assert(sizeof(addr) == 16); assert(sizeof(header) == 40); assert(sizeof(options_header) == 8); this->local = lo; } uint8_t IP6::parse6(uint8_t*& reader, uint8_t next) { switch (next) { case PROTO_HOPOPT: case PROTO_OPTSv6: { std::cout << ">>> IPv6 options header " << protocol_name(next) << std::endl; options_header& opts = *(options_header*) reader; reader += opts.size(); std::cout << "OPTSv6 size: " << opts.size() << std::endl; std::cout << "OPTSv6 ext size: " << opts.extended() << std::endl; next = opts.next(); std::cout << "OPTSv6 next: " << protocol_name(next) << std::endl; } break; case PROTO_ICMPv6: break; case PROTO_UDP: break; default: std::cout << "Not parsing " << protocol_name(next) << std::endl; } return next; } int IP6::bottom(std::shared_ptr<Packet>& pckt) { std::cout << ">>> IPv6 packet:" << std::endl; uint8_t* reader = pckt->buffer(); full_header& full = *(full_header*) reader; reader += sizeof(full_header); header& hdr = full.ip6_hdr; std::cout << "IPv6 v: " << hdr.version() << " \t"; std::cout << "class: " << hdr.tclass() << " \t"; std::cout << "size: " << hdr.size() << " bytes" << std::endl; uint8_t next = hdr.next(); std::cout << "IPv6 next hdr: " << protocol_name(next) << std::endl; std::cout << "IPv6 hoplimit: " << hdr.hoplimit() << " hops" << std::endl; std::cout << "IPv6 src: " << hdr.source() << std::endl; std::cout << "IPv6 dst: " << hdr.dest() << std::endl; while (next != PROTO_NoNext) { auto it = proto_handlers.find(next); if (it != proto_handlers.end()) { pckt->_payload = reader; return it->second(pckt); } else // just print information next = parse6(reader, next); } std::cout << std::endl; return 0; }; std::string IP6::addr::to_string() const { static const std::string lut = "0123456789abcdef"; std::string ret(40, 0); int counter = 0; const uint8_t* octet = i8; for (int i = 0; i < 16; i++) { ret[counter++] = lut[(octet[i] & 0xF0) >> 4]; ret[counter++] = lut[(octet[i] & 0x0F) >> 0]; if (i & 1) ret[counter++] = ':'; } ret.resize(counter-1); return ret; } } <commit_msg>Moved static outside of function<commit_after>//#define DEBUG // Allow debugging #include <os> #include <net/class_ip6.hpp> #include <net/ip6/icmp6.hpp> #include <net/ip6/udp6.hpp> #include <assert.h> namespace net { IP6::IP6(const IP6::addr& lo) // : local(lo) { int ttt; printf("IP6: stack: %p\n", &ttt); printf("IP6 constructor, addr = %s\n", lo.to_string().c_str()); assert(sizeof(addr) == 16); assert(sizeof(header) == 40); assert(sizeof(options_header) == 8); this->local = lo; } uint8_t IP6::parse6(uint8_t*& reader, uint8_t next) { switch (next) { case PROTO_HOPOPT: case PROTO_OPTSv6: { std::cout << ">>> IPv6 options header " << protocol_name(next) << std::endl; options_header& opts = *(options_header*) reader; reader += opts.size(); std::cout << "OPTSv6 size: " << opts.size() << std::endl; std::cout << "OPTSv6 ext size: " << opts.extended() << std::endl; next = opts.next(); std::cout << "OPTSv6 next: " << protocol_name(next) << std::endl; } break; case PROTO_ICMPv6: break; case PROTO_UDP: break; default: std::cout << "Not parsing " << protocol_name(next) << std::endl; } return next; } int IP6::bottom(std::shared_ptr<Packet>& pckt) { std::cout << ">>> IPv6 packet:" << std::endl; uint8_t* reader = pckt->buffer(); full_header& full = *(full_header*) reader; reader += sizeof(full_header); header& hdr = full.ip6_hdr; std::cout << "IPv6 v: " << hdr.version() << " \t"; std::cout << "class: " << hdr.tclass() << " \t"; std::cout << "size: " << hdr.size() << " bytes" << std::endl; uint8_t next = hdr.next(); std::cout << "IPv6 next hdr: " << protocol_name(next) << std::endl; std::cout << "IPv6 hoplimit: " << hdr.hoplimit() << " hops" << std::endl; std::cout << "IPv6 src: " << hdr.source() << std::endl; std::cout << "IPv6 dst: " << hdr.dest() << std::endl; while (next != PROTO_NoNext) { auto it = proto_handlers.find(next); if (it != proto_handlers.end()) { pckt->_payload = reader; return it->second(pckt); } else // just print information next = parse6(reader, next); } std::cout << std::endl; return 0; }; static const std::string lut = "0123456789abcdef"; std::string IP6::addr::to_string() const { std::string ret(40, 0); int counter = 0; const uint8_t* octet = i8; for (int i = 0; i < 16; i++) { ret[counter++] = lut[(octet[i] & 0xF0) >> 4]; ret[counter++] = lut[(octet[i] & 0x0F) >> 0]; if (i & 1) ret[counter++] = ':'; } ret.resize(counter-1); return ret; } } <|endoftext|>
<commit_before>/* * Copyright (C) DreamLab Onet.pl Sp. z o. o. * * 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 <v8.h> #include <node.h> #include <Uri.h> enum parseOptions { kProtocol = 1, kAuth = 1 << 1, kHost = 1 << 2, kPort = 1 << 3, kQuery = 1 << 4, kFragment = 1 << 5, kPath = 1 << 6, kAll = kProtocol | kAuth | kHost | kPort | kQuery | kFragment | kPath }; static v8::Persistent<v8::String> protocol_symbol = NODE_PSYMBOL("protocol"); static v8::Persistent<v8::String> auth_symbol = NODE_PSYMBOL("auth"); static v8::Persistent<v8::String> host_symbol = NODE_PSYMBOL("host"); static v8::Persistent<v8::String> port_symbol = NODE_PSYMBOL("port"); static v8::Persistent<v8::String> query_symbol = NODE_PSYMBOL("query"); static v8::Persistent<v8::String> fragment_symbol = NODE_PSYMBOL("fragment"); static v8::Persistent<v8::String> path_symbol = NODE_PSYMBOL("path"); static v8::Handle<v8::Value> parse(const v8::Arguments& args){ v8::HandleScope scope; parseOptions opts = kAll; if (args.Length() == 0 || !args[0]->IsString()) { v8::ThrowException(v8::Exception::TypeError(v8::String::New("First argument has to be string"))); } if (args[1]->IsNumber()) { opts = static_cast<parseOptions>(args[1]->Int32Value()); } v8::String::Utf8Value url (args[0]->ToString()); if (url.length() == 0) { v8::ThrowException(v8::Exception::TypeError(v8::String::New("String mustn't be empty"))); } UriParserStateA state; UriUriA uri; state.uri = &uri; if (uriParseUriA(&state, *url) != URI_SUCCESS) { return scope.Close(v8::Boolean::New(false)); } v8::PropertyAttribute attrib = (v8::PropertyAttribute) (v8::ReadOnly | v8::DontDelete); v8::Local<v8::Object> data = v8::Object::New(); if (uri.scheme.first && opts & kProtocol) { // +1 here because we need : after protocol data->Set(protocol_symbol, v8::String::New(uri.scheme.first, strlen(uri.scheme.first) - strlen(uri.scheme.afterLast) + 1), attrib); } if (uri.userInfo.first && opts & kAuth) { char *auth = (char*) uri.userInfo.first; const char *delim = ":"; auth[strlen(uri.userInfo.first) - strlen(uri.userInfo.afterLast)] = '\0'; v8::Local<v8::Object> authData = v8::Object::New(); authData->Set(v8::String::New("user"), v8::String::New(strtok(auth, delim))), attrib; authData->Set(v8::String::New("password"), v8::String::New(strtok(NULL, delim)), attrib); data->Set(auth_symbol, authData, attrib); } if (uri.hostText.first && opts & kHost) { int tmpLength = strlen(uri.hostText.first); data->Set(host_symbol, v8::String::New(uri.hostText.first, tmpLength - strlen(uri.hostText.afterLast)), attrib); } if (uri.portText.first && opts & kPort) { data->Set(port_symbol, v8::String::New(uri.portText.first, strlen(uri.portText.first) - strlen(uri.portText.afterLast)), attrib); } if (uri.query.first && opts & kQuery) { char *query = (char*) uri.query.first; query[strlen(uri.query.first) - strlen(uri.query.afterLast)] = '\0'; const char *amp = "&", *sum = "="; char *queryParamPtr, *queryParam = strtok_r(query, amp, &queryParamPtr), *queryParamKey, *queryParamValue; v8::Local<v8::Object> queryData = v8::Object::New(); while (queryParam) { queryParamKey = strtok(queryParam, sum); queryParamValue = strtok(NULL, sum); queryParam = strtok_r(NULL, amp, &queryParamPtr); queryData->Set(v8::String::New(queryParamKey), v8::String::New(queryParamValue ? queryParamValue : ""), attrib); } data->Set(query_symbol, queryData, attrib); //parsing the path will be easier query--; query[0] = '\0'; } if (uri.fragment.first && opts & kFragment) { data->Set(fragment_symbol, v8::String::New(uri.fragment.first, strlen(uri.fragment.first) - strlen(uri.fragment.afterLast)), attrib); } if (uri.pathHead && uri.pathHead->text.first && opts & kPath) { UriPathSegmentA pathHead = *uri.pathHead; char *path = (char*) pathHead.text.first; int position = strlen(pathHead.text.first); while (pathHead.next) { pathHead = *pathHead.next; } int tmpPosition = strlen(pathHead.text.afterLast); if ( (position - tmpPosition) == 0) { path = (char *) "/"; } if ((uri.absolutePath || uri.hostText.first) && strlen(path) > 1) { path--; } data->Set(path_symbol, v8::String::New(path), attrib); } else if (opts & kPath) { data->Set(path_symbol, v8::String::New("/"), attrib); } uriFreeUriMembersA(&uri); return scope.Close(data); } extern "C" void init (v8::Handle<v8::Object> target){ v8::HandleScope scope; NODE_SET_METHOD(target, "parse", parse); NODE_DEFINE_CONSTANT(target, kProtocol); NODE_DEFINE_CONSTANT(target, kAuth); NODE_DEFINE_CONSTANT(target, kHost); NODE_DEFINE_CONSTANT(target, kPort); NODE_DEFINE_CONSTANT(target, kQuery); NODE_DEFINE_CONSTANT(target, kFragment); NODE_DEFINE_CONSTANT(target, kPath); NODE_DEFINE_CONSTANT(target, kAll); } <commit_msg>Fixed an issue with the path.<commit_after>/* * Copyright (C) DreamLab Onet.pl Sp. z o. o. * * 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 <v8.h> #include <node.h> #include <Uri.h> enum parseOptions { kProtocol = 1, kAuth = 1 << 1, kHost = 1 << 2, kPort = 1 << 3, kQuery = 1 << 4, kFragment = 1 << 5, kPath = 1 << 6, kAll = kProtocol | kAuth | kHost | kPort | kQuery | kFragment | kPath }; static v8::Persistent<v8::String> protocol_symbol = NODE_PSYMBOL("protocol"); static v8::Persistent<v8::String> auth_symbol = NODE_PSYMBOL("auth"); static v8::Persistent<v8::String> host_symbol = NODE_PSYMBOL("host"); static v8::Persistent<v8::String> port_symbol = NODE_PSYMBOL("port"); static v8::Persistent<v8::String> query_symbol = NODE_PSYMBOL("query"); static v8::Persistent<v8::String> fragment_symbol = NODE_PSYMBOL("fragment"); static v8::Persistent<v8::String> path_symbol = NODE_PSYMBOL("path"); static v8::Handle<v8::Value> parse(const v8::Arguments& args){ v8::HandleScope scope; parseOptions opts = kAll; if (args.Length() == 0 || !args[0]->IsString()) { v8::ThrowException(v8::Exception::TypeError(v8::String::New("First argument has to be string"))); } if (args[1]->IsNumber()) { opts = static_cast<parseOptions>(args[1]->Int32Value()); } v8::String::Utf8Value url (args[0]->ToString()); if (url.length() == 0) { v8::ThrowException(v8::Exception::TypeError(v8::String::New("String mustn't be empty"))); } UriParserStateA state; UriUriA uri; state.uri = &uri; if (uriParseUriA(&state, *url) != URI_SUCCESS) { return scope.Close(v8::Boolean::New(false)); } v8::PropertyAttribute attrib = (v8::PropertyAttribute) (v8::ReadOnly | v8::DontDelete); v8::Local<v8::Object> data = v8::Object::New(); if (uri.scheme.first && opts & kProtocol) { // +1 here because we need : after protocol data->Set(protocol_symbol, v8::String::New(uri.scheme.first, strlen(uri.scheme.first) - strlen(uri.scheme.afterLast) + 1), attrib); } if (uri.userInfo.first && opts & kAuth) { char *auth = (char *) uri.userInfo.first; const char *delim = ":"; auth[strlen(uri.userInfo.first) - strlen(uri.userInfo.afterLast)] = '\0'; v8::Local<v8::Object> authData = v8::Object::New(); authData->Set(v8::String::New("user"), v8::String::New(strtok(auth, delim))), attrib; authData->Set(v8::String::New("password"), v8::String::New(strtok(NULL, delim)), attrib); data->Set(auth_symbol, authData, attrib); } if (uri.hostText.first && opts & kHost) { int tmpLength = strlen(uri.hostText.first); data->Set(host_symbol, v8::String::New(uri.hostText.first, tmpLength - strlen(uri.hostText.afterLast)), attrib); } if (uri.portText.first && opts & kPort) { data->Set(port_symbol, v8::String::New(uri.portText.first, strlen(uri.portText.first) - strlen(uri.portText.afterLast)), attrib); } if (uri.query.first && opts & kQuery) { char *query = (char *) uri.query.first; query[strlen(uri.query.first) - strlen(uri.query.afterLast)] = '\0'; const char *amp = "&", *sum = "="; char *queryParamPtr, *queryParam = strtok_r(query, amp, &queryParamPtr), *queryParamKey, *queryParamValue; v8::Local<v8::Object> queryData = v8::Object::New(); while (queryParam) { queryParamKey = strtok(queryParam, sum); queryParamValue = strtok(NULL, sum); queryParam = strtok_r(NULL, amp, &queryParamPtr); queryData->Set(v8::String::New(queryParamKey), v8::String::New(queryParamValue ? queryParamValue : ""), attrib); } data->Set(query_symbol, queryData, attrib); //parsing the path will be easier query--; query[0] = '\0'; } if (uri.fragment.first && opts & kFragment) { data->Set(fragment_symbol, v8::String::New(uri.fragment.first, strlen(uri.fragment.first) - strlen(uri.fragment.afterLast)), attrib); } if (uri.pathHead && uri.pathHead->text.first && opts & kPath) { UriPathSegmentA pathHead = *uri.pathHead; char *path = (char *) pathHead.text.first; int position = strlen(pathHead.text.first); while (pathHead.next) { pathHead = *pathHead.next; } int tmpPosition = strlen(pathHead.text.afterLast); if ((position - tmpPosition) == 0) { path = (char *) "/"; } if ((uri.absolutePath || uri.hostText.first) && strlen(path) >= 1) { char *isNull = path; if(*(--isNull)) { path--; } } data->Set(path_symbol, v8::String::New(path), attrib); } else if (opts & kPath) { data->Set(path_symbol, v8::String::New("/"), attrib); } uriFreeUriMembersA(&uri); return scope.Close(data); } extern "C" void init (v8::Handle<v8::Object> target){ v8::HandleScope scope; NODE_SET_METHOD(target, "parse", parse); NODE_DEFINE_CONSTANT(target, kProtocol); NODE_DEFINE_CONSTANT(target, kAuth); NODE_DEFINE_CONSTANT(target, kHost); NODE_DEFINE_CONSTANT(target, kPort); NODE_DEFINE_CONSTANT(target, kQuery); NODE_DEFINE_CONSTANT(target, kFragment); NODE_DEFINE_CONSTANT(target, kPath); NODE_DEFINE_CONSTANT(target, kAll); } <|endoftext|>
<commit_before>/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab: * * Test memcached_result_st * * Copyright (C) 2013 Data Differential, http://datadifferential.com/ * * 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. * * * The names of its contributors may not 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. * */ /* Test that we are cycling the servers we are creating during testing. */ #include "gear_config.h" #include <libtest/test.hpp> using namespace libtest; #include "libgearman/result.hpp" #include "libgearman/assert.hpp" #include "libgearman-1.0/visibility.h" #include "libgearman-1.0/result.h" #include <memory> static test_return_t declare_result_TEST(void*) { gearman_result_st result; ASSERT_EQ(0, result.size()); ASSERT_EQ(0, result.capacity()); return TEST_SUCCESS; } static test_return_t new_result_TEST(void*) { gearman_result_st* result= new gearman_result_st; ASSERT_EQ(0, result->size()); ASSERT_EQ(0, result->capacity()); delete result; return TEST_SUCCESS; } static test_return_t declare_result_size_TEST(void*) { gearman_result_st result(2048); ASSERT_EQ(0, result.size()); ASSERT_TRUE(result.capacity() >= 2048); return TEST_SUCCESS; } static test_return_t new_result_size_TEST(void*) { gearman_result_st* result= new gearman_result_st(2023); ASSERT_EQ(0, result->size()); ASSERT_TRUE(result->capacity() >= 2023); delete result; return TEST_SUCCESS; } static test_return_t zero_resize_TEST(void*) { gearman_result_st result(89); ASSERT_EQ(0, result.size()); ASSERT_TRUE(result.capacity() >= 89); result.resize(0); ASSERT_EQ(0, result.size()); ASSERT_EQ(0, result.capacity()); return TEST_SUCCESS; } static test_return_t smaller_resize_TEST(void*) { gearman_result_st result(89); ASSERT_EQ(0, result.size()); ASSERT_TRUE(result.capacity() >= 89); result.resize(20); ASSERT_EQ(0, result.size()); ASSERT_TRUE(result.capacity() >= 20); return TEST_SUCCESS; } static test_return_t bigger_resize_TEST(void*) { gearman_result_st result(89); ASSERT_EQ(0, result.size()); ASSERT_TRUE(result.capacity() >= 89); result.resize(181); ASSERT_EQ(0, result.size()); ASSERT_TRUE(result.capacity() >= 181); return TEST_SUCCESS; } static test_return_t random_resize_TEST(void*) { const size_t max_block= 10 * GEARMAN_VECTOR_BLOCK_SIZE; for (size_t x= 0; x < 20; x++) { gearman_result_st result(random() % max_block); ASSERT_TRUE(result.capacity() >= result.size()); result.resize(random() % max_block); ASSERT_TRUE(result.capacity() >= result.size()); result.resize(random() % max_block +GEARMAN_VECTOR_BLOCK_SIZE); ASSERT_TRUE(result.capacity() >= result.size()); } return TEST_SUCCESS; } static test_return_t append_TEST(void*) { const size_t max_block= 10 * GEARMAN_VECTOR_BLOCK_SIZE; for (size_t x= 0; x < 20; x++) { gearman_result_st result(random() % max_block); libtest::vchar_t random_string; libtest::vchar::make(random_string, random() % max_block); result.append(&random_string[0], random_string.size()); if (random() % 2) { result.clear(); } } return TEST_SUCCESS; } static test_return_t gearman_string_take_TEST(void*) { const size_t max_block= 10 * GEARMAN_VECTOR_BLOCK_SIZE; for (size_t x= 0; x < 20; x++) { gearman_result_st result((random() % max_block) +1); // Now we insert a random string libtest::vchar_t random_string; libtest::vchar::make(random_string, random() % max_block); result.append(&random_string[0], random_string.size()); gearman_string_t temp= gearman_result_take_string(&result); ASSERT_TRUE(gearman_c_str(temp)); free((void*)(gearman_c_str(temp))); } return TEST_SUCCESS; } static test_return_t gearman_string_allocate_take_TEST(void*) { const size_t max_block= 10 * GEARMAN_VECTOR_BLOCK_SIZE; for (size_t x= 0; x < 20; x++) { gearman_result_st* result= new gearman_result_st((random() % max_block) +1); { // Now we insert a random string libtest::vchar_t random_string; libtest::vchar::make(random_string, random() % max_block); result->append(&random_string[0], random_string.size() +1); } gearman_string_t temp= gearman_result_take_string(result); ASSERT_TRUE(gearman_c_str(temp)); free((void*)(gearman_c_str(temp))); if (random() % 2) { // Now we insert a random string libtest::vchar_t random_string; libtest::vchar::make(random_string, random() % max_block); result->append(&random_string[0], random_string.size()); } delete result; } return TEST_SUCCESS; } static test_return_t gearman_result_integer_TEST(void*) { gearman_result_st result; ASSERT_TRUE(result.store(8976)); ASSERT_EQ(0, gearman_result_integer(NULL)); ASSERT_EQ(8976, gearman_result_integer(&result)); return TEST_SUCCESS; } static test_return_t gearman_result_boolean_TEST(void*) { gearman_result_st result; ASSERT_TRUE(result.is_type(GEARMAN_RESULT_NULL)); ASSERT_EQ(false, gearman_result_boolean(NULL)); ASSERT_TRUE(result.boolean(true)); ASSERT_EQ(true, gearman_result_boolean(&result)); ASSERT_TRUE(result.is_type(GEARMAN_RESULT_BOOLEAN)); ASSERT_TRUE(result.boolean(false)); ASSERT_EQ(false, gearman_result_boolean(&result)); ASSERT_TRUE(result.is_type(GEARMAN_RESULT_BOOLEAN)); gearman_result_st result_false; ASSERT_TRUE(result_false.boolean(false)); ASSERT_EQ(false, gearman_result_boolean(&result_false)); ASSERT_TRUE(result.is_type(GEARMAN_RESULT_BOOLEAN)); return TEST_SUCCESS; } static test_return_t gearman_result_string_TEST(void*) { gearman_string_t value= { test_literal_param("This is my echo test") }; gearman_result_st result; ASSERT_EQ(GEARMAN_SUCCESS, gearman_result_store_string(&result, value)); gearman_string_t ret_value= gearman_result_string(&result); ASSERT_EQ(test_literal_param_size(value), test_literal_param_size(ret_value)); ASSERT_EQ(GEARMAN_INVALID_ARGUMENT, gearman_result_store_string(NULL, value)); return TEST_SUCCESS; } static test_return_t gearman_result_store_string_TEST(void*) { gearman_string_t value= { test_literal_param("This is my echo test") }; ASSERT_EQ(GEARMAN_INVALID_ARGUMENT, gearman_result_store_string(NULL, value)); gearman_result_st result; ASSERT_EQ(GEARMAN_SUCCESS, gearman_result_store_string(&result, value)); return TEST_SUCCESS; } static test_return_t gearman_result_store_integer_TEST(void*) { const int64_t value= __LINE__; gearman_result_st result; gearman_result_store_integer(&result, value); return TEST_SUCCESS; } static test_return_t gearman_result_store_value_TEST(void*) { ASSERT_EQ(GEARMAN_INVALID_ARGUMENT, gearman_result_store_value(NULL, NULL, 0)); gearman_result_st result; ASSERT_EQ(GEARMAN_SUCCESS, gearman_result_store_value(&result, test_literal_param(__func__))); return TEST_SUCCESS; } static test_return_t gearman_result_size_TEST(void*) { gearman_result_st result; ASSERT_EQ(GEARMAN_SUCCESS, gearman_result_store_value(&result, test_literal_param(__func__))); ASSERT_EQ(strlen(__func__), gearman_result_size(&result)); ASSERT_EQ(0, gearman_result_size(NULL)); return TEST_SUCCESS; } static test_return_t gearman_result_value_TEST(void*) { gearman_result_st result; ASSERT_EQ(GEARMAN_SUCCESS, gearman_result_store_value(&result, test_literal_param(__func__))); ASSERT_EQ(GEARMAN_INVALID_ARGUMENT, gearman_result_store_value(NULL, test_literal_param(__func__))); return TEST_SUCCESS; } static test_return_t gearman_result_is_null_TEST(void*) { gearman_result_st result; ASSERT_TRUE(gearman_result_is_null(&result)); ASSERT_TRUE(gearman_result_is_null(NULL)); return TEST_SUCCESS; } test_st allocate_TESTS[] ={ { "declare result", 0, declare_result_TEST }, { "new result", 0, new_result_TEST }, { "declare result(2048)", 0, declare_result_size_TEST }, { "new result(2023)", 0, new_result_size_TEST }, { 0, 0, 0 } }; test_st resize_TESTS[] ={ { "zero", 0, zero_resize_TEST }, { "smaller", 0, smaller_resize_TEST }, { "bigger", 0, bigger_resize_TEST }, { "random", 0, random_resize_TEST }, { 0, 0, 0 } }; test_st append_TESTS[] ={ { "append()", 0, append_TEST }, { 0, 0, 0 } }; test_st take_TESTS[] ={ { "gearman_string_take_string()", 0, gearman_string_take_TEST }, { "new gearman_result_st() gearman_string_take_string()", 0, gearman_string_allocate_take_TEST }, { 0, 0, 0 } }; test_st API_TESTS[] ={ { "gearman_result_integer()", 0, gearman_result_integer_TEST }, { "gearman_result_boolean()", 0, gearman_result_boolean_TEST }, { "gearman_result_string()", 0, gearman_result_string_TEST }, { "gearman_result_store_string()", 0, gearman_result_store_string_TEST }, { "gearman_result_store_integer()", 0, gearman_result_store_integer_TEST }, { "gearman_result_store_value()", 0, gearman_result_store_value_TEST }, { "gearman_result_size()", 0, gearman_result_size_TEST }, { "gearman_result_value()", 0, gearman_result_value_TEST }, { "gearman_result_is_null()", 0, gearman_result_is_null_TEST }, { 0, 0, 0 } }; collection_st collection[] ={ {"allocate", NULL, NULL, allocate_TESTS }, {"resize", NULL, NULL, resize_TESTS }, {"append", NULL, NULL, append_TESTS }, {"take", NULL, NULL, take_TESTS }, {"API", NULL, NULL, API_TESTS }, {0, 0, 0, 0} }; void get_world(libtest::Framework *world) { world->collections(collection); } <commit_msg>Make sure we always have at least one byte stored in this test.<commit_after>/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab: * * Test memcached_result_st * * Copyright (C) 2013 Data Differential, http://datadifferential.com/ * * 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. * * * The names of its contributors may not 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. * */ /* Test that we are cycling the servers we are creating during testing. */ #include "gear_config.h" #include <libtest/test.hpp> using namespace libtest; #include "libgearman/result.hpp" #include "libgearman/assert.hpp" #include "libgearman-1.0/visibility.h" #include "libgearman-1.0/result.h" #include <memory> static test_return_t declare_result_TEST(void*) { gearman_result_st result; ASSERT_EQ(0, result.size()); ASSERT_EQ(0, result.capacity()); return TEST_SUCCESS; } static test_return_t new_result_TEST(void*) { gearman_result_st* result= new gearman_result_st; ASSERT_EQ(0, result->size()); ASSERT_EQ(0, result->capacity()); delete result; return TEST_SUCCESS; } static test_return_t declare_result_size_TEST(void*) { gearman_result_st result(2048); ASSERT_EQ(0, result.size()); ASSERT_TRUE(result.capacity() >= 2048); return TEST_SUCCESS; } static test_return_t new_result_size_TEST(void*) { gearman_result_st* result= new gearman_result_st(2023); ASSERT_EQ(0, result->size()); ASSERT_TRUE(result->capacity() >= 2023); delete result; return TEST_SUCCESS; } static test_return_t zero_resize_TEST(void*) { gearman_result_st result(89); ASSERT_EQ(0, result.size()); ASSERT_TRUE(result.capacity() >= 89); result.resize(0); ASSERT_EQ(0, result.size()); ASSERT_EQ(0, result.capacity()); return TEST_SUCCESS; } static test_return_t smaller_resize_TEST(void*) { gearman_result_st result(89); ASSERT_EQ(0, result.size()); ASSERT_TRUE(result.capacity() >= 89); result.resize(20); ASSERT_EQ(0, result.size()); ASSERT_TRUE(result.capacity() >= 20); return TEST_SUCCESS; } static test_return_t bigger_resize_TEST(void*) { gearman_result_st result(89); ASSERT_EQ(0, result.size()); ASSERT_TRUE(result.capacity() >= 89); result.resize(181); ASSERT_EQ(0, result.size()); ASSERT_TRUE(result.capacity() >= 181); return TEST_SUCCESS; } static test_return_t random_resize_TEST(void*) { const size_t max_block= 10 * GEARMAN_VECTOR_BLOCK_SIZE; for (size_t x= 0; x < 20; x++) { gearman_result_st result(random() % max_block); ASSERT_TRUE(result.capacity() >= result.size()); result.resize(random() % max_block); ASSERT_TRUE(result.capacity() >= result.size()); result.resize(random() % max_block +GEARMAN_VECTOR_BLOCK_SIZE); ASSERT_TRUE(result.capacity() >= result.size()); } return TEST_SUCCESS; } static test_return_t append_TEST(void*) { const size_t max_block= 10 * GEARMAN_VECTOR_BLOCK_SIZE; for (size_t x= 0; x < 20; x++) { gearman_result_st result(random() % max_block); libtest::vchar_t random_string; libtest::vchar::make(random_string, (random() % max_block) +1); result.append(&random_string[0], random_string.size()); if (random() % 2) { result.clear(); } } return TEST_SUCCESS; } static test_return_t gearman_string_take_TEST(void*) { const size_t max_block= 10 * GEARMAN_VECTOR_BLOCK_SIZE; for (size_t x= 0; x < 20; x++) { gearman_result_st result((random() % max_block) +1); // Now we insert a random string libtest::vchar_t random_string; libtest::vchar::make(random_string, (random() % max_block) +1); result.append(&random_string[0], random_string.size()); gearman_string_t temp= gearman_result_take_string(&result); ASSERT_TRUE(gearman_c_str(temp)); free((void*)(gearman_c_str(temp))); } return TEST_SUCCESS; } static test_return_t gearman_string_allocate_take_TEST(void*) { const size_t max_block= 10 * GEARMAN_VECTOR_BLOCK_SIZE; for (size_t x= 0; x < 20; x++) { gearman_result_st* result= new gearman_result_st((random() % max_block) +1); { // Now we insert a random string libtest::vchar_t random_string; libtest::vchar::make(random_string, (random() % max_block) +1); result->append(&random_string[0], random_string.size()); } gearman_string_t temp= gearman_result_take_string(result); ASSERT_TRUE(gearman_c_str(temp)); free((void*)(gearman_c_str(temp))); if (random() % 2) { // Now we insert a random string libtest::vchar_t random_string; libtest::vchar::make(random_string, (random() % max_block) +1); result->append(&random_string[0], random_string.size()); } delete result; } return TEST_SUCCESS; } static test_return_t gearman_result_integer_TEST(void*) { gearman_result_st result; ASSERT_TRUE(result.store(8976)); ASSERT_EQ(0, gearman_result_integer(NULL)); ASSERT_EQ(8976, gearman_result_integer(&result)); return TEST_SUCCESS; } static test_return_t gearman_result_boolean_TEST(void*) { gearman_result_st result; ASSERT_TRUE(result.is_type(GEARMAN_RESULT_NULL)); ASSERT_EQ(false, gearman_result_boolean(NULL)); ASSERT_TRUE(result.boolean(true)); ASSERT_EQ(true, gearman_result_boolean(&result)); ASSERT_TRUE(result.is_type(GEARMAN_RESULT_BOOLEAN)); ASSERT_TRUE(result.boolean(false)); ASSERT_EQ(false, gearman_result_boolean(&result)); ASSERT_TRUE(result.is_type(GEARMAN_RESULT_BOOLEAN)); gearman_result_st result_false; ASSERT_TRUE(result_false.boolean(false)); ASSERT_EQ(false, gearman_result_boolean(&result_false)); ASSERT_TRUE(result.is_type(GEARMAN_RESULT_BOOLEAN)); return TEST_SUCCESS; } static test_return_t gearman_result_string_TEST(void*) { gearman_string_t value= { test_literal_param("This is my echo test") }; gearman_result_st result; ASSERT_EQ(GEARMAN_SUCCESS, gearman_result_store_string(&result, value)); gearman_string_t ret_value= gearman_result_string(&result); ASSERT_EQ(test_literal_param_size(value), test_literal_param_size(ret_value)); ASSERT_EQ(GEARMAN_INVALID_ARGUMENT, gearman_result_store_string(NULL, value)); return TEST_SUCCESS; } static test_return_t gearman_result_store_string_TEST(void*) { gearman_string_t value= { test_literal_param("This is my echo test") }; ASSERT_EQ(GEARMAN_INVALID_ARGUMENT, gearman_result_store_string(NULL, value)); gearman_result_st result; ASSERT_EQ(GEARMAN_SUCCESS, gearman_result_store_string(&result, value)); return TEST_SUCCESS; } static test_return_t gearman_result_store_integer_TEST(void*) { const int64_t value= __LINE__; gearman_result_st result; gearman_result_store_integer(&result, value); return TEST_SUCCESS; } static test_return_t gearman_result_store_value_TEST(void*) { ASSERT_EQ(GEARMAN_INVALID_ARGUMENT, gearman_result_store_value(NULL, NULL, 0)); gearman_result_st result; ASSERT_EQ(GEARMAN_SUCCESS, gearman_result_store_value(&result, test_literal_param(__func__))); return TEST_SUCCESS; } static test_return_t gearman_result_size_TEST(void*) { gearman_result_st result; ASSERT_EQ(GEARMAN_SUCCESS, gearman_result_store_value(&result, test_literal_param(__func__))); ASSERT_EQ(strlen(__func__), gearman_result_size(&result)); ASSERT_EQ(0, gearman_result_size(NULL)); return TEST_SUCCESS; } static test_return_t gearman_result_value_TEST(void*) { gearman_result_st result; ASSERT_EQ(GEARMAN_SUCCESS, gearman_result_store_value(&result, test_literal_param(__func__))); ASSERT_EQ(GEARMAN_INVALID_ARGUMENT, gearman_result_store_value(NULL, test_literal_param(__func__))); return TEST_SUCCESS; } static test_return_t gearman_result_is_null_TEST(void*) { gearman_result_st result; ASSERT_TRUE(gearman_result_is_null(&result)); ASSERT_TRUE(gearman_result_is_null(NULL)); return TEST_SUCCESS; } test_st allocate_TESTS[] ={ { "declare result", 0, declare_result_TEST }, { "new result", 0, new_result_TEST }, { "declare result(2048)", 0, declare_result_size_TEST }, { "new result(2023)", 0, new_result_size_TEST }, { 0, 0, 0 } }; test_st resize_TESTS[] ={ { "zero", 0, zero_resize_TEST }, { "smaller", 0, smaller_resize_TEST }, { "bigger", 0, bigger_resize_TEST }, { "random", 0, random_resize_TEST }, { 0, 0, 0 } }; test_st append_TESTS[] ={ { "append()", 0, append_TEST }, { 0, 0, 0 } }; test_st take_TESTS[] ={ { "gearman_string_take_string()", 0, gearman_string_take_TEST }, { "new gearman_result_st() gearman_string_take_string()", 0, gearman_string_allocate_take_TEST }, { 0, 0, 0 } }; test_st API_TESTS[] ={ { "gearman_result_integer()", 0, gearman_result_integer_TEST }, { "gearman_result_boolean()", 0, gearman_result_boolean_TEST }, { "gearman_result_string()", 0, gearman_result_string_TEST }, { "gearman_result_store_string()", 0, gearman_result_store_string_TEST }, { "gearman_result_store_integer()", 0, gearman_result_store_integer_TEST }, { "gearman_result_store_value()", 0, gearman_result_store_value_TEST }, { "gearman_result_size()", 0, gearman_result_size_TEST }, { "gearman_result_value()", 0, gearman_result_value_TEST }, { "gearman_result_is_null()", 0, gearman_result_is_null_TEST }, { 0, 0, 0 } }; collection_st collection[] ={ {"allocate", NULL, NULL, allocate_TESTS }, {"resize", NULL, NULL, resize_TESTS }, {"append", NULL, NULL, append_TESTS }, {"take", NULL, NULL, take_TESTS }, {"API", NULL, NULL, API_TESTS }, {0, 0, 0, 0} }; void get_world(libtest::Framework *world) { world->collections(collection); } <|endoftext|>
<commit_before>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2014, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ /* Author: Arjun Menon */ #include <ros/ros.h> #include <moveit/move_group_interface/move_group.h> #include <moveit/warehouse/planning_scene_storage.h> #include <boost/program_options.hpp> #include <boost/filesystem.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <view_controller_msgs/CameraPlacement.h> #include "moveit_recorder/trajectory_retimer.h" #include "moveit_recorder/animation_recorder.h" #include <rosbag/bag.h> #include <rosbag/query.h> #include <rosbag/view.h> #include <algorithm> int main(int argc, char** argv) { ros::init(argc, argv, "playback"); ros::NodeHandle node_handle; ros::AsyncSpinner spinner(1); spinner.start(); sleep(20); // to let RVIZ come up boost::program_options::options_description desc; desc.add_options() ("help", "Show help message") ("host", boost::program_options::value<std::string>(), "Host for the MongoDB.") ("port", boost::program_options::value<std::size_t>(), "Port for the MongoDB.") ("views",boost::program_options::value<std::string>(), "Bag file for viewpoints") ("save_dir",boost::program_options::value<std::string>(), "Directory for saving videos"); boost::program_options::variables_map vm; boost::program_options::parsed_options po = boost::program_options::parse_command_line(argc, argv, desc); boost::program_options::store(po, vm); boost::program_options::notify(vm); if (vm.count("help") || argc == 1) // show help if no parameters passed { std::cout << desc << std::endl; return 1; } try { //connect to the DB std::string host = vm.count("host") ? vm["host"].as<std::string>() : ""; size_t port = vm.count("port") ? vm["port"].as<std::size_t>() : 0; moveit_warehouse::PlanningSceneStorage pss(host, port); ROS_INFO("Connected to Warehouse DB at host (%s) and port (%d)", host.c_str(), (int)port); // set up the storage directory boost::filesystem::path storage_dir( vm.count("save_dir") ? vm["save_dir"].as<std::string>() : "/tmp" ); boost::filesystem::create_directories( storage_dir ); // create bag file to track the associated video to the scene, query, and traj that spawned it boost::filesystem::path bagpath = storage_dir / "video_lookup.bag"; rosbag::Bag bag(bagpath.string(), rosbag::bagmode::Write); bag.close(); // load the viewpoints std::string bagfilename = vm.count("views") ? vm["views"].as<std::string>() : ""; std::vector<view_controller_msgs::CameraPlacement> views; rosbag::Bag viewbag; viewbag.open(bagfilename, rosbag::bagmode::Read); std::vector<std::string> topics; topics.push_back("viewpoints"); rosbag::View view_t(viewbag, rosbag::TopicQuery(topics)); BOOST_FOREACH(rosbag::MessageInstance const m, view_t) { view_controller_msgs::CameraPlacement::ConstPtr i = m.instantiate<view_controller_msgs::CameraPlacement>(); if (i != NULL) views.push_back(*i); } viewbag.close(); ROS_INFO("%d views loaded",(int)views.size()); //TODO change these to params AnimationRecorder recorder( "/rviz/camera_placement", "planning_scene", "/move_group/display_planned_path", "animation_status", "animation_response", node_handle); // ask the warehouse for the scenes std::vector<std::string> ps_names; pss.getPlanningSceneNames( ps_names ); ROS_INFO("%d available scenes to display", (int)ps_names.size()); // iterate over scenes std::vector<std::string>::iterator scene_name = ps_names.begin(); for(; scene_name!=ps_names.end(); ++scene_name) { ROS_INFO("Retrieving scene %s", scene_name->c_str()); moveit_warehouse::PlanningSceneWithMetadata pswm; pss.getPlanningScene(pswm, *scene_name); moveit_msgs::PlanningScene ps_msg = static_cast<const moveit_msgs::PlanningScene&>(*pswm); // ask qarehosue for the queries std::vector<std::string> pq_names; pss.getPlanningQueriesNames( pq_names, *scene_name); ROS_INFO("%d available queries to display", (int)pq_names.size()); // iterate over the queries std::vector<std::string>::iterator query_name = pq_names.begin(); for(; query_name!=pq_names.end(); ++query_name) { ROS_INFO("Retrieving query %s", query_name->c_str()); moveit_warehouse::MotionPlanRequestWithMetadata mprwm; pss.getPlanningQuery(mprwm, *scene_name, *query_name); moveit_msgs::MotionPlanRequest mpr_msg = static_cast<const moveit_msgs::MotionPlanRequest&>(*mprwm); // ask warehouse for stored trajectories std::vector<moveit_warehouse::RobotTrajectoryWithMetadata> planning_results; pss.getPlanningResults(planning_results, *scene_name, *query_name); ROS_INFO("Loaded %d trajectories", (int)planning_results.size()); // animate each trajectory std::vector<moveit_warehouse::RobotTrajectoryWithMetadata>::iterator traj_w_mdata = planning_results.begin(); for(; traj_w_mdata!=planning_results.end(); ++traj_w_mdata) { moveit_msgs::RobotTrajectory rt_msg; rt_msg = static_cast<const moveit_msgs::RobotTrajectory&>(**traj_w_mdata); // retime it TrajectoryRetimer retimer( "robot_description", mpr_msg.group_name ); retimer.configure(ps_msg, mpr_msg); bool result = retimer.retime(rt_msg); ROS_INFO("Retiming success? %s", result? "yes" : "no" ); //date and time based filename boost::posix_time::ptime now = boost::posix_time::second_clock::local_time(); std::string vid_filename = boost::posix_time::to_simple_string(now); // fix filename std::replace(vid_filename.begin(), vid_filename.end(), '-','_'); std::replace(vid_filename.begin(), vid_filename.end(), ' ','_'); std::replace(vid_filename.begin(), vid_filename.end(), ':','_'); boost::filesystem::path filename( vid_filename ); boost::filesystem::path filepath = storage_dir / filename; // save into lookup rosbag::Bag bag(bagpath.string(), rosbag::bagmode::Append); bag.write(filepath.string(), ros::Time::now(), ps_msg); bag.write(filepath.string(), ros::Time::now(), mpr_msg); bag.write(filepath.string(), ros::Time::now(), rt_msg); int view_counter=0; std::vector<view_controller_msgs::CameraPlacement>::iterator view_msg; for(view_msg=views.begin(); view_msg!=views.end(); ++view_msg) { AnimationRequest req; view_msg->time_from_start = ros::Duration(0.1); ros::Time t_now = ros::Time::now(); view_msg->eye.header.stamp = t_now; view_msg->focus.header.stamp = t_now; view_msg->up.header.stamp = t_now; req.camera_placement = *view_msg; req.planning_scene = ps_msg; req.motion_plan_request = mpr_msg; req.robot_trajectory = rt_msg; // same filename, counter for viewpoint std::string ext = boost::lexical_cast<std::string>(view_counter++) + ".ogv"; std_msgs::String filemsg; filemsg.data = req.filepath; bag.write(filepath.string(), ros::Time::now(), filemsg); std::string video_file = filepath.string()+ext; req.filepath = video_file; recorder.record(req); recorder.startCapture(); ROS_INFO("RECORDING DONE!"); }//view bag.close(); }//traj }//query }//scene } catch(mongo_ros::DbConnectException &ex) { ROS_ERROR_STREAM("Unable to connect to warehouse. If you just created the database, it could take a while for initial setup. Please try to run the benchmark again." << std::endl << ex.what()); } ROS_INFO("Successfully performed trajectory playback"); ros::shutdown(); return 0; } <commit_msg>added program option for animation recorder topics<commit_after>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2014, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ /* Author: Arjun Menon */ #include <ros/ros.h> #include <moveit/move_group_interface/move_group.h> #include <moveit/warehouse/planning_scene_storage.h> #include <boost/program_options.hpp> #include <boost/filesystem.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <view_controller_msgs/CameraPlacement.h> #include "moveit_recorder/trajectory_retimer.h" #include "moveit_recorder/animation_recorder.h" #include "moveit_recorder/utils.h" #include <rosbag/bag.h> #include <rosbag/query.h> #include <rosbag/view.h> #include <algorithm> int main(int argc, char** argv) { ros::init(argc, argv, "playback"); ros::NodeHandle node_handle; ros::AsyncSpinner spinner(1); spinner.start(); sleep(20); // to let RVIZ come up boost::program_options::options_description desc; desc.add_options() ("help", "Show help message") ("host", boost::program_options::value<std::string>(), "Host for the MongoDB.") ("port", boost::program_options::value<std::size_t>(), "Port for the MongoDB.") ("views",boost::program_options::value<std::string>(), "Bag file for viewpoints") ("camera_topic",boost::program_options::value<std::string>(), "Topic for publishing to the camera position") ("planning_scene_topic",boost::program_options::value<std::string>(), "Topic for publishing the planning scene for recording") ("display_traj_topic",boost::program_options::value<std::string>(), "Topic for publishing the trajectory for recorder") ("animation_status_topic",boost::program_options::value<std::string>(), "Topic for listening to the completion of the replay") ("save_dir",boost::program_options::value<std::string>(), "Directory for saving videos"); boost::program_options::variables_map vm; boost::program_options::parsed_options po = boost::program_options::parse_command_line(argc, argv, desc); boost::program_options::store(po, vm); boost::program_options::notify(vm); if (vm.count("help") || argc == 1) // show help if no parameters passed { std::cout << desc << std::endl; return 1; } try { //connect to the DB std::string host = vm.count("host") ? vm["host"].as<std::string>() : ""; size_t port = vm.count("port") ? vm["port"].as<std::size_t>() : 0; moveit_warehouse::PlanningSceneStorage pss(host, port); ROS_INFO("Connected to Warehouse DB at host (%s) and port (%d)", host.c_str(), (int)port); // set up the storage directory boost::filesystem::path storage_dir( vm.count("save_dir") ? vm["save_dir"].as<std::string>() : "/tmp" ); boost::filesystem::create_directories( storage_dir ); // create bag file to track the associated video to the scene, query, and traj that spawned it boost::filesystem::path bagpath = storage_dir / "video_lookup.bag"; rosbag::Bag bag(bagpath.string(), rosbag::bagmode::Write); bag.close(); // load the viewpoints std::string bagfilename = vm.count("views") ? vm["views"].as<std::string>() : ""; std::vector<view_controller_msgs::CameraPlacement> views; rosbag::Bag viewbag; viewbag.open(bagfilename, rosbag::bagmode::Read); std::vector<std::string> topics; topics.push_back("viewpoints"); rosbag::View view_t(viewbag, rosbag::TopicQuery(topics)); BOOST_FOREACH(rosbag::MessageInstance const m, view_t) { view_controller_msgs::CameraPlacement::ConstPtr i = m.instantiate<view_controller_msgs::CameraPlacement>(); if (i != NULL) views.push_back(*i); } viewbag.close(); ROS_INFO("%d views loaded",(int)views.size()); //TODO change these to params std::string camera_placement_topic = utils::get_option(vm, "camera_topic", "/rviz/camera_placement"); std::string planning_scene_topic =utils:: get_option(vm, "planning_scene_topic", "planning_scene"); std::string display_traj_topic = utils::get_option(vm, "display_traj_topic", "/move_group/display_planned_path"); std::string anim_status_topic = utils::get_option(vm, "animation_status_topic", "animation_status"); AnimationRecorder recorder( camera_placement_topic, planning_scene_topic, display_traj_topic, anim_status_topic, node_handle); // ask the warehouse for the scenes std::vector<std::string> ps_names; pss.getPlanningSceneNames( ps_names ); ROS_INFO("%d available scenes to display", (int)ps_names.size()); // iterate over scenes std::vector<std::string>::iterator scene_name = ps_names.begin(); for(; scene_name!=ps_names.end(); ++scene_name) { ROS_INFO("Retrieving scene %s", scene_name->c_str()); moveit_warehouse::PlanningSceneWithMetadata pswm; pss.getPlanningScene(pswm, *scene_name); moveit_msgs::PlanningScene ps_msg = static_cast<const moveit_msgs::PlanningScene&>(*pswm); // ask qarehosue for the queries std::vector<std::string> pq_names; pss.getPlanningQueriesNames( pq_names, *scene_name); ROS_INFO("%d available queries to display", (int)pq_names.size()); // iterate over the queries std::vector<std::string>::iterator query_name = pq_names.begin(); for(; query_name!=pq_names.end(); ++query_name) { ROS_INFO("Retrieving query %s", query_name->c_str()); moveit_warehouse::MotionPlanRequestWithMetadata mprwm; pss.getPlanningQuery(mprwm, *scene_name, *query_name); moveit_msgs::MotionPlanRequest mpr_msg = static_cast<const moveit_msgs::MotionPlanRequest&>(*mprwm); // ask warehouse for stored trajectories std::vector<moveit_warehouse::RobotTrajectoryWithMetadata> planning_results; pss.getPlanningResults(planning_results, *scene_name, *query_name); ROS_INFO("Loaded %d trajectories", (int)planning_results.size()); // animate each trajectory std::vector<moveit_warehouse::RobotTrajectoryWithMetadata>::iterator traj_w_mdata = planning_results.begin(); for(; traj_w_mdata!=planning_results.end(); ++traj_w_mdata) { moveit_msgs::RobotTrajectory rt_msg; rt_msg = static_cast<const moveit_msgs::RobotTrajectory&>(**traj_w_mdata); // retime it TrajectoryRetimer retimer( "robot_description", mpr_msg.group_name ); retimer.configure(ps_msg, mpr_msg); bool result = retimer.retime(rt_msg); ROS_INFO("Retiming success? %s", result? "yes" : "no" ); //date and time based filename boost::posix_time::ptime now = boost::posix_time::second_clock::local_time(); std::string vid_filename = boost::posix_time::to_simple_string(now); // fix filename std::replace(vid_filename.begin(), vid_filename.end(), '-','_'); std::replace(vid_filename.begin(), vid_filename.end(), ' ','_'); std::replace(vid_filename.begin(), vid_filename.end(), ':','_'); boost::filesystem::path filename( vid_filename ); boost::filesystem::path filepath = storage_dir / filename; // save into lookup rosbag::Bag bag(bagpath.string(), rosbag::bagmode::Append); bag.write(filepath.string(), ros::Time::now(), ps_msg); bag.write(filepath.string(), ros::Time::now(), mpr_msg); bag.write(filepath.string(), ros::Time::now(), rt_msg); int view_counter=0; std::vector<view_controller_msgs::CameraPlacement>::iterator view_msg; for(view_msg=views.begin(); view_msg!=views.end(); ++view_msg) { AnimationRequest req; view_msg->time_from_start = ros::Duration(0.1); ros::Time t_now = ros::Time::now(); view_msg->eye.header.stamp = t_now; view_msg->focus.header.stamp = t_now; view_msg->up.header.stamp = t_now; req.camera_placement = *view_msg; req.planning_scene = ps_msg; req.motion_plan_request = mpr_msg; req.robot_trajectory = rt_msg; // same filename, counter for viewpoint std::string ext = boost::lexical_cast<std::string>(view_counter++) + ".ogv"; std_msgs::String filemsg; filemsg.data = req.filepath; bag.write(filepath.string(), ros::Time::now(), filemsg); std::string video_file = filepath.string()+ext; req.filepath = video_file; recorder.record(req); recorder.startCapture(); ROS_INFO("RECORDING DONE!"); }//view bag.close(); }//traj }//query }//scene } catch(mongo_ros::DbConnectException &ex) { ROS_ERROR_STREAM("Unable to connect to warehouse. If you just created the database, it could take a while for initial setup. Please try to run the benchmark again." << std::endl << ex.what()); } ROS_INFO("Successfully performed trajectory playback"); ros::shutdown(); return 0; } <|endoftext|>
<commit_before><commit_msg>MIOpen add OpenCL backend deprecation Message (#1664)<commit_after><|endoftext|>
<commit_before><commit_msg>fixed formatting<commit_after><|endoftext|>
<commit_before>/* -*- C++ -*- This file is part of ThreadWeaver. SPDX-FileCopyrightText: 2005-2014 Mirko Boehm <mirko@kde.org> SPDX-License-Identifier: LGPL-2.0-or-later */ #include <QtDebug> #include <QFile> #include <QFileInfo> #include <QLocale> #include <QImageReader> #include <QBuffer> #include <ThreadWeaver/ThreadWeaver> #include <ThreadWeaver/Exception> #include "Image.h" #include "Model.h" //const int Image::ThumbHeight = 75; //const int Image::ThumbWidth = 120; const int Image::ThumbHeight = 60; const int Image::ThumbWidth = 80; QReadWriteLock Image::Lock; int Image::ProcessingOrder; Image::Image(const QString inputFileName, const QString outputFileName, Model *model, int id) : m_inputFileName(inputFileName) , m_outputFileName(outputFileName) , m_model(model) , m_id(id) { } Progress Image::progress() const { #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) return qMakePair(m_progress.load(), Step_NumberOfSteps); #else return qMakePair(m_progress.loadRelaxed(), Step_NumberOfSteps); #endif } QString Image::description() const { QReadLocker l(&Lock); return m_description; } QString Image::details() const { QReadLocker l(&Lock); return m_details; } QString Image::details2() const { QReadLocker l(&Lock); return m_details2; } int Image::processingOrder() const { return m_processingOrder.loadAcquire(); } const QString Image::inputFileName() const { return m_inputFileName; } const QString Image::outputFileName() const { return m_outputFileName; } QImage Image::thumbNail() const { QReadLocker r(&Lock); return m_thumbnail; } void Image::loadFile() { m_processingOrder.storeRelease(ProcessingOrder++); QFile file(m_inputFileName); if (!file.open(QIODevice::ReadOnly)) { error(Step_LoadFile, tr("Unable to load input file!")); } m_imageData = file.readAll(); QFileInfo fi(file); QLocale locale; QString details2 = tr("%1kB").arg(locale.toString(fi.size()/1024)); { QWriteLocker l(&Lock); m_description = fi.fileName(); m_details2 = details2; } announceProgress(Step_LoadFile); } void Image::loadImage() { m_processingOrder.storeRelease(ProcessingOrder++); QBuffer in(&m_imageData); in.open(QIODevice::ReadOnly); QImageReader reader(&in); m_image = reader.read(); m_imageData.clear(); if (m_image.isNull()) { QWriteLocker l(&Lock); m_details = tr("%1!").arg(reader.errorString()); error(Step_LoadImage, m_details); } QString details = tr("%1x%2 pixels") .arg(m_image.width()) .arg(m_image.height()); { QWriteLocker l(&Lock); m_details = details; } announceProgress(Step_LoadImage); } void Image::computeThumbNail() { m_processingOrder.storeRelease(ProcessingOrder++); QImage thumb = m_image.scaled(ThumbWidth, ThumbHeight, Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation); if (thumb.isNull()) { error(Step_ComputeThumbNail, tr("Unable to compute thumbnail!")); } { // thumb is implicitly shared, no copy: QWriteLocker l(&Lock); m_thumbnail = thumb; } m_image = QImage(); announceProgress(Step_ComputeThumbNail); } void Image::saveThumbNail() { QImage thumb; { QReadLocker r(&Lock); thumb = m_thumbnail; } if (!thumb.save(m_outputFileName)) { error(Step_SaveThumbNail, tr("Unable to save output file!")); } announceProgress(Step_SaveThumbNail); } void Image::announceProgress(Steps step) { m_progress.storeRelease(step); if (m_model) { m_model->progressChanged(); m_model->elementChanged(m_id); } } void Image::error(Image::Steps step, const QString &message) { #if QT_VERSION < QT_VERSION_CHECK(5, 15, 0) m_failedStep.store(step); #else m_failedStep.storeRelaxed(step); #endif announceProgress(Step_Complete); throw ThreadWeaver::JobFailed(message); } <commit_msg>QBasicAtomicInteger<T>::storeRelaxed() is available since 5.14<commit_after>/* -*- C++ -*- This file is part of ThreadWeaver. SPDX-FileCopyrightText: 2005-2014 Mirko Boehm <mirko@kde.org> SPDX-License-Identifier: LGPL-2.0-or-later */ #include <QtDebug> #include <QFile> #include <QFileInfo> #include <QLocale> #include <QImageReader> #include <QBuffer> #include <ThreadWeaver/ThreadWeaver> #include <ThreadWeaver/Exception> #include "Image.h" #include "Model.h" //const int Image::ThumbHeight = 75; //const int Image::ThumbWidth = 120; const int Image::ThumbHeight = 60; const int Image::ThumbWidth = 80; QReadWriteLock Image::Lock; int Image::ProcessingOrder; Image::Image(const QString inputFileName, const QString outputFileName, Model *model, int id) : m_inputFileName(inputFileName) , m_outputFileName(outputFileName) , m_model(model) , m_id(id) { } Progress Image::progress() const { #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) return qMakePair(m_progress.load(), Step_NumberOfSteps); #else return qMakePair(m_progress.loadRelaxed(), Step_NumberOfSteps); #endif } QString Image::description() const { QReadLocker l(&Lock); return m_description; } QString Image::details() const { QReadLocker l(&Lock); return m_details; } QString Image::details2() const { QReadLocker l(&Lock); return m_details2; } int Image::processingOrder() const { return m_processingOrder.loadAcquire(); } const QString Image::inputFileName() const { return m_inputFileName; } const QString Image::outputFileName() const { return m_outputFileName; } QImage Image::thumbNail() const { QReadLocker r(&Lock); return m_thumbnail; } void Image::loadFile() { m_processingOrder.storeRelease(ProcessingOrder++); QFile file(m_inputFileName); if (!file.open(QIODevice::ReadOnly)) { error(Step_LoadFile, tr("Unable to load input file!")); } m_imageData = file.readAll(); QFileInfo fi(file); QLocale locale; QString details2 = tr("%1kB").arg(locale.toString(fi.size()/1024)); { QWriteLocker l(&Lock); m_description = fi.fileName(); m_details2 = details2; } announceProgress(Step_LoadFile); } void Image::loadImage() { m_processingOrder.storeRelease(ProcessingOrder++); QBuffer in(&m_imageData); in.open(QIODevice::ReadOnly); QImageReader reader(&in); m_image = reader.read(); m_imageData.clear(); if (m_image.isNull()) { QWriteLocker l(&Lock); m_details = tr("%1!").arg(reader.errorString()); error(Step_LoadImage, m_details); } QString details = tr("%1x%2 pixels") .arg(m_image.width()) .arg(m_image.height()); { QWriteLocker l(&Lock); m_details = details; } announceProgress(Step_LoadImage); } void Image::computeThumbNail() { m_processingOrder.storeRelease(ProcessingOrder++); QImage thumb = m_image.scaled(ThumbWidth, ThumbHeight, Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation); if (thumb.isNull()) { error(Step_ComputeThumbNail, tr("Unable to compute thumbnail!")); } { // thumb is implicitly shared, no copy: QWriteLocker l(&Lock); m_thumbnail = thumb; } m_image = QImage(); announceProgress(Step_ComputeThumbNail); } void Image::saveThumbNail() { QImage thumb; { QReadLocker r(&Lock); thumb = m_thumbnail; } if (!thumb.save(m_outputFileName)) { error(Step_SaveThumbNail, tr("Unable to save output file!")); } announceProgress(Step_SaveThumbNail); } void Image::announceProgress(Steps step) { m_progress.storeRelease(step); if (m_model) { m_model->progressChanged(); m_model->elementChanged(m_id); } } void Image::error(Image::Steps step, const QString &message) { #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) m_failedStep.store(step); #else m_failedStep.storeRelaxed(step); #endif announceProgress(Step_Complete); throw ThreadWeaver::JobFailed(message); } <|endoftext|>
<commit_before>/* *************************************** * Asylum3D @ 2014-12-17 *************************************** */ #ifndef __ASYLUM3D_HPP__ #define __ASYLUM3D_HPP__ /* Asylum Namespace */ namespace asy { /***************/ /* Effect Port */ /***************/ class IEffect : public asylum { public: /* ================ */ virtual ~IEffect () {} public: /* ==================== */ virtual void enter () = 0; /* ==================== */ virtual void leave () = 0; }; /******************/ /* Attribute Port */ /******************/ class IAttrib : public asylum { protected: int64u m_type; public: /* ================ */ virtual ~IAttrib () {} public: /* ===================== */ virtual void commit () = 0; /* ============== */ int64u type () const { return (m_type); } }; // Attribute Type #define ATTR_TYPE_ALPHAOP 0x00000001ULL // Alpha Blend #define ATTR_TYPE_TEXTURE 0x00000002ULL // Have Texture #define ATTR_TYPE_SPECULAR 0x00000004ULL // Specular Light #define ATTR_TYPE_NRML_MAP 0x00000008ULL // Normal Map #define ATTR_TYPE_LGHT_MAP 0x00000010ULL // Light Map /*************/ /* Mesh Port */ /*************/ class IMesh : public asylum { public: /* ============== */ virtual ~IMesh () {} /* ===================== */ virtual void commit () = 0; }; /****************/ /* Commit Batch */ /****************/ struct commit_batch { IMesh** mesh; IAttrib* attr; /* ====== */ void free () { IMesh* tmp; size_t idx; if (this->attr != NULL) delete this->attr; if (this->mesh != NULL) { for (idx = 0; ; idx++) { tmp = this->mesh[idx]; if (tmp == NULL) break; delete tmp; } mem_free(this->mesh); } } }; /***************/ /* Object Base */ /***************/ struct object_base { void* real; sAABB aabb; sSPHERE ball; array<commit_batch> list; void (*kill) (void* real); /* ====== */ void free () { this->list.free(); if (this->real != NULL && this->kill != NULL) this->kill(this->real); } }; /*******************/ /* Object Instance */ /*******************/ struct object_inst { object_base* base; union { mat4x4_t mat; struct { vec3d_t rote; vec3d_t move; vec3d_t scale; } sep; } trans; union { sAABB aabb; sSPHERE ball; } bound; /* ========= */ void free () {} }; } /* namespace */ #endif /* __ASYLUM3D_HPP__ */ <commit_msg>Asylum: 增加提交管线类型<commit_after>/* *************************************** * Asylum3D @ 2014-12-17 *************************************** */ #ifndef __ASYLUM3D_HPP__ #define __ASYLUM3D_HPP__ /* Asylum Namespace */ namespace asy { /***************/ /* Effect Port */ /***************/ class IEffect : public asylum { public: /* ================ */ virtual ~IEffect () {} public: /* ==================== */ virtual void enter () = 0; /* ==================== */ virtual void leave () = 0; }; /******************/ /* Attribute Port */ /******************/ class IAttrib : public asylum { protected: int64u m_type; public: /* ================ */ virtual ~IAttrib () {} public: /* ===================== */ virtual void commit () = 0; /* ============== */ int64u type () const { return (m_type); } }; // Attribute Type #define ATTR_TYPE_ALPHAOP 0x00000001ULL // Alpha Blend #define ATTR_TYPE_TEXTURE 0x00000002ULL // Have Texture #define ATTR_TYPE_SPECULAR 0x00000004ULL // Specular Light #define ATTR_TYPE_NRML_MAP 0x00000008ULL // Normal Map #define ATTR_TYPE_LGHT_MAP 0x00000010ULL // Light Map /*************/ /* Mesh Port */ /*************/ class IMesh : public asylum { public: /* ============== */ virtual ~IMesh () {} /* ===================== */ virtual void commit () = 0; }; /****************/ /* Commit Batch */ /****************/ struct commit_batch { IMesh** mesh; IAttrib* attr; /* ====== */ void free () { IMesh* tmp; size_t idx; if (this->attr != NULL) delete this->attr; if (this->mesh != NULL) { for (idx = 0; ; idx++) { tmp = this->mesh[idx]; if (tmp == NULL) break; delete tmp; } mem_free(this->mesh); } } }; /***************/ /* Object Base */ /***************/ struct object_base { void* real; sAABB aabb; sSPHERE ball; array<commit_batch> list; void (*kill) (void* real); /* ====== */ void free () { this->list.free(); if (this->real != NULL && this->kill != NULL) this->kill(this->real); } }; /*******************/ /* Object Instance */ /*******************/ struct object_inst { object_base* base; union { mat4x4_t mat; struct { vec3d_t rote; vec3d_t move; vec3d_t scale; } sep; } trans; union { sAABB aabb; sSPHERE ball; } bound; /* ========= */ void free () {} }; /***************/ /* Commit Pipe */ /***************/ struct commit_pipe { array<cnode_ptr> stuff_list; // <commit_batch*> array<cnode_ptr> effect_stack; // <IEffect*> void free () { size_t size; IEffect* ffct; cnode_ptr* data; this->stuff_list.free(); size = this->effect_stack.size(); data = this->effect_stack.data(); for (size_t idx = 0; idx < size; idx++) { ffct = (IEffect*)(data[idx].ptr); delete ffct; } this->effect_stack.free(); } }; } /* namespace */ #endif /* __ASYLUM3D_HPP__ */ <|endoftext|>
<commit_before>#include <iostream> #include <gtest/gtest.h> TEST(sizeof, test1) { char str1[10]; char str2[] = "Hello World!"; EXPECT_EQ(10, sizeof(str1)); EXPECT_EQ(13, sizeof(str2)); } TEST(memcpy, test1) { int a[] = {1, 2, 3}; int b[3]; memcpy(b, a, sizeof(int) * 3); EXPECT_EQ(1, b[0]); EXPECT_EQ(2, b[1]); EXPECT_EQ(3, b[2]); } TEST(swap, test1) { int a = 1; int b = 2; std::swap(a, b); EXPECT_EQ(2, a); EXPECT_EQ(1, b); } TEST(array, test1) { int foo[2] = {1}; EXPECT_EQ(1, foo[0]); EXPECT_EQ(0, foo[1]); } <commit_msg>Add array sorting<commit_after>#include <iostream> #include <algorithm> #include <gtest/gtest.h> TEST(sizeof, test1) { char str1[10]; char str2[] = "Hello World!"; EXPECT_EQ(10, sizeof(str1)); EXPECT_EQ(13, sizeof(str2)); } TEST(memcpy, test1) { int a[] = {1, 2, 3}; int b[3]; memcpy(b, a, sizeof(int) * 3); EXPECT_EQ(1, b[0]); EXPECT_EQ(2, b[1]); EXPECT_EQ(3, b[2]); } TEST(swap, test1) { int a = 1; int b = 2; std::swap(a, b); EXPECT_EQ(2, a); EXPECT_EQ(1, b); } TEST(array, test1) { int foo[2] = {1}; EXPECT_EQ(1, foo[0]); EXPECT_EQ(0, foo[1]); } TEST(array, sorting) { int foo[3] = {1, 3, 2}; std::sort(foo, foo + 3); EXPECT_EQ(1, foo[0]); EXPECT_EQ(2, foo[1]); EXPECT_EQ(3, foo[2]); } <|endoftext|>
<commit_before>//===- xray-log-reader.cc - XRay Log Reader Implementation ----------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // XRay log reader implementation. // //===----------------------------------------------------------------------===// #include <sys/types.h> #include "xray-log-reader.h" #include "xray-record-yaml.h" #include "llvm/Support/DataExtractor.h" #include "llvm/Support/FileSystem.h" using namespace llvm; using namespace llvm::xray; using llvm::yaml::Input; LogReader::LogReader( StringRef Filename, Error &Err, bool Sort, std::function<Error(StringRef, XRayFileHeader &, std::vector<XRayRecord> &)> Loader) { ErrorAsOutParameter Guard(&Err); int Fd; if (auto EC = sys::fs::openFileForRead(Filename, Fd)) { Err = make_error<StringError>( Twine("Cannot read log from '") + Filename + "'", EC); return; } uint64_t FileSize; if (auto EC = sys::fs::file_size(Filename, FileSize)) { Err = make_error<StringError>( Twine("Cannot read log from '") + Filename + "'", EC); return; } std::error_code EC; sys::fs::mapped_file_region MappedFile( Fd, sys::fs::mapped_file_region::mapmode::readonly, FileSize, 0, EC); if (EC) { Err = make_error<StringError>( Twine("Cannot read log from '") + Filename + "'", EC); return; } if (auto E = Loader(StringRef(MappedFile.data(), MappedFile.size()), FileHeader, Records)) { Err = std::move(E); return; } if (Sort) std::sort( Records.begin(), Records.end(), [](const XRayRecord &L, const XRayRecord &R) { return L.TSC < R.TSC; }); } Error llvm::xray::NaiveLogLoader(StringRef Data, XRayFileHeader &FileHeader, std::vector<XRayRecord> &Records) { // FIXME: Maybe deduce whether the data is little or big-endian using some // magic bytes in the beginning of the file? // First 32 bytes of the file will always be the header. We assume a certain // format here: // // (2) uint16 : version // (2) uint16 : type // (4) uint32 : bitfield // (8) uint64 : cycle frequency // (16) - : padding // if (Data.size() < 32) return make_error<StringError>( "Not enough bytes for an XRay log.", std::make_error_code(std::errc::invalid_argument)); if (Data.size() - 32 == 0 || Data.size() % 32 != 0) return make_error<StringError>( "Invalid-sized XRay data.", std::make_error_code(std::errc::invalid_argument)); DataExtractor HeaderExtractor(Data, true, 8); uint32_t OffsetPtr = 0; FileHeader.Version = HeaderExtractor.getU16(&OffsetPtr); FileHeader.Type = HeaderExtractor.getU16(&OffsetPtr); uint32_t Bitfield = HeaderExtractor.getU32(&OffsetPtr); FileHeader.ConstantTSC = Bitfield & 1uL; FileHeader.NonstopTSC = Bitfield & 1uL << 1; FileHeader.CycleFrequency = HeaderExtractor.getU64(&OffsetPtr); if (FileHeader.Version != 1) return make_error<StringError>( Twine("Unsupported XRay file version: ") + Twine(FileHeader.Version), std::make_error_code(std::errc::invalid_argument)); // Each record after the header will be 32 bytes, in the following format: // // (2) uint16 : record type // (1) uint8 : cpu id // (1) uint8 : type // (4) sint32 : function id // (8) uint64 : tsc // (4) uint32 : thread id // (12) - : padding for (auto S = Data.drop_front(32); !S.empty(); S = S.drop_front(32)) { DataExtractor RecordExtractor(S, true, 8); uint32_t OffsetPtr = 0; Records.emplace_back(); auto &Record = Records.back(); Record.RecordType = RecordExtractor.getU16(&OffsetPtr); Record.CPU = RecordExtractor.getU8(&OffsetPtr); auto Type = RecordExtractor.getU8(&OffsetPtr); switch (Type) { case 0: Record.Type = RecordTypes::ENTER; break; case 1: Record.Type = RecordTypes::EXIT; break; default: return make_error<StringError>( Twine("Unknown record type '") + Twine(int{Type}) + "'", std::make_error_code(std::errc::protocol_error)); } Record.FuncId = RecordExtractor.getSigned(&OffsetPtr, sizeof(int32_t)); Record.TSC = RecordExtractor.getU64(&OffsetPtr); Record.TId = RecordExtractor.getU32(&OffsetPtr); } return Error::success(); } Error llvm::xray::YAMLLogLoader(StringRef Data, XRayFileHeader &FileHeader, std::vector<XRayRecord> &Records) { // Load the documents from the MappedFile. YAMLXRayTrace Trace; Input In(Data); In >> Trace; if (In.error()) return make_error<StringError>("Failed loading YAML Data.", In.error()); FileHeader.Version = Trace.Header.Version; FileHeader.Type = Trace.Header.Type; FileHeader.ConstantTSC = Trace.Header.ConstantTSC; FileHeader.NonstopTSC = Trace.Header.NonstopTSC; FileHeader.CycleFrequency = Trace.Header.CycleFrequency; if (FileHeader.Version != 1) return make_error<StringError>( Twine("Unsupported XRay file version: ") + Twine(FileHeader.Version), std::make_error_code(std::errc::invalid_argument)); Records.clear(); std::transform(Trace.Records.begin(), Trace.Records.end(), std::back_inserter(Records), [&](const YAMLXRayRecord &R) { return XRayRecord{R.RecordType, R.CPU, R.Type, R.FuncId, R.TSC, R.TId}; }); return Error::success(); } <commit_msg>[XRay] Fixup includes for modules build<commit_after>//===- xray-log-reader.cc - XRay Log Reader Implementation ----------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // XRay log reader implementation. // //===----------------------------------------------------------------------===// #include "xray-log-reader.h" #include "xray-record-yaml.h" #include "llvm/Support/DataExtractor.h" #include "llvm/Support/FileSystem.h" using namespace llvm; using namespace llvm::xray; using llvm::yaml::Input; LogReader::LogReader( StringRef Filename, Error &Err, bool Sort, std::function<Error(StringRef, XRayFileHeader &, std::vector<XRayRecord> &)> Loader) { ErrorAsOutParameter Guard(&Err); int Fd; if (auto EC = sys::fs::openFileForRead(Filename, Fd)) { Err = make_error<StringError>( Twine("Cannot read log from '") + Filename + "'", EC); return; } uint64_t FileSize; if (auto EC = sys::fs::file_size(Filename, FileSize)) { Err = make_error<StringError>( Twine("Cannot read log from '") + Filename + "'", EC); return; } std::error_code EC; sys::fs::mapped_file_region MappedFile( Fd, sys::fs::mapped_file_region::mapmode::readonly, FileSize, 0, EC); if (EC) { Err = make_error<StringError>( Twine("Cannot read log from '") + Filename + "'", EC); return; } if (auto E = Loader(StringRef(MappedFile.data(), MappedFile.size()), FileHeader, Records)) { Err = std::move(E); return; } if (Sort) std::sort( Records.begin(), Records.end(), [](const XRayRecord &L, const XRayRecord &R) { return L.TSC < R.TSC; }); } Error llvm::xray::NaiveLogLoader(StringRef Data, XRayFileHeader &FileHeader, std::vector<XRayRecord> &Records) { // FIXME: Maybe deduce whether the data is little or big-endian using some // magic bytes in the beginning of the file? // First 32 bytes of the file will always be the header. We assume a certain // format here: // // (2) uint16 : version // (2) uint16 : type // (4) uint32 : bitfield // (8) uint64 : cycle frequency // (16) - : padding // if (Data.size() < 32) return make_error<StringError>( "Not enough bytes for an XRay log.", std::make_error_code(std::errc::invalid_argument)); if (Data.size() - 32 == 0 || Data.size() % 32 != 0) return make_error<StringError>( "Invalid-sized XRay data.", std::make_error_code(std::errc::invalid_argument)); DataExtractor HeaderExtractor(Data, true, 8); uint32_t OffsetPtr = 0; FileHeader.Version = HeaderExtractor.getU16(&OffsetPtr); FileHeader.Type = HeaderExtractor.getU16(&OffsetPtr); uint32_t Bitfield = HeaderExtractor.getU32(&OffsetPtr); FileHeader.ConstantTSC = Bitfield & 1uL; FileHeader.NonstopTSC = Bitfield & 1uL << 1; FileHeader.CycleFrequency = HeaderExtractor.getU64(&OffsetPtr); if (FileHeader.Version != 1) return make_error<StringError>( Twine("Unsupported XRay file version: ") + Twine(FileHeader.Version), std::make_error_code(std::errc::invalid_argument)); // Each record after the header will be 32 bytes, in the following format: // // (2) uint16 : record type // (1) uint8 : cpu id // (1) uint8 : type // (4) sint32 : function id // (8) uint64 : tsc // (4) uint32 : thread id // (12) - : padding for (auto S = Data.drop_front(32); !S.empty(); S = S.drop_front(32)) { DataExtractor RecordExtractor(S, true, 8); uint32_t OffsetPtr = 0; Records.emplace_back(); auto &Record = Records.back(); Record.RecordType = RecordExtractor.getU16(&OffsetPtr); Record.CPU = RecordExtractor.getU8(&OffsetPtr); auto Type = RecordExtractor.getU8(&OffsetPtr); switch (Type) { case 0: Record.Type = RecordTypes::ENTER; break; case 1: Record.Type = RecordTypes::EXIT; break; default: return make_error<StringError>( Twine("Unknown record type '") + Twine(int{Type}) + "'", std::make_error_code(std::errc::protocol_error)); } Record.FuncId = RecordExtractor.getSigned(&OffsetPtr, sizeof(int32_t)); Record.TSC = RecordExtractor.getU64(&OffsetPtr); Record.TId = RecordExtractor.getU32(&OffsetPtr); } return Error::success(); } Error llvm::xray::YAMLLogLoader(StringRef Data, XRayFileHeader &FileHeader, std::vector<XRayRecord> &Records) { // Load the documents from the MappedFile. YAMLXRayTrace Trace; Input In(Data); In >> Trace; if (In.error()) return make_error<StringError>("Failed loading YAML Data.", In.error()); FileHeader.Version = Trace.Header.Version; FileHeader.Type = Trace.Header.Type; FileHeader.ConstantTSC = Trace.Header.ConstantTSC; FileHeader.NonstopTSC = Trace.Header.NonstopTSC; FileHeader.CycleFrequency = Trace.Header.CycleFrequency; if (FileHeader.Version != 1) return make_error<StringError>( Twine("Unsupported XRay file version: ") + Twine(FileHeader.Version), std::make_error_code(std::errc::invalid_argument)); Records.clear(); std::transform(Trace.Records.begin(), Trace.Records.end(), std::back_inserter(Records), [&](const YAMLXRayRecord &R) { return XRayRecord{R.RecordType, R.CPU, R.Type, R.FuncId, R.TSC, R.TId}; }); return Error::success(); } <|endoftext|>
<commit_before>#include "includes.h" #include <sys/types.h> #include <dirent.h> void prepare_logdir() { spdlog::drop_all(); #ifdef _WIN32 system("if not exist logs mkdir logs"); system("del /F /Q logs\\*"); #else auto rv = system("mkdir -p logs"); if (rv != 0) { throw std::runtime_error("Failed to mkdir -p logs"); } rv = system("rm -f logs/*"); if (rv != 0) { throw std::runtime_error("Failed to rm -f logs/*"); } #endif } std::string file_contents(const std::string &filename) { std::ifstream ifs(filename); if (!ifs) { throw std::runtime_error("Failed open file "); } return std::string((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>())); } std::size_t count_lines(const std::string &filename) { std::ifstream ifs(filename); if (!ifs) { throw std::runtime_error("Failed open file "); } std::string line; size_t counter = 0; while (std::getline(ifs, line)) counter++; return counter; } std::size_t get_filesize(const std::string &filename) { std::ifstream ifs(filename, std::ifstream::ate | std::ifstream::binary); if (!ifs) { throw std::runtime_error("Failed open file "); } return static_cast<std::size_t>(ifs.tellg()); } // source: https://stackoverflow.com/a/2072890/192001 bool ends_with(std::string const &value, std::string const &ending) { if (ending.size() > value.size()) { return false; } return std::equal(ending.rbegin(), ending.rend(), value.rbegin()); } #ifdef _WIN32 std::size_t count_files(const std::string &folder) {} #else // Based on: https://stackoverflow.com/a/2802255/192001 std::size_t count_files(const std::string &folder) { size_t counter = 0; DIR *dp = opendir(folder.c_str()); if (dp == nullptr) { throw std::runtime_error("Failed open folder " + folder); } struct dirent *ep; while (ep = readdir(dp)) { if (ep->d_name[0] != '.') counter++; } (void)closedir(dp); return counter; } #endif <commit_msg>Update test utils for windows<commit_after>#include "includes.h" #include <sys/types.h> #include <dirent.h> void prepare_logdir() { spdlog::drop_all(); #ifdef _WIN32 system("if not exist logs mkdir logs"); system("del /F /Q logs\\*"); #else auto rv = system("mkdir -p logs"); if (rv != 0) { throw std::runtime_error("Failed to mkdir -p logs"); } rv = system("rm -f logs/*"); if (rv != 0) { throw std::runtime_error("Failed to rm -f logs/*"); } #endif } std::string file_contents(const std::string &filename) { std::ifstream ifs(filename); if (!ifs) { throw std::runtime_error("Failed open file "); } return std::string((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>())); } std::size_t count_lines(const std::string &filename) { std::ifstream ifs(filename); if (!ifs) { throw std::runtime_error("Failed open file "); } std::string line; size_t counter = 0; while (std::getline(ifs, line)) counter++; return counter; } std::size_t get_filesize(const std::string &filename) { std::ifstream ifs(filename, std::ifstream::ate | std::ifstream::binary); if (!ifs) { throw std::runtime_error("Failed open file "); } return static_cast<std::size_t>(ifs.tellg()); } // source: https://stackoverflow.com/a/2072890/192001 bool ends_with(std::string const &value, std::string const &ending) { if (ending.size() > value.size()) { return false; } return std::equal(ending.rbegin(), ending.rend(), value.rbegin()); } #ifdef _WIN32 // source: https://stackoverflow.com/a/37416569/192001 std::size_t count_files(const std::string &folder) { counter counter = 0; WIN32_FIND_DATA ffd; HANDLE hFind = INVALID_HANDLE_VALUE; // Start iterating over the files in the path directory. hFind = ::FindFirstFileA(path.c_str(), &ffd); if (hFind != INVALID_HANDLE_VALUE) { do // Managed to locate and create an handle to that folder. { counter++; } while (::FindNextFile(hFind, &ffd) == TRUE); ::FindClose(hFind); } else { throw std::runtime_error("Failed open folder " + folder); } return counter; } #else // Based on: https://stackoverflow.com/a/2802255/192001 std::size_t count_files(const std::string &folder) { size_t counter = 0; DIR *dp = opendir(folder.c_str()); if (dp == nullptr) { throw std::runtime_error("Failed open folder " + folder); } struct dirent *ep; while (ep = readdir(dp)) { if (ep->d_name[0] != '.') counter++; } (void)closedir(dp); return counter; } #endif <|endoftext|>
<commit_before>/***************************************************************************** * Media Library ***************************************************************************** * Copyright (C) 2015-2019 Hugo Beauzée-Luyssen, Videolabs, VideoLAN * * Authors: Hugo Beauzée-Luyssen <hugo@beauzee.fr> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #if HAVE_CONFIG_H # include "config.h" #endif #include "Parser.h" #include <utility> #include <cassert> #include "MediaLibrary.h" #include "ParserWorker.h" #include "parser/Task.h" #include "logging/Logger.h" namespace medialibrary { namespace parser { Parser::Parser( MediaLibrary* ml ) : m_ml( ml ) , m_callback( ml->getCb() ) , m_opToDo( 0 ) , m_opDone( 0 ) , m_percent( 0 ) { } Parser::~Parser() { stop(); } void Parser::addService( ServicePtr service ) { auto worker = std::unique_ptr<Worker>( new Worker ); if ( worker->initialize( m_ml, this, std::move( service ) ) == false ) return; m_serviceWorkers.push_back( std::move( worker ) ); } void Parser::parse( std::shared_ptr<Task> task ) { if ( m_serviceWorkers.empty() == true ) return; assert( task != nullptr ); m_serviceWorkers[0]->parse( std::move( task ) ); ++m_opToDo; updateStats(); } void Parser::start() { assert( m_serviceWorkers.size() == 3 ); restore(); } void Parser::pause() { for ( auto& s : m_serviceWorkers ) s->pause(); } void Parser::resume() { for ( auto& s : m_serviceWorkers ) s->resume(); } void Parser::stop() { for ( auto& s : m_serviceWorkers ) { s->signalStop(); } for ( auto& s : m_serviceWorkers ) { s->stop(); } } void Parser::flush() { for ( auto& s : m_serviceWorkers ) s->flush(); m_opToDo = 0; m_opDone = 0; } void Parser::prepareRescan() { pause(); flush(); } void Parser::rescan() { restart(); restore(); resume(); } void Parser::restart() { for ( auto& s : m_serviceWorkers ) s->restart(); } void Parser::restore() { if ( m_serviceWorkers.empty() == true ) return; auto tasks = Task::fetchUncompleted( m_ml ); if ( tasks.empty() == true ) { LOG_DEBUG( "No task to resume." ); return; } LOG_INFO( "Resuming parsing on ", tasks.size(), " tasks" ); m_opToDo += tasks.size(); updateStats(); m_serviceWorkers[0]->parse( std::move( tasks ) ); } void Parser::refreshTaskList() { /* * We need to do this in various steps: * - Pausing the workers after their currently running task * - Flushing their task list * - Restoring the task list from DB * - Resuming the workers */ pause(); flush(); restore(); resume(); } void Parser::updateStats() { if ( m_opDone == 0 && m_opToDo > 0 && m_chrono == decltype(m_chrono){}) m_chrono = std::chrono::steady_clock::now(); auto percent = m_opToDo > 0 ? ( m_opDone * 100 / m_opToDo ) : 0; assert( m_opToDo >= m_opDone ); if ( percent != m_percent ) { m_percent = percent; LOG_DEBUG( "Updating progress: ", percent ); m_callback->onParsingStatsUpdated( m_percent ); if ( m_percent == 100 ) { auto duration = std::chrono::steady_clock::now() - m_chrono; LOG_VERBOSE( "Finished all parsing operations in ", std::chrono::duration_cast<std::chrono::milliseconds>( duration ).count(), "ms" ); m_chrono = decltype(m_chrono){}; } } } void Parser::done( std::shared_ptr<Task> t, Status status ) { auto serviceIdx = t->goToNextService(); if ( status == Status::TemporaryUnavailable || status == Status::Fatal || status == Status::Discarded || t->isCompleted() ) { ++m_opDone; updateStats(); // We create a separate task for refresh, which doesn't count toward // (mrl,parent_playlist) uniqueness. In order to allow for a subsequent // refresh of the same file, we remove it once the refresh is complete. // In case the status was `Discarded`, the task was already deleted from // the database. if ( t->isRefresh() == true ) Task::destroy( m_ml, t->id() ); return; } if ( status == Status::Requeue ) { // The retry_count is mostly handled when fetching the remaining tasks // from the database. However, when requeuing, it all happens at runtime // in the C++ code, so we also need to ensure we're not requeuing tasks // forever. if ( t->retryCount() >= parser::MaxNbRetries ) { ++m_opDone; updateStats(); return; } t->resetCurrentService(); serviceIdx = 0; } // If some services declined to parse the file, start over again. assert( serviceIdx < m_serviceWorkers.size() ); updateStats(); m_serviceWorkers[serviceIdx]->parse( std::move( t ) ); } void Parser::onIdleChanged( bool idle ) { // If any parser service is not idle, then the global parser state is active if ( idle == false ) { m_ml->onParserIdleChanged( false ); return; } // Otherwise the parser is idle when all services are idle for ( const auto& s : m_serviceWorkers ) { // We're switching a service from "not idle" to "idle" here, so as far as the medialibrary // is concerned the parser is still "not idle". In case a single parser service isn't // idle, no need to trigger a change to the medialibrary. if ( s->isIdle() == false ) return; } m_ml->onParserIdleChanged( true ); } } } <commit_msg>Parser: Fix linking tasks retry handling<commit_after>/***************************************************************************** * Media Library ***************************************************************************** * Copyright (C) 2015-2019 Hugo Beauzée-Luyssen, Videolabs, VideoLAN * * Authors: Hugo Beauzée-Luyssen <hugo@beauzee.fr> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #if HAVE_CONFIG_H # include "config.h" #endif #include "Parser.h" #include <utility> #include <cassert> #include "MediaLibrary.h" #include "ParserWorker.h" #include "parser/Task.h" #include "logging/Logger.h" namespace medialibrary { namespace parser { Parser::Parser( MediaLibrary* ml ) : m_ml( ml ) , m_callback( ml->getCb() ) , m_opToDo( 0 ) , m_opDone( 0 ) , m_percent( 0 ) { } Parser::~Parser() { stop(); } void Parser::addService( ServicePtr service ) { auto worker = std::unique_ptr<Worker>( new Worker ); if ( worker->initialize( m_ml, this, std::move( service ) ) == false ) return; m_serviceWorkers.push_back( std::move( worker ) ); } void Parser::parse( std::shared_ptr<Task> task ) { if ( m_serviceWorkers.empty() == true ) return; assert( task != nullptr ); m_serviceWorkers[0]->parse( std::move( task ) ); ++m_opToDo; updateStats(); } void Parser::start() { assert( m_serviceWorkers.size() == 3 ); restore(); } void Parser::pause() { for ( auto& s : m_serviceWorkers ) s->pause(); } void Parser::resume() { for ( auto& s : m_serviceWorkers ) s->resume(); } void Parser::stop() { for ( auto& s : m_serviceWorkers ) { s->signalStop(); } for ( auto& s : m_serviceWorkers ) { s->stop(); } } void Parser::flush() { for ( auto& s : m_serviceWorkers ) s->flush(); m_opToDo = 0; m_opDone = 0; } void Parser::prepareRescan() { pause(); flush(); } void Parser::rescan() { restart(); restore(); resume(); } void Parser::restart() { for ( auto& s : m_serviceWorkers ) s->restart(); } void Parser::restore() { if ( m_serviceWorkers.empty() == true ) return; auto tasks = Task::fetchUncompleted( m_ml ); if ( tasks.empty() == true ) { LOG_DEBUG( "No task to resume." ); return; } LOG_INFO( "Resuming parsing on ", tasks.size(), " tasks" ); m_opToDo += tasks.size(); updateStats(); m_serviceWorkers[0]->parse( std::move( tasks ) ); } void Parser::refreshTaskList() { /* * We need to do this in various steps: * - Pausing the workers after their currently running task * - Flushing their task list * - Restoring the task list from DB * - Resuming the workers */ pause(); flush(); restore(); resume(); } void Parser::updateStats() { if ( m_opDone == 0 && m_opToDo > 0 && m_chrono == decltype(m_chrono){}) m_chrono = std::chrono::steady_clock::now(); auto percent = m_opToDo > 0 ? ( m_opDone * 100 / m_opToDo ) : 0; assert( m_opToDo >= m_opDone ); if ( percent != m_percent ) { m_percent = percent; LOG_DEBUG( "Updating progress: ", percent ); m_callback->onParsingStatsUpdated( m_percent ); if ( m_percent == 100 ) { auto duration = std::chrono::steady_clock::now() - m_chrono; LOG_VERBOSE( "Finished all parsing operations in ", std::chrono::duration_cast<std::chrono::milliseconds>( duration ).count(), "ms" ); m_chrono = decltype(m_chrono){}; } } } void Parser::done( std::shared_ptr<Task> t, Status status ) { auto serviceIdx = t->goToNextService(); if ( status == Status::TemporaryUnavailable || status == Status::Fatal || status == Status::Discarded || t->isCompleted() ) { ++m_opDone; updateStats(); // We create a separate task for refresh, which doesn't count toward // (mrl,parent_playlist) uniqueness. In order to allow for a subsequent // refresh of the same file, we remove it once the refresh is complete. // In case the status was `Discarded`, the task was already deleted from // the database. if ( t->isRefresh() == true ) Task::destroy( m_ml, t->id() ); return; } if ( status == Status::Requeue ) { // The retry_count is mostly handled when fetching the remaining tasks // from the database. However, when requeuing, it all happens at runtime // in the C++ code, so we also need to ensure we're not requeuing tasks // forever. if ( t->retryCount() > parser::MaxNbRetries ) { ++m_opDone; updateStats(); return; } t->resetCurrentService(); serviceIdx = 0; } // If some services declined to parse the file, start over again. assert( serviceIdx < m_serviceWorkers.size() ); updateStats(); m_serviceWorkers[serviceIdx]->parse( std::move( t ) ); } void Parser::onIdleChanged( bool idle ) { // If any parser service is not idle, then the global parser state is active if ( idle == false ) { m_ml->onParserIdleChanged( false ); return; } // Otherwise the parser is idle when all services are idle for ( const auto& s : m_serviceWorkers ) { // We're switching a service from "not idle" to "idle" here, so as far as the medialibrary // is concerned the parser is still "not idle". In case a single parser service isn't // idle, no need to trigger a change to the medialibrary. if ( s->isIdle() == false ) return; } m_ml->onParserIdleChanged( true ); } } } <|endoftext|>
<commit_before>#include "qt/pivx/txrow.h" #include "qt/pivx/forms/ui_txrow.h" #include "guiutil.h" #include <iostream> TxRow::TxRow(bool isLightTheme, QWidget *parent) : QWidget(parent), ui(new Ui::TxRow) { ui->setupUi(this); setConfirmStatus(true); updateStatus(isLightTheme, false, false); } void TxRow::setConfirmStatus(bool isConfirm){ if(isConfirm){ ui->lblAddress->setProperty("cssClass", "text-list-body1"); ui->lblDate->setProperty("cssClass", "text-list-caption"); }else{ ui->lblAddress->setProperty("cssClass", "text-list-body-unconfirmed"); ui->lblDate->setProperty("cssClass","text-list-caption-unconfirmed"); } } void TxRow::updateStatus(bool isLightTheme, bool isHover, bool isSelected){ if(isLightTheme) ui->lblDivisory->setStyleSheet("background-color:#bababa"); else ui->lblDivisory->setStyleSheet("background-color:#40ffffff"); } void TxRow::setDate(QDateTime date){ ui->lblDate->setText(GUIUtil::dateTimeStr(date)); } void TxRow::setLabel(QString str){ ui->lblAddress->setText(str); } void TxRow::setAmount(QString str){ ui->lblAmount->setText(str); } // TODO: Agregar send to zPIV and receive zPIV icons.. void TxRow::setType(bool isLightTheme, int type, bool isConfirmed){ QString path; QString css; switch (type) { case TransactionRecord::ZerocoinMint: path = "://ic-transaction-mint"; css = "text-list-amount-send"; break; case TransactionRecord::Generated: case TransactionRecord::StakeZPIV: case TransactionRecord::MNReward: case TransactionRecord::StakeMint: path = "://ic-transaction-staked"; css = "text-list-amount-receive"; break; case TransactionRecord::RecvWithObfuscation: case TransactionRecord::RecvWithAddress: case TransactionRecord::RecvFromOther: case TransactionRecord::RecvFromZerocoinSpend: path = "://ic-transaction-received"; css = "text-list-amount-receive"; break; case TransactionRecord::SendToAddress: case TransactionRecord::SendToOther: case TransactionRecord::ZerocoinSpend: case TransactionRecord::ZerocoinSpend_Change_zPiv: case TransactionRecord::ZerocoinSpend_FromMe: path = "://ic-transaction-sent"; css = "text-list-amount-send"; break; case TransactionRecord::SendToSelf: path = "://ic-transaction-mint"; css = "text-list-amount-send"; break; default: path = ":/icons/tx_inout"; break; } if (!isConfirmed){ css = "text-list-amount-unconfirmed"; path += "-inactive"; setConfirmStatus(false); }else{ setConfirmStatus(true); } if (!isLightTheme){ path += "-dark"; } ui->lblAmount->setProperty("cssClass", css); ui->icon->setIcon(QIcon(path)); } TxRow::~TxRow() { delete ui; } void TxRow::sendRow(bool isLightTheme){ ui->lblAddress->setText("Sent to DN6i46dytMPV..hV1FuQBh7BZZ6nN"); ui->lblDate->setText("10/04/2019"); QPixmap pixmap(isLightTheme ? "://ic-transaction-sent" : "://ic-transaction-sent-dark"); ui->lblAmount->setText("-5.00 PIV"); ui->lblAmount->setProperty("cssClass", "text-list-amount-send"); QIcon buttonIcon(pixmap); ui->icon->setIcon(buttonIcon); } void TxRow::receiveRow(bool isLightTheme){ ui->lblAddress->setText("Received from DN6i46dytMPVhVBh7BZZD23"); ui->lblDate->setText("10/04/2019"); ui->lblAmount->setText("+0.00543 PIV"); ui->lblAmount->setProperty("cssClass", "text-list-amount-receive"); QPixmap pixmap(isLightTheme ? "://ic-transaction-received" : "://ic-transaction-received-dark"); QIcon buttonIcon(pixmap); ui->icon->setIcon(buttonIcon); } void TxRow::stakeRow(bool isLightTheme){ ui->lblAddress->setText("PIV Staked"); ui->lblDate->setText("10/04/2019"); ui->lblAmount->setText("+2.00 PIV"); ui->lblAmount->setProperty("cssClass", "text-list-amount-send"); QPixmap pixmap(isLightTheme ? "://ic-transaction-staked" : "://ic-transaction-staked-dark"); QIcon buttonIcon(pixmap); ui->icon->setIcon(buttonIcon); } void TxRow::zPIVStakeRow(bool isLightTheme){ ui->lblAddress->setText("zPIV Staked"); ui->lblDate->setText("10/04/2019"); ui->lblAmount->setText("+3.00 zPIV"); ui->lblAmount->setProperty("cssClass", "text-list-amount-send"); QPixmap pixmap(isLightTheme ? "://ic-transaction-staked" : "://ic-transaction-staked-dark"); QIcon buttonIcon(pixmap); ui->icon->setIcon(buttonIcon); } void TxRow::mintRow(bool isLightTheme){ ui->lblAddress->setText("Mint"); ui->lblDate->setText("10/04/2019"); ui->lblAmount->setText("+0.00 PIV"); ui->lblAmount->setProperty("cssClass", "text-list-amount-send"); QPixmap pixmap(isLightTheme ? "://ic-transaction-mint" : "://ic-transaction-mint-dark"); QIcon buttonIcon(pixmap); ui->icon->setIcon(buttonIcon); } <commit_msg>[GUI] dark theme invalid icons name fix.<commit_after>#include "qt/pivx/txrow.h" #include "qt/pivx/forms/ui_txrow.h" #include "guiutil.h" #include <iostream> TxRow::TxRow(bool isLightTheme, QWidget *parent) : QWidget(parent), ui(new Ui::TxRow) { ui->setupUi(this); setConfirmStatus(true); updateStatus(isLightTheme, false, false); } void TxRow::setConfirmStatus(bool isConfirm){ if(isConfirm){ ui->lblAddress->setProperty("cssClass", "text-list-body1"); ui->lblDate->setProperty("cssClass", "text-list-caption"); }else{ ui->lblAddress->setProperty("cssClass", "text-list-body-unconfirmed"); ui->lblDate->setProperty("cssClass","text-list-caption-unconfirmed"); } } void TxRow::updateStatus(bool isLightTheme, bool isHover, bool isSelected){ if(isLightTheme) ui->lblDivisory->setStyleSheet("background-color:#bababa"); else ui->lblDivisory->setStyleSheet("background-color:#40ffffff"); } void TxRow::setDate(QDateTime date){ ui->lblDate->setText(GUIUtil::dateTimeStr(date)); } void TxRow::setLabel(QString str){ ui->lblAddress->setText(str); } void TxRow::setAmount(QString str){ ui->lblAmount->setText(str); } // TODO: Agregar send to zPIV and receive zPIV icons.. void TxRow::setType(bool isLightTheme, int type, bool isConfirmed){ QString path; QString css; switch (type) { case TransactionRecord::ZerocoinMint: path = "://ic-transaction-mint"; css = "text-list-amount-send"; break; case TransactionRecord::Generated: case TransactionRecord::StakeZPIV: case TransactionRecord::MNReward: case TransactionRecord::StakeMint: path = "://ic-transaction-staked"; css = "text-list-amount-receive"; break; case TransactionRecord::RecvWithObfuscation: case TransactionRecord::RecvWithAddress: case TransactionRecord::RecvFromOther: case TransactionRecord::RecvFromZerocoinSpend: path = "://ic-transaction-received"; css = "text-list-amount-receive"; break; case TransactionRecord::SendToAddress: case TransactionRecord::SendToOther: case TransactionRecord::ZerocoinSpend: case TransactionRecord::ZerocoinSpend_Change_zPiv: case TransactionRecord::ZerocoinSpend_FromMe: path = "://ic-transaction-sent"; css = "text-list-amount-send"; break; case TransactionRecord::SendToSelf: path = "://ic-transaction-mint"; css = "text-list-amount-send"; break; default: path = ":/icons/tx_inout"; break; } if (!isLightTheme){ path += "-dark"; } if (!isConfirmed){ css = "text-list-amount-unconfirmed"; path += "-inactive"; setConfirmStatus(false); }else{ setConfirmStatus(true); } ui->lblAmount->setProperty("cssClass", css); ui->icon->setIcon(QIcon(path)); } TxRow::~TxRow() { delete ui; } void TxRow::sendRow(bool isLightTheme){ ui->lblAddress->setText("Sent to DN6i46dytMPV..hV1FuQBh7BZZ6nN"); ui->lblDate->setText("10/04/2019"); QPixmap pixmap(isLightTheme ? "://ic-transaction-sent" : "://ic-transaction-sent-dark"); ui->lblAmount->setText("-5.00 PIV"); ui->lblAmount->setProperty("cssClass", "text-list-amount-send"); QIcon buttonIcon(pixmap); ui->icon->setIcon(buttonIcon); } void TxRow::receiveRow(bool isLightTheme){ ui->lblAddress->setText("Received from DN6i46dytMPVhVBh7BZZD23"); ui->lblDate->setText("10/04/2019"); ui->lblAmount->setText("+0.00543 PIV"); ui->lblAmount->setProperty("cssClass", "text-list-amount-receive"); QPixmap pixmap(isLightTheme ? "://ic-transaction-received" : "://ic-transaction-received-dark"); QIcon buttonIcon(pixmap); ui->icon->setIcon(buttonIcon); } void TxRow::stakeRow(bool isLightTheme){ ui->lblAddress->setText("PIV Staked"); ui->lblDate->setText("10/04/2019"); ui->lblAmount->setText("+2.00 PIV"); ui->lblAmount->setProperty("cssClass", "text-list-amount-send"); QPixmap pixmap(isLightTheme ? "://ic-transaction-staked" : "://ic-transaction-staked-dark"); QIcon buttonIcon(pixmap); ui->icon->setIcon(buttonIcon); } void TxRow::zPIVStakeRow(bool isLightTheme){ ui->lblAddress->setText("zPIV Staked"); ui->lblDate->setText("10/04/2019"); ui->lblAmount->setText("+3.00 zPIV"); ui->lblAmount->setProperty("cssClass", "text-list-amount-send"); QPixmap pixmap(isLightTheme ? "://ic-transaction-staked" : "://ic-transaction-staked-dark"); QIcon buttonIcon(pixmap); ui->icon->setIcon(buttonIcon); } void TxRow::mintRow(bool isLightTheme){ ui->lblAddress->setText("Mint"); ui->lblDate->setText("10/04/2019"); ui->lblAmount->setText("+0.00 PIV"); ui->lblAmount->setProperty("cssClass", "text-list-amount-send"); QPixmap pixmap(isLightTheme ? "://ic-transaction-mint" : "://ic-transaction-mint-dark"); QIcon buttonIcon(pixmap); ui->icon->setIcon(buttonIcon); } <|endoftext|>
<commit_before><commit_msg>Solution for ElectrumX<commit_after><|endoftext|>
<commit_before>#ifndef COMPONENT_HPP #define COMPONENT_HPP #include "../MessageSystem/Observable.hpp" #include <string> namespace swift { class Component : public Observable { public: static std::string getType(); }; } #endif // COMPONENT_HPP <commit_msg>Made destructor default and virtual<commit_after>#ifndef COMPONENT_HPP #define COMPONENT_HPP #include "../MessageSystem/Observable.hpp" #include <string> namespace swift { class Component : public Observable { public: virtual ~Component() = default; static std::string getType(); }; } #endif // COMPONENT_HPP <|endoftext|>
<commit_before>#include "script/Script.h" #define XP_UNIX #include "jsapi.h" #undef XP_UNIX #include "log.h" static JSRuntime* rt = NULL; static JSClass scriptClassGlobal = { "global", JSCLASS_GLOBAL_FLAGS, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, JS_FinalizeStub, JSCLASS_NO_OPTIONAL_MEMBERS }; static void scriptReportError (JSContext* _ctx, const char* message, JSErrorReport* report) { LOGW("%s:%u:%s\n", report->filename ? report->filename : "<no filename>", (unsigned int) report->lineno, message); } static JSBool amity_log (JSContext* ctx, uintN argc, jsval* vp) { LOGI("amity_log %i", argc); JSString* message; if (!JS_ConvertArguments(ctx, argc, JS_ARGV(ctx, vp), "S", &message)) { return JS_FALSE; } LOGI("amity.log() -> %s", JS_EncodeString(ctx, message)); return JS_TRUE; } static JSClass scriptClassAmity = { "Amity", 0, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, JS_FinalizeStub, }; static JSFunctionSpec scriptClassAmity_staticMethods[] = { // JS_TN? JS_FS("log", amity_log, 1, 0), JS_FS_END }; static void scriptInitClasses (JSContext* ctx, JSObject* global) { JSObject* amity = JS_NewObject(ctx, &scriptClassAmity, NULL, global); JS_DefineProperty(ctx, global, "$amity", OBJECT_TO_JSVAL(amity), NULL, NULL, 0); JS_DefineFunctions(ctx, amity, scriptClassAmity_staticMethods); } Script::~Script () { if (_ctx != NULL) { JS_DestroyContext(_ctx); } } int Script::parse (const char* filename, const char* source) { LOGI("A"); if (rt == NULL) { LOGI("Creating runtime"); rt = JS_NewRuntime(8L * 1024L * 1024L); if (rt == NULL) { return 1; } } LOGI("B Creating context"); _ctx = JS_NewContext(rt, 8192); if (_ctx == NULL) { return 1; } LOGI("C setting options"); JS_SetOptions(_ctx, JSOPTION_STRICT | JSOPTION_WERROR | JSOPTION_VAROBJFIX | JSOPTION_NO_SCRIPT_RVAL | JSOPTION_JIT | JSOPTION_METHODJIT); JS_SetVersion(_ctx, JSVERSION_ECMA_5); JS_SetErrorReporter(_ctx, scriptReportError); LOGI("D creating global %s", scriptClassGlobal.name); JSObject* global = JS_NewGlobalObject(_ctx, &scriptClassGlobal); if (global == NULL) { return 1; } LOGI("E"); if (!JS_InitStandardClasses(_ctx, global)) { return 1; } JSBool success = JS_EvaluateScript(_ctx, global, source, strlen(source), filename, 0, NULL); return !success; } void Script::onEnterFrame (float dt) { // TODO: Call into js } <commit_msg>Disable some noisy logs, and create the $amity object.<commit_after>#include "script/Script.h" #define XP_UNIX #include "jsapi.h" #undef XP_UNIX #include "log.h" static JSRuntime* rt = NULL; static JSClass scriptClassGlobal = { "global", JSCLASS_GLOBAL_FLAGS, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, JS_FinalizeStub, JSCLASS_NO_OPTIONAL_MEMBERS }; static void scriptReportError (JSContext* _ctx, const char* message, JSErrorReport* report) { LOGW("%s:%u:%s\n", report->filename ? report->filename : "<no filename>", (unsigned int) report->lineno, message); } static JSBool amity_log (JSContext* ctx, uintN argc, jsval* vp) { JSString* message; if (!JS_ConvertArguments(ctx, argc, JS_ARGV(ctx, vp), "S", &message)) { return JS_FALSE; } LOGI("amity.log() -> %s", JS_EncodeString(ctx, message)); return JS_TRUE; } static JSClass scriptClassAmity = { "Amity", 0, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, JS_FinalizeStub, }; static JSFunctionSpec scriptClassAmity_staticMethods[] = { // JS_TN? JS_FS("log", amity_log, 1, 0), JS_FS_END }; static void scriptInitClasses (JSContext* ctx, JSObject* global) { JSObject* amity = JS_NewObject(ctx, &scriptClassAmity, NULL, global); JS_DefineProperty(ctx, global, "$amity", OBJECT_TO_JSVAL(amity), NULL, NULL, 0); JS_DefineFunctions(ctx, amity, scriptClassAmity_staticMethods); } Script::~Script () { if (_ctx != NULL) { JS_DestroyContext(_ctx); } } int Script::parse (const char* filename, const char* source) { if (rt == NULL) { LOGI("Creating runtime"); rt = JS_NewRuntime(8L * 1024L * 1024L); if (rt == NULL) { return 1; } } _ctx = JS_NewContext(rt, 8192); if (_ctx == NULL) { return 1; } JS_SetOptions(_ctx, JSOPTION_STRICT | JSOPTION_WERROR | JSOPTION_VAROBJFIX | JSOPTION_NO_SCRIPT_RVAL | JSOPTION_JIT | JSOPTION_METHODJIT); JS_SetVersion(_ctx, JSVERSION_ECMA_5); JS_SetErrorReporter(_ctx, scriptReportError); JSObject* global = JS_NewGlobalObject(_ctx, &scriptClassGlobal); if (global == NULL) { return 1; } if (!JS_InitStandardClasses(_ctx, global)) { return 1; } scriptInitClasses(_ctx, global); JSBool success = JS_EvaluateScript(_ctx, global, source, strlen(source), filename, 0, NULL); return !success; } void Script::onEnterFrame (float dt) { // TODO: Call into js } <|endoftext|>
<commit_before>// This is an independent project of an individual developer. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com /** * File: BarPeriod.cpp * Author: kan * * Created on 11.11.2015. */ #include <cmath> #include <time.h> #include <stddef.h> #include <cassert> #include <sstream> #include "Comparers.h" #include "DelphisRound.h" #include "BarPeriod.h" #include "BasisOfStrategy.h" //------------------------------------------------------------------------------------------ const std::string whitespaces (" \t\f\v\n\r"); std::string trim( const std::string& str ) { const size_t first = str.find_first_not_of( whitespaces ); if( std::string::npos == first ) { return str; } const size_t last = str.find_last_not_of( whitespaces ); return str.substr(first, (last - first + 1)); } //------------------------------------------------------------------------------------------ bool IsOneDay( const TInnerDate aLeft, const TInnerDate aRight) { return Trunc( aLeft / gOneDay ) == Trunc( aRight / gOneDay ); } //------------------------------------------------------------------------------------------ bool IsOneHour( const TInnerDate aLeft, const TInnerDate aRight, const double aDuration ) { assert( isPositiveValue( aDuration ) ); return IsLess( std::fabs( aLeft - aRight ), gOneHour*aDuration + 1.0 ); } //------------------------------------------------------------------------------------------ bool IsValidBar( const TSimpleBar & aBar ) { return IsGreat( aBar.Volume, -2.0 * gAbsoluteZero ) // >= 0 and IsValidPrice( aBar.Open ) and IsValidPrice( aBar.High ) and IsValidPrice( aBar.Low ) and IsValidPrice( aBar.Close ); } //------------------------------------------------------------------------------------------ #define FAST_DECODER( aField ) \ for( std::size_t lRowNum = 0; lRowNum < aBar.size(); ++lRowNum ) { \ TSimpleBar lBar = aBar[ lRowNum ]; \ TPrice lPrice = lBar.aField; \ TSimpleTick lTick { lBar.DateTime, lPrice, lBar.Volume }; \ lResult[ lRowNum ] = lTick; \ } \ // end of FAST_DECODER TPriceSeries BarsToPriceSeries( const TBarSeries &aBar, const TMAPoint aType ) { TPriceSeries lResult( aBar.size() ); switch ( aType ) { ///////// case TMAPoint::MAP_Close : { FAST_DECODER( Close ); } break ; ///////// case TMAPoint::MAP_Mid : { for( std::size_t lRowNum = 0; lRowNum < aBar.size(); ++lRowNum ) { TSimpleBar lBar = aBar[ lRowNum ]; TPrice lPrice = ( lBar.High + lBar.Low ) / 2.0 ; TSimpleTick lTick { lBar.DateTime, lPrice, lBar.Volume }; lResult[ lRowNum ] = lTick; } } break ; ///////// case TMAPoint::MAP_Triple : { for( std::size_t lRowNum = 0; lRowNum < aBar.size(); ++lRowNum ) { TSimpleBar lBar = aBar[ lRowNum ]; TPrice lPrice = ( lBar.High + lBar.Low + lBar.Close ) / 3.0 ; TSimpleTick lTick { lBar.DateTime, lPrice, lBar.Volume }; lResult[ lRowNum ] = lTick; } } break ; ///////// case TMAPoint::MAP_Open : { FAST_DECODER( Open ); } break ; ///////// case TMAPoint::MAP_High : { FAST_DECODER( High ); } break ; ///////// case TMAPoint::MAP_Low : { FAST_DECODER( Low ); } break ; ///////// case TMAPoint::MAP_Volume : { FAST_DECODER( Volume ); } break ; } return lResult; } //------------------------------------------------------------------------------------------ void Reset( TSimpleBar &aBar ) { aBar.DateTime = gStartingTime; aBar.Open = 0.0; aBar.High = 0.0; aBar.Low = 0.0; aBar.Close = 0.0; aBar.Volume = -1.0; } //------------------------------------------------------------------------------------------ TBarSeries _CreateBars( const TBarSeries & aBars, const TBarPeriod aBarPeriod ) { const double lOutBarPeriod = getBarPeriodLength( aBarPeriod );//0.0; TBarSeries oResuiltBarSeries; TSimpleBar lOutBar; Reset( lOutBar ); int GlobalBarIndex = 0; for( size_t i = 0; i < aBars.size( ); i++ ) { const TSimpleBar lCurrentBar = aBars[ i ]; const TInnerDate lBarTime = lCurrentBar.DateTime; const int lCurrentBarIndex = Trunc( ( lBarTime - gStartingTime ) / lOutBarPeriod ); if( lCurrentBarIndex != GlobalBarIndex ) { if( GlobalBarIndex != 0 ) { lOutBar.DateTime = GlobalBarIndex * lOutBarPeriod + gStartingTime; oResuiltBarSeries.push_back( lOutBar ); Reset( lOutBar ); } GlobalBarIndex = lCurrentBarIndex; } lOutBar = lOutBar + lCurrentBar; if( ( aBars.size( ) - i ) == 1 ) { lOutBar.DateTime = lCurrentBarIndex * lOutBarPeriod + gStartingTime; oResuiltBarSeries.push_back( lOutBar ); Reset( lOutBar ); } } return oResuiltBarSeries; } //------------------------------------------------------------------------------------------ TSimpleBar operator+( const TSimpleBar &aStarBar, const TSimpleBar &aEndBar ) { if( not IsValidBar( aEndBar ) ) { return aStarBar; } if( not IsValidBar( aStarBar ) ) { return aEndBar; } const double lOpen = aStarBar.Open; const double lHigh = IsGreat( aStarBar.High, aEndBar.High ) ? aStarBar.High : aEndBar.High ; const double lLow = IsLess( aStarBar.Low, aEndBar.Low ) ? aStarBar.Low : aEndBar.Low; const double lClose = aEndBar.Close; const double lVolume = aStarBar.Volume + aEndBar.Volume; const TSimpleBar lOutBar{ aStarBar.DateTime, lOpen, lHigh, lLow, lClose, lVolume }; return lOutBar; } //------------------------------------------------------------------------------------------ std::string DateToStr( const TInnerDate aDate ) { const time_t lTime = Round( aDate ); const std::string lStrTime( ctime( &lTime ) ); return trim( lStrTime ); } //------------------------------------------------------------------------------------------ TInnerTime ITime( const TInnerDate aDate ) { // const time_t lTime = Round( aDate ); // struct tm * ltimeinfo = localtime (&lTime); // return ltimeinfo->tm_hour * 3600 + ltimeinfo->tm_min * 60 + ltimeinfo->tm_sec; return ToDouble(ToInt(aDate) % ToInt(gOneDay)); } //------------------------------------------------------------------------------------------ TInnerTime ITime( const std::string& aTime ) { std::string s{aTime}; const std::string delimiter{":"}; int lHours; size_t pos = 0; if ((pos = s.find(delimiter)) != std::string::npos) { lHours = std::stoi(s.substr(0, pos)); s.erase(0, pos + delimiter.length()); } else { return 0.0; } if ((pos = s.find(delimiter)) != std::string::npos) { int lMinutes = std::stoi(s.substr(0, pos)); s.erase(0, pos + delimiter.length()); int lSeconds = std::stoi(s.substr(0, pos)); return ToDouble(lHours * 3600 + lMinutes * 60 + lSeconds); } else { int lMinutes = std::stoi(s); return ToDouble(lHours * 3600 + lMinutes * 60); } } //------------------------------------------------------------------------------------------ std::ostream& operator<<( std::ostream &out, const TSimpleBar &aBar ) { std::stringstream strm; strm << DateToStr( aBar.DateTime ) << "\t" << aBar.Open << "\t" << aBar.High << "\t" << aBar.Low << "\t" << aBar.Close << "\t" << aBar.Volume ; return out << strm.str(); } //------------------------------------------------------------------------------------------ std::ostream& operator<<( std::ostream &out, const TSimpleTick &aTick ) { std::stringstream strm; strm << DateToStr( aTick.DateTime ) << "\t" << aTick.Price << "\t" << aTick.Volume ; return out << strm.str(); } //------------------------------------------------------------------------------------------ TPrice RoundTo( const TPrice aPrice, const TPrice aPriceStep ) { assert( isPositiveValue( aPriceStep ) ); return std::round( aPrice / aPriceStep ) * aPriceStep ; } //------------------------------------------------------------------------------------------ TPrice TruncTo( const TPrice aPrice, const TPrice aPriceStep ) { assert( isPositiveValue( aPriceStep ) ); return std::trunc( aPrice / aPriceStep ) * aPriceStep ; } //------------------------------------------------------------------------------------------ TPrice CeilTo( const TPrice aPrice, const TPrice aPriceStep ) { assert( isPositiveValue( aPriceStep ) ); return std::ceil( aPrice / aPriceStep ) * aPriceStep ; } //------------------------------------------------------------------------------------------ <commit_msg>[*] IsOneHour<commit_after>// This is an independent project of an individual developer. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com /** * File: BarPeriod.cpp * Author: kan * * Created on 11.11.2015. */ #include <cmath> #include <time.h> #include <stddef.h> #include <cassert> #include <sstream> #include "Comparers.h" #include "DelphisRound.h" #include "BarPeriod.h" #include "BasisOfStrategy.h" //------------------------------------------------------------------------------------------ const std::string whitespaces (" \t\f\v\n\r"); std::string trim( const std::string& str ) { const size_t first = str.find_first_not_of( whitespaces ); if( std::string::npos == first ) { return str; } const size_t last = str.find_last_not_of( whitespaces ); return str.substr(first, (last - first + 1)); } //------------------------------------------------------------------------------------------ bool IsOneDay( const TInnerDate aLeft, const TInnerDate aRight) { return Trunc( aLeft / gOneDay ) == Trunc( aRight / gOneDay ); } //------------------------------------------------------------------------------------------ bool IsOneHour( const TInnerDate aLeft, const TInnerDate aRight, const double aDuration ) { assert( isPositiveValue( aDuration ) ); //return IsLess( std::fabs( aLeft - aRight ), gOneHour*aDuration + 1.0 ); return Trunc( aLeft / (gOneHour*aDuration) ) == Trunc( aRight / (gOneHour*aDuration) ); } //------------------------------------------------------------------------------------------ bool IsValidBar( const TSimpleBar & aBar ) { return IsGreat( aBar.Volume, -2.0 * gAbsoluteZero ) // >= 0 and IsValidPrice( aBar.Open ) and IsValidPrice( aBar.High ) and IsValidPrice( aBar.Low ) and IsValidPrice( aBar.Close ); } //------------------------------------------------------------------------------------------ #define FAST_DECODER( aField ) \ for( std::size_t lRowNum = 0; lRowNum < aBar.size(); ++lRowNum ) { \ TSimpleBar lBar = aBar[ lRowNum ]; \ TPrice lPrice = lBar.aField; \ TSimpleTick lTick { lBar.DateTime, lPrice, lBar.Volume }; \ lResult[ lRowNum ] = lTick; \ } \ // end of FAST_DECODER TPriceSeries BarsToPriceSeries( const TBarSeries &aBar, const TMAPoint aType ) { TPriceSeries lResult( aBar.size() ); switch ( aType ) { ///////// case TMAPoint::MAP_Close : { FAST_DECODER( Close ); } break ; ///////// case TMAPoint::MAP_Mid : { for( std::size_t lRowNum = 0; lRowNum < aBar.size(); ++lRowNum ) { TSimpleBar lBar = aBar[ lRowNum ]; TPrice lPrice = ( lBar.High + lBar.Low ) / 2.0 ; TSimpleTick lTick { lBar.DateTime, lPrice, lBar.Volume }; lResult[ lRowNum ] = lTick; } } break ; ///////// case TMAPoint::MAP_Triple : { for( std::size_t lRowNum = 0; lRowNum < aBar.size(); ++lRowNum ) { TSimpleBar lBar = aBar[ lRowNum ]; TPrice lPrice = ( lBar.High + lBar.Low + lBar.Close ) / 3.0 ; TSimpleTick lTick { lBar.DateTime, lPrice, lBar.Volume }; lResult[ lRowNum ] = lTick; } } break ; ///////// case TMAPoint::MAP_Open : { FAST_DECODER( Open ); } break ; ///////// case TMAPoint::MAP_High : { FAST_DECODER( High ); } break ; ///////// case TMAPoint::MAP_Low : { FAST_DECODER( Low ); } break ; ///////// case TMAPoint::MAP_Volume : { FAST_DECODER( Volume ); } break ; } return lResult; } //------------------------------------------------------------------------------------------ void Reset( TSimpleBar &aBar ) { aBar.DateTime = gStartingTime; aBar.Open = 0.0; aBar.High = 0.0; aBar.Low = 0.0; aBar.Close = 0.0; aBar.Volume = -1.0; } //------------------------------------------------------------------------------------------ TBarSeries _CreateBars( const TBarSeries & aBars, const TBarPeriod aBarPeriod ) { const double lOutBarPeriod = getBarPeriodLength( aBarPeriod );//0.0; TBarSeries oResuiltBarSeries; TSimpleBar lOutBar; Reset( lOutBar ); int GlobalBarIndex = 0; for( size_t i = 0; i < aBars.size( ); i++ ) { const TSimpleBar lCurrentBar = aBars[ i ]; const TInnerDate lBarTime = lCurrentBar.DateTime; const int lCurrentBarIndex = Trunc( ( lBarTime - gStartingTime ) / lOutBarPeriod ); if( lCurrentBarIndex != GlobalBarIndex ) { if( GlobalBarIndex != 0 ) { lOutBar.DateTime = GlobalBarIndex * lOutBarPeriod + gStartingTime; oResuiltBarSeries.push_back( lOutBar ); Reset( lOutBar ); } GlobalBarIndex = lCurrentBarIndex; } lOutBar = lOutBar + lCurrentBar; if( ( aBars.size( ) - i ) == 1 ) { lOutBar.DateTime = lCurrentBarIndex * lOutBarPeriod + gStartingTime; oResuiltBarSeries.push_back( lOutBar ); Reset( lOutBar ); } } return oResuiltBarSeries; } //------------------------------------------------------------------------------------------ TSimpleBar operator+( const TSimpleBar &aStarBar, const TSimpleBar &aEndBar ) { if( not IsValidBar( aEndBar ) ) { return aStarBar; } if( not IsValidBar( aStarBar ) ) { return aEndBar; } const double lOpen = aStarBar.Open; const double lHigh = IsGreat( aStarBar.High, aEndBar.High ) ? aStarBar.High : aEndBar.High ; const double lLow = IsLess( aStarBar.Low, aEndBar.Low ) ? aStarBar.Low : aEndBar.Low; const double lClose = aEndBar.Close; const double lVolume = aStarBar.Volume + aEndBar.Volume; const TSimpleBar lOutBar{ aStarBar.DateTime, lOpen, lHigh, lLow, lClose, lVolume }; return lOutBar; } //------------------------------------------------------------------------------------------ std::string DateToStr( const TInnerDate aDate ) { const time_t lTime = Round( aDate ); const std::string lStrTime( ctime( &lTime ) ); return trim( lStrTime ); } //------------------------------------------------------------------------------------------ TInnerTime ITime( const TInnerDate aDate ) { // const time_t lTime = Round( aDate ); // struct tm * ltimeinfo = localtime (&lTime); // return ltimeinfo->tm_hour * 3600 + ltimeinfo->tm_min * 60 + ltimeinfo->tm_sec; return ToDouble(ToInt(aDate) % ToInt(gOneDay)); } //------------------------------------------------------------------------------------------ TInnerTime ITime( const std::string& aTime ) { std::string s{aTime}; const std::string delimiter{":"}; int lHours; size_t pos = 0; if ((pos = s.find(delimiter)) != std::string::npos) { lHours = std::stoi(s.substr(0, pos)); s.erase(0, pos + delimiter.length()); } else { return 0.0; } if ((pos = s.find(delimiter)) != std::string::npos) { int lMinutes = std::stoi(s.substr(0, pos)); s.erase(0, pos + delimiter.length()); int lSeconds = std::stoi(s.substr(0, pos)); return ToDouble(lHours * 3600 + lMinutes * 60 + lSeconds); } else { int lMinutes = std::stoi(s); return ToDouble(lHours * 3600 + lMinutes * 60); } } //------------------------------------------------------------------------------------------ std::ostream& operator<<( std::ostream &out, const TSimpleBar &aBar ) { std::stringstream strm; strm << DateToStr( aBar.DateTime ) << "\t" << aBar.Open << "\t" << aBar.High << "\t" << aBar.Low << "\t" << aBar.Close << "\t" << aBar.Volume ; return out << strm.str(); } //------------------------------------------------------------------------------------------ std::ostream& operator<<( std::ostream &out, const TSimpleTick &aTick ) { std::stringstream strm; strm << DateToStr( aTick.DateTime ) << "\t" << aTick.Price << "\t" << aTick.Volume ; return out << strm.str(); } //------------------------------------------------------------------------------------------ TPrice RoundTo( const TPrice aPrice, const TPrice aPriceStep ) { assert( isPositiveValue( aPriceStep ) ); return std::round( aPrice / aPriceStep ) * aPriceStep ; } //------------------------------------------------------------------------------------------ TPrice TruncTo( const TPrice aPrice, const TPrice aPriceStep ) { assert( isPositiveValue( aPriceStep ) ); return std::trunc( aPrice / aPriceStep ) * aPriceStep ; } //------------------------------------------------------------------------------------------ TPrice CeilTo( const TPrice aPrice, const TPrice aPriceStep ) { assert( isPositiveValue( aPriceStep ) ); return std::ceil( aPrice / aPriceStep ) * aPriceStep ; } //------------------------------------------------------------------------------------------ <|endoftext|>
<commit_before>// Copyright 2016 Alessio Sclocco <a.sclocco@vu.nl> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <vector> #include <iostream> #include <exception> #include <iomanip> #include <ctime> #include <algorithm> #include <configuration.hpp> #include <ArgumentList.hpp> #include <InitializeOpenCL.hpp> #include <Kernel.hpp> #include <Correlator.hpp> #include <utils.hpp> #include <Timer.hpp> #include <Stats.hpp> const unsigned int magicValue = 42; void initializeDeviceMemory(cl::Context & clContext, cl::CommandQueue * clQueue, std::vector< inputDataType > * input, cl::Buffer * input_d, cl::Buffer * output_d); int main(int argc, char * argv[]) { bool reInit = true; unsigned int padding = 0; unsigned int nrIterations = 0; unsigned int clPlatformID = 0; unsigned int clDeviceID = 0; unsigned int vectorSize = 0; unsigned int maxThreads = 0; unsigned int maxItems = 0; unsigned int nrChannels = 0; unsigned int nrStations = 0; unsigned int nrSamples = 0; isa::OpenCL::KernelConf conf; try { isa::utils::ArgumentList args(argc, argv); clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform"); clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device"); padding = args.getSwitchArgument< unsigned int >("-padding"); nrIterations = args.getSwitchArgument< unsigned int >("-iterations"); vectorSize = args.getSwitchArgument< unsigned int >("-vector"); maxThreads = args.getSwitchArgument< unsigned int >("-max_threads"); maxItems = args.getSwitchArgument< unsigned int >("-max_items"); nrChannels = args.getSwitchArgument< unsigned int >("-channels"); nrStations = args.getSwitchArgument< unsigned int >("-stations"); nrSamples = args.getSwitchArgument< unsigned int >("-samples"); } catch ( isa::utils::EmptyCommandLine & err ) { std::cerr << argv[0] << " -opencl_platform ... -opencl_device ... -padding ... -iterations ... -vector ... -max_threads ... -max_items ... -channels ... -stations ... -samples ..." << std::endl; return 1; } catch ( std::exception & err ) { std::cerr << err.what() << std::endl; return 1; } cl::Context clContext; std::vector< cl::Platform > * clPlatforms = new std::vector< cl::Platform >(); std::vector< cl::Device > * clDevices = new std::vector< cl::Device >(); std::vector< std::vector< cl::CommandQueue > > * clQueues = 0; // Allocate host memory unsigned int nrBaselines = (nrStations * (nrStations + 1)) / 2; std::vector< inputDataType > input(nrChannels * nrStations * nrSamples * nrPolarizations * 2), output(nrChannels * nrBaselines * nrPolarizations * nrPolarizations * 2), output_c(nrChannels * nrBaselines * nrPolarizations * nrPolarizations * 2); cl::Buffer input_d, output_d; // Populate data structures srand(time(0)); for ( unsigned int channel = 0; channel < nrChannels; channel++ ) { for ( unsigned int station = 0; station < nrStations; station++ ) { for ( unsigned int sample = 0; sample < nrSamples; sample++ ) { for ( unsigned int polarization = 0; polarization < nrPolarizations; polarization++ ) { input[(channel * nrStations * nrSamples * nrPolarizations * 2) + (station * nrSamples * nrPolarizations * 2) + (sample * nrPolarizations * 2) + (polarization * 2)] = rand() % magicValue; input[(channel * nrStations * nrSamples * nrPolarizations * 2) + (station * nrSamples * nrPolarizations * 2) + (sample * nrPolarizations * 2) + (polarization * 2) + 1] = rand() % magicValue; } } } } // Compute CPU control results std::fill(output.begin(), output.end(), 0); TuneBench::correlator(input, output_c, nrChannels, nrStations, nrSamples, nrPolarizations); std::cout << std::fixed << std::endl; std::cout << "# nrChannels nrStations nrSamples nrPolarizations nrThreadsD0 nrItemsD0 nrItemsD1 GFLOP/s time stdDeviation COV" << std::endl << std::endl; for ( unsigned int threads = vectorSize; threads <= maxThreads; threads += vectorSize ) { conf.setNrThreadsD0(threads); for ( unsigned int items = 1; items <= maxItems; items++ ) { conf.setNrItemsD0(items); if ( nrSamples % (conf.getNrThreadsD0() * conf.getNrItemsD0()) != 0 ) { continue; } for ( unsigned int items = 1; (1 + (5 * conf.getNrItemsD1()) + (8 * ((conf.getNrItemsD1() * (conf.getNrItemsD1() + 1)) / 2))) <= maxItems; items++ ) { conf.setNrItemsD1(items); if ( nrStations % (conf.getNrItemsD1()) != 0 ) { continue; } // Generate kernel double gflops = isa::utils::giga(static_cast< uint64_t >(nrChannels) * nrSamples * nrBaselines * 32); cl::Event clEvent; cl::Kernel * kernel; isa::utils::Timer timer; std::string * code = TuneBench::getCorrelatorOpenCL(conf, inputDataName, padding, nrChannels, nrStations, nrSamples, nrPolarizations); if ( reInit ) { delete clQueues; clQueues = new std::vector< std::vector< cl::CommandQueue > >(); isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, &clContext, clDevices, clQueues); try { initializeDeviceMemory(clContext, &(clQueues->at(clDeviceID)[0]), &input, &input_d, &output_d); } catch ( cl::Error & err ) { return -1; } reInit = false; } try { kernel = isa::OpenCL::compile("correlator", *code, "-cl-mad-enable -Werror", clContext, clDevices->at(clDeviceID)); } catch ( isa::OpenCL::OpenCLError & err ) { std::cerr << err.what() << std::endl; delete code; break; } delete code; cl::NDRange global(nrSamples / conf.getNrItemsD0(), nrStations / conf.getNrItemsD1(), nrChannels); cl::NDRange local(conf.getNrThreadsD0(), 1, 1); kernel->setArg(0, input_d); kernel->setArg(1, output_d); try { // Warm-up run clQueues->at(clDeviceID)[0].finish(); clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &clEvent); clEvent.wait(); // Tuning runs for ( unsigned int iteration = 0; iteration < nrIterations; iteration++ ) { timer.start(); clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &clEvent); clEvent.wait(); timer.stop(); } clQueues->at(clDeviceID)[0].enqueueReadBuffer(output_d, CL_TRUE, 0, output.size() * sizeof(inputDataType), reinterpret_cast< void * >(output.data()), 0, &clEvent); clEvent.wait(); } catch ( cl::Error & err ) { reInit = true; std::cerr << "OpenCL kernel execution error ("; std::cerr << conf.print(); std::cerr << "): "; std::cerr << isa::utils::toString(err.err()) << std::endl; delete kernel; if ( err.err() == -4 || err.err() == -61 ) { return -1; } break; } delete kernel; bool error = false; for ( unsigned int item = 0; item < output_c.size(); item++ ) { if ( !isa::utils::same(output[item], output_c[item]) ) { std::cerr << "Output error (" << conf.print() << ")." << std::endl; error = true; break; } } if ( error ) { continue; } std::cout << nrChannels << " " << nrStations << " " << nrSamples << " " << nrPolarizations << " " ; std::cout << conf.print() << " "; std::cout << std::setprecision(3); std::cout << gflops / timer.getAverageTime() << " "; std::cout << std::setprecision(6); std::cout << timer.getAverageTime() << " " << timer.getStandardDeviation() << " " << timer.getCoefficientOfVariation() << std::endl; } } } std::cout << std::endl; return 0; } void initializeDeviceMemory(cl::Context & clContext, cl::CommandQueue * clQueue, std::vector< inputDataType > * input, cl::Buffer * input_d, cl::Buffer * output_d) { try { *input_d = cl::Buffer(clContext, CL_MEM_READ_ONLY, input->size() * sizeof(inputDataType), 0, 0); *output_d = cl::Buffer(clContext, CL_MEM_WRITE_ONLY, input->size() * sizeof(inputDataType), 0, 0); clQueue->enqueueWriteBuffer(*input_d, CL_FALSE, 0, input->size() * sizeof(inputDataType), reinterpret_cast< void * >(input->data())); clQueue->finish(); } catch ( cl::Error & err ) { std::cerr << "OpenCL error (memory initialization): " << isa::utils::toString(err.err()) << "." << std::endl; throw; } } <commit_msg>Error in the items constraint.<commit_after>// Copyright 2016 Alessio Sclocco <a.sclocco@vu.nl> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <vector> #include <iostream> #include <exception> #include <iomanip> #include <ctime> #include <algorithm> #include <configuration.hpp> #include <ArgumentList.hpp> #include <InitializeOpenCL.hpp> #include <Kernel.hpp> #include <Correlator.hpp> #include <utils.hpp> #include <Timer.hpp> #include <Stats.hpp> const unsigned int magicValue = 42; void initializeDeviceMemory(cl::Context & clContext, cl::CommandQueue * clQueue, std::vector< inputDataType > * input, cl::Buffer * input_d, cl::Buffer * output_d); int main(int argc, char * argv[]) { bool reInit = true; unsigned int padding = 0; unsigned int nrIterations = 0; unsigned int clPlatformID = 0; unsigned int clDeviceID = 0; unsigned int vectorSize = 0; unsigned int maxThreads = 0; unsigned int maxItems = 0; unsigned int nrChannels = 0; unsigned int nrStations = 0; unsigned int nrSamples = 0; isa::OpenCL::KernelConf conf; try { isa::utils::ArgumentList args(argc, argv); clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform"); clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device"); padding = args.getSwitchArgument< unsigned int >("-padding"); nrIterations = args.getSwitchArgument< unsigned int >("-iterations"); vectorSize = args.getSwitchArgument< unsigned int >("-vector"); maxThreads = args.getSwitchArgument< unsigned int >("-max_threads"); maxItems = args.getSwitchArgument< unsigned int >("-max_items"); nrChannels = args.getSwitchArgument< unsigned int >("-channels"); nrStations = args.getSwitchArgument< unsigned int >("-stations"); nrSamples = args.getSwitchArgument< unsigned int >("-samples"); } catch ( isa::utils::EmptyCommandLine & err ) { std::cerr << argv[0] << " -opencl_platform ... -opencl_device ... -padding ... -iterations ... -vector ... -max_threads ... -max_items ... -channels ... -stations ... -samples ..." << std::endl; return 1; } catch ( std::exception & err ) { std::cerr << err.what() << std::endl; return 1; } cl::Context clContext; std::vector< cl::Platform > * clPlatforms = new std::vector< cl::Platform >(); std::vector< cl::Device > * clDevices = new std::vector< cl::Device >(); std::vector< std::vector< cl::CommandQueue > > * clQueues = 0; // Allocate host memory unsigned int nrBaselines = (nrStations * (nrStations + 1)) / 2; std::vector< inputDataType > input(nrChannels * nrStations * nrSamples * nrPolarizations * 2), output(nrChannels * nrBaselines * nrPolarizations * nrPolarizations * 2), output_c(nrChannels * nrBaselines * nrPolarizations * nrPolarizations * 2); cl::Buffer input_d, output_d; // Populate data structures srand(time(0)); for ( unsigned int channel = 0; channel < nrChannels; channel++ ) { for ( unsigned int station = 0; station < nrStations; station++ ) { for ( unsigned int sample = 0; sample < nrSamples; sample++ ) { for ( unsigned int polarization = 0; polarization < nrPolarizations; polarization++ ) { input[(channel * nrStations * nrSamples * nrPolarizations * 2) + (station * nrSamples * nrPolarizations * 2) + (sample * nrPolarizations * 2) + (polarization * 2)] = rand() % magicValue; input[(channel * nrStations * nrSamples * nrPolarizations * 2) + (station * nrSamples * nrPolarizations * 2) + (sample * nrPolarizations * 2) + (polarization * 2) + 1] = rand() % magicValue; } } } } // Compute CPU control results std::fill(output.begin(), output.end(), 0); TuneBench::correlator(input, output_c, nrChannels, nrStations, nrSamples, nrPolarizations); std::cout << std::fixed << std::endl; std::cout << "# nrChannels nrStations nrSamples nrPolarizations nrThreadsD0 nrItemsD0 nrItemsD1 GFLOP/s time stdDeviation COV" << std::endl << std::endl; for ( unsigned int threads = vectorSize; threads <= maxThreads; threads += vectorSize ) { conf.setNrThreadsD0(threads); for ( unsigned int items = 1; items <= maxItems; items++ ) { conf.setNrItemsD0(items); if ( nrSamples % (conf.getNrThreadsD0() * conf.getNrItemsD0()) != 0 ) { continue; } for ( unsigned int items = 1; (1 + (5 * items) + (8 * ((items * (items + 1)) / 2))) <= maxItems; items++ ) { conf.setNrItemsD1(items); if ( nrStations % (conf.getNrItemsD1()) != 0 ) { continue; } // Generate kernel double gflops = isa::utils::giga(static_cast< uint64_t >(nrChannels) * nrSamples * nrBaselines * 32); cl::Event clEvent; cl::Kernel * kernel; isa::utils::Timer timer; std::string * code = TuneBench::getCorrelatorOpenCL(conf, inputDataName, padding, nrChannels, nrStations, nrSamples, nrPolarizations); if ( reInit ) { delete clQueues; clQueues = new std::vector< std::vector< cl::CommandQueue > >(); isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, &clContext, clDevices, clQueues); try { initializeDeviceMemory(clContext, &(clQueues->at(clDeviceID)[0]), &input, &input_d, &output_d); } catch ( cl::Error & err ) { return -1; } reInit = false; } try { kernel = isa::OpenCL::compile("correlator", *code, "-cl-mad-enable -Werror", clContext, clDevices->at(clDeviceID)); } catch ( isa::OpenCL::OpenCLError & err ) { std::cerr << err.what() << std::endl; delete code; break; } delete code; cl::NDRange global(nrSamples / conf.getNrItemsD0(), nrStations / conf.getNrItemsD1(), nrChannels); cl::NDRange local(conf.getNrThreadsD0(), 1, 1); kernel->setArg(0, input_d); kernel->setArg(1, output_d); try { // Warm-up run clQueues->at(clDeviceID)[0].finish(); clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &clEvent); clEvent.wait(); // Tuning runs for ( unsigned int iteration = 0; iteration < nrIterations; iteration++ ) { timer.start(); clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &clEvent); clEvent.wait(); timer.stop(); } clQueues->at(clDeviceID)[0].enqueueReadBuffer(output_d, CL_TRUE, 0, output.size() * sizeof(inputDataType), reinterpret_cast< void * >(output.data()), 0, &clEvent); clEvent.wait(); } catch ( cl::Error & err ) { reInit = true; std::cerr << "OpenCL kernel execution error ("; std::cerr << conf.print(); std::cerr << "): "; std::cerr << isa::utils::toString(err.err()) << std::endl; delete kernel; if ( err.err() == -4 || err.err() == -61 ) { return -1; } break; } delete kernel; bool error = false; for ( unsigned int item = 0; item < output_c.size(); item++ ) { if ( !isa::utils::same(output[item], output_c[item]) ) { std::cerr << "Output error (" << conf.print() << ")." << std::endl; error = true; break; } } if ( error ) { continue; } std::cout << nrChannels << " " << nrStations << " " << nrSamples << " " << nrPolarizations << " " ; std::cout << conf.print() << " "; std::cout << std::setprecision(3); std::cout << gflops / timer.getAverageTime() << " "; std::cout << std::setprecision(6); std::cout << timer.getAverageTime() << " " << timer.getStandardDeviation() << " " << timer.getCoefficientOfVariation() << std::endl; } } } std::cout << std::endl; return 0; } void initializeDeviceMemory(cl::Context & clContext, cl::CommandQueue * clQueue, std::vector< inputDataType > * input, cl::Buffer * input_d, cl::Buffer * output_d) { try { *input_d = cl::Buffer(clContext, CL_MEM_READ_ONLY, input->size() * sizeof(inputDataType), 0, 0); *output_d = cl::Buffer(clContext, CL_MEM_WRITE_ONLY, input->size() * sizeof(inputDataType), 0, 0); clQueue->enqueueWriteBuffer(*input_d, CL_FALSE, 0, input->size() * sizeof(inputDataType), reinterpret_cast< void * >(input->data())); clQueue->finish(); } catch ( cl::Error & err ) { std::cerr << "OpenCL error (memory initialization): " << isa::utils::toString(err.err()) << "." << std::endl; throw; } } <|endoftext|>
<commit_before>/* NUI3 - C++ cross-platform GUI framework for OpenGL based applications Copyright (C) 2002-2003 Sebastien Metrot licence: see nui3/LICENCE.TXT */ #include "nui.h" #include "nuiDrawContext.h" #include "nuiImageSequence.h" nuiImageSequence::nuiImageSequence() : nuiWidget(), mFrameIndex(0) { if (SetObjectClass(_T("nuiImageSequence"))) InitAttributes(); mColor = nuiColor(255,255,255); mInterpolated = true; mNbFrames = 0; mpTempImage = NULL; mRefreshTextures = true; mUseAlpha = false; } nuiImageSequence::nuiImageSequence(uint32 nbFrames, nglImage* pImage, nuiOrientation orientation, const nuiColor& rColor) : nuiWidget(), mFrameIndex(0), mColor(rColor) { if (SetObjectClass(_T("nuiImageSequence"))) InitAttributes(); mInterpolated = true; mNbFrames = nbFrames; mOrientation = orientation; mpTempImage = new nglImage(*pImage); mRefreshTextures = true; mUseAlpha = false; } nuiImageSequence::nuiImageSequence(uint32 nbFrames, const nglPath& rTexturePath, nuiOrientation orientation, const nuiColor& rColor) : nuiWidget(), mFrameIndex(0), mColor(rColor), mGlobalTexturePath(rTexturePath) { if (SetObjectClass(_T("nuiImageSequence"))) InitAttributes(); mpTempImage = new nglImage(rTexturePath); mInterpolated = true; mNbFrames = nbFrames; mOrientation = orientation; mRefreshTextures = true; mUseAlpha = false; } void nuiImageSequence::InitAttributes() { nuiAttribute<const nuiColor&>* AttributeColor = new nuiAttribute<const nuiColor&> (nglString(_T("Color")), nuiUnitNone, nuiAttribute<const nuiColor&>::GetterDelegate(this, &nuiImageSequence::GetColor), nuiAttribute<const nuiColor&>::SetterDelegate(this, &nuiImageSequence::SetColor)); nuiAttribute<const nglPath&>* AttributeTexture = new nuiAttribute<const nglPath&> (nglString(_T("Texture")), nuiUnitNone, nuiFastDelegate::MakeDelegate(this, &nuiImageSequence::GetTexturePath), nuiFastDelegate::MakeDelegate(this, &nuiImageSequence::SetTexturePath)); nuiAttribute<bool>* AttributeInterpolation = new nuiAttribute<bool> (nglString(_T("Interpolation")), nuiUnitBoolean, nuiAttribute<bool>::GetterDelegate(this, &nuiImageSequence::IsInterpolated), nuiAttribute<bool>::SetterDelegate(this, &nuiImageSequence::SetInterpolated)); nuiAttribute<uint32>* AttributeNbFrames = new nuiAttribute<uint32> (nglString(_T("NbFrames")), nuiUnitNone, nuiAttribute<uint32>::GetterDelegate(this, &nuiImageSequence::GetNbFrames), nuiAttribute<uint32>::SetterDelegate(this, &nuiImageSequence::SetNbFrames)); nuiAttribute<nglString>* AttributeOrientation = new nuiAttribute<nglString> (nglString(_T("Orientation")), nuiUnitNone, nuiAttribute<nglString>::GetterDelegate(this, &nuiImageSequence::GetOrientation), nuiAttribute<nglString>::SetterDelegate(this, &nuiImageSequence::SetOrientation)); AddAttribute(_T("Color"), AttributeColor); AddAttribute(_T("Texture"), AttributeTexture); AddAttribute(_T("Interpolation"), AttributeInterpolation); AddAttribute(_T("NbFrames"), AttributeNbFrames); AddAttribute(_T("Orientation"), AttributeOrientation); } nuiImageSequence::~nuiImageSequence() { for (uint32 i = 0; i < mTextures.size(); i++) mTextures[i]->Release(); } bool nuiImageSequence::Load(const nuiXMLNode* pNode) { mColor.SetValue(nuiGetString(pNode, _T("Color"), _T("white"))); mpTempImage = new nglImage(nglPath(nuiGetString(pNode, _T("Texture"), nglString::Empty))); mRefreshTextures = true; return true; } nuiXMLNode* nuiImageSequence::Serialize(nuiXMLNode* pNode) { pNode->SetName(_T("nuiImageSequence")); pNode->SetAttribute(_T("Color"), mColor.GetValue()); pNode->SetAttribute(_T("Texture"), GetTexturePath()); return pNode; } nuiRect nuiImageSequence::CalcIdealSize() { // create the sequence textures the first time ::CalcIdealSize is called. // we don't do it in the decoration initialization because the decoration // may have been created from a css stylesheet, and its attributes are set in // a undefined order. We need all the attributed to be properly set before creating the textures. if (mRefreshTextures) { NGL_ASSERT(mpTempImage); bool res = CreateTextures(); NGL_ASSERT(res); delete mpTempImage; mpTempImage = NULL; mRefreshTextures = false; } if (!mTextures.size()) return mIdealRect; mIdealRect.Set(0.0f,0.0f,(nuiSize) mTexRect.GetWidth(),(nuiSize) mTexRect.GetHeight()); return mIdealRect; } bool nuiImageSequence::CreateTextures() { if (!mNbFrames) return false; if (!mpTempImage && !mTextures.size()) return false; NGL_ASSERT(mpTempImage); if (mOrientation == nuiVertical) mTexRect.Set(0, 0, mpTempImage->GetWidth(), ToBelow(mpTempImage->GetHeight() / (float)mNbFrames)); else mTexRect.Set(0, 0, ToBelow(mpTempImage->GetWidth() / (float)mNbFrames), mpTempImage->GetHeight()); // clean existing textures for (uint32 i = 0; i < mTextures.size(); i++) mTextures[i]->Release(); char* pBuffer = mpTempImage->GetBuffer(); // create temp. buffer for destination uint32 dstBufferSize = mTexRect.GetWidth() * mTexRect.GetHeight() * 4; char* pDst = (char*)malloc(dstBufferSize); NGL_ASSERT(pDst); //***************************************************************** // frames are aligned vertically if (mOrientation == nuiVertical) { // copy and paste each frame from the image to an individual texture for (uint32 frame = 0; frame < mNbFrames; frame++) { uint32 x = 0; uint32 y = frame * mTexRect.GetHeight(); nglImageInfo info; mpTempImage->GetInfo(info); NGL_ASSERT((info.mPixelFormat == eImagePixelRGB) || (info.mPixelFormat == eImagePixelRGBA)) char* pSrc = pBuffer + (y * info.mBytesPerLine); nglCopyLineFn pFunc = nglGetCopyLineFn(32, info.mBitDepth); NGL_ASSERT(pFunc); // copy part of the image pFunc(pDst, pSrc, mTexRect.GetWidth() * mTexRect.GetHeight(), false/*don't invert*/); // create a texture from the copyied buffer and store it info.mBufferFormat = eImageFormatRaw; info.mPixelFormat = eImagePixelRGBA; info.mWidth = mTexRect.GetWidth(); info.mHeight = mTexRect.GetHeight(); info.mBitDepth = 32; info.mBytesPerPixel = 4; info.mBytesPerLine = (mTexRect.GetWidth() * 4); info.mpBuffer = pDst; nuiTexture* pTex = nuiTexture::GetTexture(info, true/* clone the buffer */); mTextures.push_back(pTex); if (mInterpolated) { pTex->SetMinFilter(GL_LINEAR); pTex->SetMagFilter(GL_LINEAR); } else { pTex->SetMinFilter(GL_NEAREST); pTex->SetMagFilter(GL_NEAREST); } } } //***************************************************************** // frames are aligned horizontally else { // copy and paste each frame from the image to an individual texture for (uint32 frame = 0; frame < mNbFrames; frame++) { uint32 x = frame * mTexRect.GetWidth(); nglImageInfo info; mpTempImage->GetInfo(info); NGL_ASSERT((info.mPixelFormat == eImagePixelRGB) || (info.mPixelFormat == eImagePixelRGBA)) char* pSrc = pBuffer + (x * info.mBytesPerPixel); nglCopyLineFn pFunc = nglGetCopyLineFn(32, info.mBitDepth); NGL_ASSERT(pFunc); char* pDstPtr = pDst; // copy line per line for (uint32 y = 0; y < mTexRect.GetHeight(); y++) { pSrc = pBuffer + (y * info.mBytesPerLine) + (x * info.mBytesPerPixel); pFunc(pDstPtr, pSrc, mTexRect.GetWidth(), false/*don't invert*/); pDstPtr += ((uint32)mTexRect.GetWidth() * 4); } // create a texture from the copyied buffer and store it info.mBufferFormat = eImageFormatRaw; info.mPixelFormat = eImagePixelRGBA; info.mWidth = mTexRect.GetWidth(); info.mHeight = mTexRect.GetHeight(); info.mBitDepth = 32; info.mBytesPerPixel = 4; info.mBytesPerLine = (mTexRect.GetWidth() * 4); info.mpBuffer = pDst; nuiTexture* pTex = nuiTexture::GetTexture(info, true/* clone the buffer */); mTextures.push_back(pTex); if (mInterpolated) { pTex->SetMinFilter(GL_LINEAR); pTex->SetMagFilter(GL_LINEAR); } else { pTex->SetMinFilter(GL_NEAREST); pTex->SetMagFilter(GL_NEAREST); } } } // clean up free(pDst); return true; } uint32 nuiImageSequence::GetFrameIndex(nuiWidget* pWidget) const { return mFrameIndex; } void nuiImageSequence::SetFrameIndex(uint32 index) { mFrameIndex = index; } uint32 nuiImageSequence::GetNbFrames() const { return mNbFrames; } void nuiImageSequence::SetNbFrames(uint32 nbFrames) { mNbFrames = nbFrames; mRefreshTextures = true; } void nuiImageSequence::SetOrientation(nglString orientation) { if (!orientation.Compare(_T("Vertical"), false)) mOrientation = nuiVertical; else mOrientation = nuiHorizontal; mRefreshTextures = true; } nglString nuiImageSequence::GetOrientation() { if (mOrientation == nuiVertical) return nglString(_T("Vertical")); return nglString(_T("Horizontal")); } const nglPath& nuiImageSequence::GetTexturePath() const { if (HasProperty(_T("Texture"))) return GetProperty(_T("Texture")); return mGlobalTexturePath; } void nuiImageSequence::SetTexturePath(const nglPath& rPath) { SetProperty(_T("Texture"), mGlobalTexturePath); mpTempImage = new nglImage(rPath); NGL_ASSERT(mpTempImage); mRefreshTextures = true; } // virtual bool nuiImageSequence::Draw(nuiDrawContext* pContext) { // int x=0,y=0; if (!mTextures.size() || (mFrameIndex >= mTextures.size())) return false; pContext->PushState(); pContext->ResetState(); pContext->SetTexture(mTextures[mFrameIndex]); pContext->EnableTexturing(true); float alpha = 1.0f; pContext->EnableBlending(true); pContext->SetBlendFunc(nuiBlendTransp); if (mUseAlpha) { alpha = GetAlpha(); } const nuiRect& destRect = mIdealRect.Size(); nuiColor color = nuiColor(1.0f, 1.0f, 1.0f, alpha); pContext->SetFillColor(color); pContext->DrawImage(destRect,mTexRect); pContext->EnableBlending(false); pContext->EnableTexturing(false); pContext->PopState(); return true; } const nuiColor& nuiImageSequence::GetColor() const { return mColor; } void nuiImageSequence::SetColor(const nuiColor& color) { mColor = color; } bool nuiImageSequence::IsInterpolated() { return mInterpolated; } void nuiImageSequence::SetInterpolated(bool set) { mInterpolated = set; for (uint32 i = 0; i < mTextures.size(); i++) { nuiTexture* pTexture = mTextures[i]; if (mInterpolated) { pTexture->SetMinFilter(GL_LINEAR); pTexture->SetMagFilter(GL_LINEAR); } else { pTexture->SetMinFilter(GL_NEAREST); pTexture->SetMagFilter(GL_NEAREST); } } } <commit_msg>removed file from bad location<commit_after><|endoftext|>
<commit_before>#include "server.h" SERVER::SERVER () { struct addrinfo hints, *servinfo, *p; int rv; // return value int yes = 1; memset(&hints, 0, sizeof hints); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; // use my IP if ((rv = getaddrinfo(NULL, PORT, &hints, &servinfo)) != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); exit(EXIT_FAILURE); } // loop through all the results and bind to the first we can for(p = servinfo; p != NULL; p = p->ai_next) { if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { perror("server: socket"); continue; } if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) { perror("setsockopt"); exit(1); } if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) { close(sockfd); perror("server: bind"); continue; } break; } if (p == NULL) { std::cerr << "server: failed to bind" << std::endl; exit (EXIT_FAILURE); } freeaddrinfo(servinfo); // all done with this structure if (listen(sockfd, BACKLOG) == -1) { perror("listen"); exit(1); } } SERVER::~SERVER () { } bool SERVER::addMessage (MESAJ &m) { listamesaje.push_back(m); return true; } bool SERVER::addClient (CLIENT &c) { listaclienti.push_back(c); return true; } bool SERVER::removeClient (CLIENT &c) { listaclienti.remove((const CLIENT &)c); return true; } std::string SERVER::decryptMSG (std::string &msg, CLIENT &sender) { std::string m; try{ m = crypto_box_open (msg, sender.getCI().getNonce(), sender.getCI().getPK(), cryptinfo.getSK()); } catch(char const *e){ write (STDERR_FILENO, e, 256); } return m; } std::string SERVER::decryptMSG (std::string &msg, std::string &pk, std::string &nonce) { std::string m; try{ m = crypto_box_open (msg, nonce, pk, cryptinfo.getSK()); } catch(char const *e){ write (STDERR_FILENO, e, 256); } return m; } std::string SERVER::encryptMSG (std::string &msg, CLIENT &receiver) { std::string c; try{ c = crypto_box(msg, cryptinfo.getNonce(), receiver.getCI().getPK(), cryptinfo.getSK()); } catch(char const *e){ write (STDERR_FILENO, e, 256); } return c; } bool SERVER::sendMessage (std::string &msg, CLIENT &sender) { std::string m = decryptMSG (msg, sender); for(std::list<CLIENT>::iterator it = listaclienti.begin(); it != listaclienti.end(); it++){ std::string cname = encryptMSG (sender.getNume(), *it); sendMsgToClient (cname, *it, false); std::string c = encryptMSG (m, *it); sendMsgToClient (c, *it, false); //sendMsgToClient (sender.getNume(), *it, false); //sendMsgToClient (msg, *it, false); } return true; } void SERVER::sendMsgToClient (std::string &msg, CLIENT &receiver, bool sendendl) { if(write(receiver.getSFD(), msg.c_str(), msg.size()) == -1){ std::cerr << "write() error" << std::endl; exit (EXIT_FAILURE); } if(sendendl){ if(write(receiver.getSFD(), "\n", 1) == -1){ std::cerr << "write() error" << std::endl; exit (EXIT_FAILURE); } } } bool SERVER::sendMessageList (CLIENT &receiver) { std::string serialmesaj; std::string c_serialmesaj; for(std::list<MESAJ>::iterator it = listamesaje.begin(); it != listamesaje.end(); it++){ //std::string cname = encryptMSG ((*it).getName(), receiver); //sendMsgToClient (cname, receiver, true); //sleep(1); //std::string enc_comment = encryptMSG ((*it).getComment(), receiver); //sendMsgToClient (enc_comment, receiver, true); serialmesaj += (*it).getName() + (*it).getComment(); } c_serialmesaj = encryptMSG(serialmesaj, receiver); sendMsgToClient (c_serialmesaj, receiver, false); return true; } bool SERVER::verifyName (std::string &nume) { for(std::list<CLIENT>::iterator it = listaclienti.begin(); it != listaclienti.end(); it++){ if(!nume.compare((*it).getNume())) return false; } return true; } void SERVER::mtxLock () { mtx.lock(); } void SERVER::mtxUnlock () { mtx.unlock(); } void SERVER::Play () { int sfd; socklen_t sin_size; struct sockaddr their_addr; // connector's address information while (true){ sfd = accept(sockfd, &their_addr, &sin_size); if(sfd == -1){ perror("accept"); continue; } std::thread (client_Communication, this, sfd).detach(); } } CLIENT SERVER::exchangeCIandName (int sfd) { std::string client_pk; std::string client_nonce; std::string client_name; sendPK(sfd); sendNonce(sfd); client_pk = recvPK(sfd); client_nonce = recvNonce(sfd); CRYPTO ci (client_pk, client_nonce); client_name = recvName (sfd); CLIENT client (ci, sfd, client_name); return client; } void SERVER::sendPK (int sfd) { if(write (sfd, cryptinfo.getPK().c_str(), crypto_box_PUBLICKEYBYTES ) != crypto_box_PUBLICKEYBYTES){ perror ("write"); exit (EXIT_FAILURE); } } void SERVER::sendNonce (int sfd) { if(write (sfd, cryptinfo.getNonce().c_str(), crypto_box_NONCEBYTES) != crypto_box_NONCEBYTES){ perror ("write"); exit (EXIT_FAILURE); } } std::string SERVER::recvPK (int sfd) { char buf[crypto_box_PUBLICKEYBYTES + 1]; memset (buf, 0, crypto_box_PUBLICKEYBYTES+1); if(read (sfd, buf, crypto_box_PUBLICKEYBYTES) != crypto_box_PUBLICKEYBYTES){ pthread_exit(NULL); } std::string server_pk(buf,crypto_box_PUBLICKEYBYTES); return server_pk; } std::string SERVER::recvNonce (int sfd) { char buf[crypto_box_NONCEBYTES + 1]; memset (buf, 0, crypto_box_NONCEBYTES + 1); if(read (sfd, buf, crypto_box_NONCEBYTES) != crypto_box_NONCEBYTES){ pthread_exit(NULL); } std::string server_nonce(buf, crypto_box_NONCEBYTES); return server_nonce; } std::string SERVER::recvName (int sfd) { char buf[64]; ssize_t br; memset (buf, 0, 64); while(true){ if((br = read (sfd, buf, 64)) == -1){ perror ("read"); exit (EXIT_FAILURE); } if(!br){} // EOF std::string name(buf,br); mtxLock (); if(verifyName (name)){ // client name free for use mtxUnlock (); if(write (sfd, "Y", 1) != 1){ perror ("write"); exit (EXIT_FAILURE); } break; } mtxUnlock (); if(write (sfd, "N", 1) != 1){ perror ("write"); exit (EXIT_FAILURE); } } std::string client_name(buf,br); return client_name; } // do all the communication with the clients in this thread function void client_Communication (SERVER *server_p, int sockfd) { CLIENT client = server_p->exchangeCIandName(sockfd); server_p->mtxLock(); server_p->addClient(client); server_p->sendMessageList(client); server_p->mtxUnlock(); while (1){ char bufread[1024]; ssize_t br; memset (bufread, 0, 1024); if((br = read (sockfd, bufread, 1024)) == -1){ perror ("read"); exit (EXIT_FAILURE); } if(!br){ // EOF server_p->removeClient(client); close (sockfd); return; } // blocks until a message arrives std::string cmsg(bufread,br); std::string msg = server_p->decryptMSG(cmsg, client); //construct MESAJ object MESAJ mes(client.getNume(), msg); server_p->mtxLock(); server_p->addMessage(mes); // add message to message list server_p->sendMessage(cmsg, client); // send message to the other clients server_p->mtxUnlock(); } }<commit_msg>remove client when decryption/encryption error occur which normally should't happen so this is because other client programm is used which doesn't respect the protocol used<commit_after>#include "server.h" SERVER::SERVER () { struct addrinfo hints, *servinfo, *p; int rv; // return value int yes = 1; memset(&hints, 0, sizeof hints); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; // use my IP if ((rv = getaddrinfo(NULL, PORT, &hints, &servinfo)) != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); exit(EXIT_FAILURE); } // loop through all the results and bind to the first we can for(p = servinfo; p != NULL; p = p->ai_next) { if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { perror("server: socket"); continue; } if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) { perror("setsockopt"); exit(1); } if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) { close(sockfd); perror("server: bind"); continue; } break; } if (p == NULL) { std::cerr << "server: failed to bind" << std::endl; exit (EXIT_FAILURE); } freeaddrinfo(servinfo); // all done with this structure if (listen(sockfd, BACKLOG) == -1) { perror("listen"); exit(1); } } SERVER::~SERVER () { } bool SERVER::addMessage (MESAJ &m) { listamesaje.push_back(m); return true; } bool SERVER::addClient (CLIENT &c) { listaclienti.push_back(c); return true; } bool SERVER::removeClient (CLIENT &c) { listaclienti.remove((const CLIENT &)c); return true; } std::string SERVER::decryptMSG (std::string &msg, CLIENT &sender) { std::string m; try{ m = crypto_box_open (msg, sender.getCI().getNonce(), sender.getCI().getPK(), cryptinfo.getSK()); } catch(char const *e){ write (STDERR_FILENO, e, 256); this->removeClient(sender); pthread_exit(NULL); } return m; } std::string SERVER::decryptMSG (std::string &msg, std::string &pk, std::string &nonce) { std::string m; try{ m = crypto_box_open (msg, nonce, pk, cryptinfo.getSK()); } catch(char const *e){ write (STDERR_FILENO, e, 256); } return m; } std::string SERVER::encryptMSG (std::string &msg, CLIENT &receiver) { std::string c; try{ c = crypto_box(msg, cryptinfo.getNonce(), receiver.getCI().getPK(), cryptinfo.getSK()); } catch(char const *e){ write (STDERR_FILENO, e, 256); this->removeClient(receiver); pthread_exit(NULL); } return c; } bool SERVER::sendMessage (std::string &msg, CLIENT &sender) { std::string m = decryptMSG (msg, sender); for(std::list<CLIENT>::iterator it = listaclienti.begin(); it != listaclienti.end(); it++){ std::string cname = encryptMSG (sender.getNume(), *it); sendMsgToClient (cname, *it, false); std::string c = encryptMSG (m, *it); sendMsgToClient (c, *it, false); //sendMsgToClient (sender.getNume(), *it, false); //sendMsgToClient (msg, *it, false); } return true; } void SERVER::sendMsgToClient (std::string &msg, CLIENT &receiver, bool sendendl) { if(write(receiver.getSFD(), msg.c_str(), msg.size()) == -1){ std::cerr << "write() error" << std::endl; exit (EXIT_FAILURE); } if(sendendl){ if(write(receiver.getSFD(), "\n", 1) == -1){ std::cerr << "write() error" << std::endl; exit (EXIT_FAILURE); } } } bool SERVER::sendMessageList (CLIENT &receiver) { std::string serialmesaj; std::string c_serialmesaj; for(std::list<MESAJ>::iterator it = listamesaje.begin(); it != listamesaje.end(); it++){ //std::string cname = encryptMSG ((*it).getName(), receiver); //sendMsgToClient (cname, receiver, true); //sleep(1); //std::string enc_comment = encryptMSG ((*it).getComment(), receiver); //sendMsgToClient (enc_comment, receiver, true); serialmesaj += (*it).getName() + (*it).getComment(); } c_serialmesaj = encryptMSG(serialmesaj, receiver); sendMsgToClient (c_serialmesaj, receiver, false); return true; } bool SERVER::verifyName (std::string &nume) { for(std::list<CLIENT>::iterator it = listaclienti.begin(); it != listaclienti.end(); it++){ if(!nume.compare((*it).getNume())) return false; } return true; } void SERVER::mtxLock () { mtx.lock(); } void SERVER::mtxUnlock () { mtx.unlock(); } void SERVER::Play () { int sfd; socklen_t sin_size; struct sockaddr their_addr; // connector's address information while (true){ sfd = accept(sockfd, &their_addr, &sin_size); if(sfd == -1){ perror("accept"); continue; } std::thread (client_Communication, this, sfd).detach(); } } CLIENT SERVER::exchangeCIandName (int sfd) { std::string client_pk; std::string client_nonce; std::string client_name; sendPK(sfd); sendNonce(sfd); client_pk = recvPK(sfd); client_nonce = recvNonce(sfd); CRYPTO ci (client_pk, client_nonce); client_name = recvName (sfd); CLIENT client (ci, sfd, client_name); return client; } void SERVER::sendPK (int sfd) { if(write (sfd, cryptinfo.getPK().c_str(), crypto_box_PUBLICKEYBYTES ) != crypto_box_PUBLICKEYBYTES){ perror ("write"); exit (EXIT_FAILURE); } } void SERVER::sendNonce (int sfd) { if(write (sfd, cryptinfo.getNonce().c_str(), crypto_box_NONCEBYTES) != crypto_box_NONCEBYTES){ perror ("write"); exit (EXIT_FAILURE); } } std::string SERVER::recvPK (int sfd) { char buf[crypto_box_PUBLICKEYBYTES + 1]; memset (buf, 0, crypto_box_PUBLICKEYBYTES+1); if(read (sfd, buf, crypto_box_PUBLICKEYBYTES) != crypto_box_PUBLICKEYBYTES){ pthread_exit(NULL); } std::string server_pk(buf,crypto_box_PUBLICKEYBYTES); return server_pk; } std::string SERVER::recvNonce (int sfd) { char buf[crypto_box_NONCEBYTES + 1]; memset (buf, 0, crypto_box_NONCEBYTES + 1); if(read (sfd, buf, crypto_box_NONCEBYTES) != crypto_box_NONCEBYTES){ pthread_exit(NULL); } std::string server_nonce(buf, crypto_box_NONCEBYTES); return server_nonce; } std::string SERVER::recvName (int sfd) { char buf[64]; ssize_t br; memset (buf, 0, 64); while(true){ if((br = read (sfd, buf, 64)) == -1){ perror ("read"); exit (EXIT_FAILURE); } if(!br){} // EOF std::string name(buf,br); mtxLock (); if(verifyName (name)){ // client name free for use mtxUnlock (); if(write (sfd, "Y", 1) != 1){ perror ("write"); exit (EXIT_FAILURE); } break; } mtxUnlock (); if(write (sfd, "N", 1) != 1){ perror ("write"); exit (EXIT_FAILURE); } } std::string client_name(buf,br); return client_name; } // do all the communication with the clients in this thread function void client_Communication (SERVER *server_p, int sockfd) { CLIENT client = server_p->exchangeCIandName(sockfd); server_p->mtxLock(); server_p->addClient(client); server_p->sendMessageList(client); server_p->mtxUnlock(); while (1){ char bufread[1024]; ssize_t br; memset (bufread, 0, 1024); if((br = read (sockfd, bufread, 1024)) == -1){ perror ("read"); exit (EXIT_FAILURE); } if(!br){ // EOF server_p->removeClient(client); close (sockfd); return; } // blocks until a message arrives std::string cmsg(bufread,br); std::string msg = server_p->decryptMSG(cmsg, client); //construct MESAJ object MESAJ mes(client.getNume(), msg); server_p->mtxLock(); server_p->addMessage(mes); // add message to message list server_p->sendMessage(cmsg, client); // send message to the other clients server_p->mtxUnlock(); } }<|endoftext|>
<commit_before>#include "debug.h" #include <QDateTime> #include <QFileInfo> #include <QMessageBox> #include <QMutex> #include <QThread> #ifdef Q_OS_WIN #include <io.h> #else #include <unistd.h> #endif namespace { QMutex mutex; QString fileName; int realStdout{}; int realStderr{}; FILE *logFile{}; void handler(QtMsgType type, const QMessageLogContext &context, const QString &msg) { const auto typeName = QMap<QtMsgType, QByteArray>{{QtDebugMsg, " DEBUG "}, {QtInfoMsg, " INFO "}, {QtWarningMsg, " WARN "}, {QtCriticalMsg, " CRIT "}, {QtFatalMsg, " FATAL "}} .value(type); const auto message = QDateTime::currentDateTime().toString(Qt::ISODate).toUtf8() + ' ' + QByteArray::number(qintptr(QThread::currentThreadId())) + ' ' + QFileInfo(context.file).fileName().toUtf8() + ':' + QByteArray::number(context.line) + typeName + msg.toUtf8() + '\n'; if (logFile) write(fileno(logFile), message.data(), message.size()); if (realStderr > 0) write(realStderr, message.data(), message.size()); } void toDefaults() { qInstallMessageHandler(nullptr); if (realStdout > 0) { dup2(realStdout, fileno(stdout)); realStdout = -1; } if (realStderr > 0) { dup2(realStderr, fileno(stderr)); realStderr = -1; } if (logFile) { fclose(logFile); logFile = nullptr; } fileName.clear(); } } // namespace namespace debug { std::atomic_bool isTrace = false; QString traceFileName() { QMutexLocker locker(&mutex); return fileName; } bool setTraceFileName(const QString &fileName) { QMutexLocker locker(&mutex); toDefaults(); if (fileName.isEmpty()) return true; logFile = fopen(qPrintable(fileName), "w"); if (!logFile) return false; realStdout = dup(fileno(stdout)); realStderr = dup(fileno(stderr)); const auto fd = fileno(logFile); dup2(fd, fileno(stdout)); dup2(fd, fileno(stderr)); ::fileName = fileName; qInstallMessageHandler(handler); return true; } } // namespace debug <commit_msg>Add mutex in log handler<commit_after>#include "debug.h" #include <QDateTime> #include <QFileInfo> #include <QMessageBox> #include <QMutex> #include <QThread> #ifdef Q_OS_WIN #include <io.h> #else #include <unistd.h> #endif namespace { QMutex mutex; QString fileName; int realStdout{}; int realStderr{}; FILE *logFile{}; void handler(QtMsgType type, const QMessageLogContext &context, const QString &msg) { const auto typeName = QMap<QtMsgType, QByteArray>{{QtDebugMsg, " DEBUG "}, {QtInfoMsg, " INFO "}, {QtWarningMsg, " WARN "}, {QtCriticalMsg, " CRIT "}, {QtFatalMsg, " FATAL "}} .value(type); const auto message = QDateTime::currentDateTime().toString(Qt::ISODate).toUtf8() + ' ' + QByteArray::number(qintptr(QThread::currentThreadId())) + ' ' + QFileInfo(context.file).fileName().toUtf8() + ':' + QByteArray::number(context.line) + typeName + msg.toUtf8() + '\n'; QMutexLocker locker(&mutex); if (logFile) write(fileno(logFile), message.data(), message.size()); if (realStderr > 0) write(realStderr, message.data(), message.size()); } void toDefaults() { qInstallMessageHandler(nullptr); if (realStdout > 0) { dup2(realStdout, fileno(stdout)); realStdout = -1; } if (realStderr > 0) { dup2(realStderr, fileno(stderr)); realStderr = -1; } if (logFile) { fclose(logFile); logFile = nullptr; } fileName.clear(); } } // namespace namespace debug { std::atomic_bool isTrace = false; QString traceFileName() { QMutexLocker locker(&mutex); return fileName; } bool setTraceFileName(const QString &fileName) { QMutexLocker locker(&mutex); toDefaults(); if (fileName.isEmpty()) return true; logFile = fopen(qPrintable(fileName), "w"); if (!logFile) return false; realStdout = dup(fileno(stdout)); realStderr = dup(fileno(stderr)); const auto fd = fileno(logFile); dup2(fd, fileno(stdout)); dup2(fd, fileno(stderr)); ::fileName = fileName; qInstallMessageHandler(handler); return true; } } // namespace debug <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (c) Yorik van Havre (yorik@uncreated.net) 2015 * * * * This file is part of the FreeCAD CAx development system. * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Library General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ #endif #include "DraftDxf.h" #include <gp_Circ.hxx> #include <gp_Ax1.hxx> #include <gp_Ax2.hxx> #include <gp_Elips.hxx> #include <BRep_Builder.hxx> #include <BRepBuilderAPI_MakeEdge.hxx> #include <BRepBuilderAPI_MakeVertex.hxx> #include <TopoDS_Edge.hxx> #include <TopoDS_Vertex.hxx> #include <TopoDS_Compound.hxx> #include <TopoDS_Shape.hxx> #include <Base/Parameter.h> #include <Base/Matrix.h> #include <Base/Vector3D.h> #include <Base/Interpreter.h> #include <App/Application.h> #include <App/Document.h> #include <App/Annotation.h> #include <Mod/Part/App/PartFeature.h> using namespace DraftUtils; DraftDxfRead::DraftDxfRead(std::string filepath, App::Document *pcDoc) : CDxfRead(filepath.c_str()) { document = pcDoc; ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Draft"); optionGroupLayers = hGrp->GetBool("groupLayers",false); optionImportAnnotations = hGrp->GetBool("dxftext",false); optionScaling = hGrp->GetFloat("dxfScaling",1.0); } gp_Pnt DraftDxfRead::makePoint(const double* p) { double sp1(p[0]); double sp2(p[1]); double sp3(p[2]); if (optionScaling != 1.0) { sp1 = sp1 * optionScaling; sp2 = sp2 * optionScaling; sp3 = sp3 * optionScaling; } return gp_Pnt(sp1,sp2,sp3); } void DraftDxfRead::OnReadLine(const double* s, const double* e, bool /*hidden*/) { gp_Pnt p0 = makePoint(s); gp_Pnt p1 = makePoint(e); if (p0.IsEqual(p1,0.00000001)) return; BRepBuilderAPI_MakeEdge makeEdge(p0, p1); TopoDS_Edge edge = makeEdge.Edge(); AddObject(new Part::TopoShape(edge)); } void DraftDxfRead::OnReadPoint(const double* s) { BRepBuilderAPI_MakeVertex makeVertex(makePoint(s)); TopoDS_Vertex vertex = makeVertex.Vertex(); AddObject(new Part::TopoShape(vertex)); } void DraftDxfRead::OnReadArc(const double* s, const double* e, const double* c, bool dir, bool /*hidden*/) { gp_Pnt p0 = makePoint(s); gp_Pnt p1 = makePoint(e); gp_Dir up(0, 0, 1); if (!dir) up = -up; gp_Pnt pc = makePoint(c); gp_Circ circle(gp_Ax2(pc, up), p0.Distance(pc)); BRepBuilderAPI_MakeEdge makeEdge(circle, p0, p1); TopoDS_Edge edge = makeEdge.Edge(); AddObject(new Part::TopoShape(edge)); } void DraftDxfRead::OnReadCircle(const double* s, const double* c, bool dir, bool /*hidden*/) { gp_Pnt p0 = makePoint(s); gp_Dir up(0, 0, 1); if (!dir) up = -up; gp_Pnt pc = makePoint(c); gp_Circ circle(gp_Ax2(pc, up), p0.Distance(pc)); BRepBuilderAPI_MakeEdge makeEdge(circle); TopoDS_Edge edge = makeEdge.Edge(); AddObject(new Part::TopoShape(edge)); } void DraftDxfRead::OnReadSpline(struct SplineData& /*sd*/) { // not yet implemented } void DraftDxfRead::OnReadEllipse(const double* c, double major_radius, double minor_radius, double rotation, double /*start_angle*/, double /*end_angle*/, bool dir) { gp_Dir up(0, 0, 1); if(!dir) up = -up; gp_Pnt pc = makePoint(c); gp_Elips ellipse(gp_Ax2(pc, up), major_radius * optionScaling, minor_radius * optionScaling); ellipse.Rotate(gp_Ax1(pc,up),rotation); BRepBuilderAPI_MakeEdge makeEdge(ellipse); TopoDS_Edge edge = makeEdge.Edge(); AddObject(new Part::TopoShape(edge)); } void DraftDxfRead::OnReadText(const double *point, const double /*height*/, const char* text) { if (optionImportAnnotations) { Base::Vector3d pt(point[0] * optionScaling, point[1] * optionScaling, point[2] * optionScaling); if(LayerName().substr(0, 6) != "BLOCKS") { App::Annotation *pcFeature = (App::Annotation *)document->addObject("App::Annotation", "Text"); pcFeature->LabelText.setValue(Deformat(text)); pcFeature->Position.setValue(pt); } //else std::cout << "skipped text in block: " << LayerName() << std::endl; } } void DraftDxfRead::OnReadInsert(const double* point, const double* scale, const char* name, double rotation) { //std::cout << "Inserting block " << name << " rotation " << rotation << " pos " << point[0] << "," << point[1] << "," << point[2] << " scale " << scale[0] << "," << scale[1] << "," << scale[2] << std::endl; for(std::map<std::string,std::vector<Part::TopoShape*> > ::const_iterator i = layers.begin(); i != layers.end(); ++i) { std::string k = i->first; std::string prefix = "BLOCKS "; prefix += name; prefix += " "; if(k.substr(0, prefix.size()) == prefix) { BRep_Builder builder; TopoDS_Compound comp; builder.MakeCompound(comp); std::vector<Part::TopoShape*> v = i->second; for(std::vector<Part::TopoShape*>::const_iterator j = v.begin(); j != v.end(); ++j) { const TopoDS_Shape& sh = (*j)->getShape(); if (!sh.IsNull()) builder.Add(comp, sh); } if (!comp.IsNull()) { Part::TopoShape* pcomp = new Part::TopoShape(comp); Base::Matrix4D mat; mat.scale(scale[0],scale[1],scale[2]); mat.rotZ(rotation); mat.move(point[0]*optionScaling,point[1]*optionScaling,point[2]*optionScaling); pcomp->transformShape(mat,true); AddObject(pcomp); } } } } void DraftDxfRead::OnReadDimension(const double* s, const double* e, const double* point, double /*rotation*/) { if (optionImportAnnotations) { Base::Interpreter().runString("import Draft"); Base::Interpreter().runStringArg("p1=FreeCAD.Vector(%f,%f,%f)",s[0]*optionScaling,s[1]*optionScaling,s[2]*optionScaling); Base::Interpreter().runStringArg("p2=FreeCAD.Vector(%f,%f,%f)",e[0]*optionScaling,e[1]*optionScaling,e[2]*optionScaling); Base::Interpreter().runStringArg("p3=FreeCAD.Vector(%f,%f,%f)",point[0]*optionScaling,point[1]*optionScaling,point[2]*optionScaling); Base::Interpreter().runString("Draft.makeDimension(p1,p2,p3)"); } } void DraftDxfRead::AddObject(Part::TopoShape *shape) { //std::cout << "layer:" << LayerName() << std::endl; std::vector <Part::TopoShape*> vec; if (layers.count(LayerName())) vec = layers[LayerName()]; vec.push_back(shape); layers[LayerName()] = vec; if (!optionGroupLayers) { Part::Feature *pcFeature = (Part::Feature *)document->addObject("Part::Feature", "Shape"); pcFeature->Shape.setValue(*shape); } } std::string DraftDxfRead::Deformat(const char* text) { // this function removes DXF formatting from texts std::stringstream ss; bool escape = false; // turned on when finding an escape character bool longescape = false; // turned on for certain escape codes that expect additional chars for(unsigned int i = 0; i<strlen(text); i++) { if (text[i] == '\\') escape = true; else if (escape) { if (longescape) { if (text[i] == ';') { escape = false; longescape = false; } } else { if ( (text[i] == 'H') || (text[i] == 'h') || (text[i] == 'Q') || (text[i] == 'q') || (text[i] == 'W') || (text[i] == 'w') || (text[i] == 'F') || (text[i] == 'f') || (text[i] == 'A') || (text[i] == 'a') || (text[i] == 'C') || (text[i] == 'c') || (text[i] == 'T') || (text[i] == 't') ) longescape = true; else { if ( (text[i] == 'P') || (text[i] == 'p') ) ss << "\n"; escape = false; } } } else if ( (text[i] != '{') && (text[i] != '}') ) { ss << text[i]; } } return ss.str(); } void DraftDxfRead::AddGraphics() const { if (optionGroupLayers) { for(std::map<std::string,std::vector<Part::TopoShape*> > ::const_iterator i = layers.begin(); i != layers.end(); ++i) { BRep_Builder builder; TopoDS_Compound comp; builder.MakeCompound(comp); std::string k = i->first; std::vector<Part::TopoShape*> v = i->second; if(k.substr(0, 6) != "BLOCKS") { for(std::vector<Part::TopoShape*>::const_iterator j = v.begin(); j != v.end(); ++j) { const TopoDS_Shape& sh = (*j)->getShape(); if (!sh.IsNull()) builder.Add(comp, sh); } if (!comp.IsNull()) { Part::Feature *pcFeature = (Part::Feature *)document->addObject("Part::Feature", k.c_str()); pcFeature->Shape.setValue(comp); } } } } } <commit_msg>Draft: Do not import non-instanciated blocks - fixes #2822<commit_after>/*************************************************************************** * Copyright (c) Yorik van Havre (yorik@uncreated.net) 2015 * * * * This file is part of the FreeCAD CAx development system. * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Library General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ #endif #include "DraftDxf.h" #include <gp_Circ.hxx> #include <gp_Ax1.hxx> #include <gp_Ax2.hxx> #include <gp_Elips.hxx> #include <BRep_Builder.hxx> #include <BRepBuilderAPI_MakeEdge.hxx> #include <BRepBuilderAPI_MakeVertex.hxx> #include <TopoDS_Edge.hxx> #include <TopoDS_Vertex.hxx> #include <TopoDS_Compound.hxx> #include <TopoDS_Shape.hxx> #include <Base/Parameter.h> #include <Base/Matrix.h> #include <Base/Vector3D.h> #include <Base/Interpreter.h> #include <App/Application.h> #include <App/Document.h> #include <App/Annotation.h> #include <Mod/Part/App/PartFeature.h> using namespace DraftUtils; DraftDxfRead::DraftDxfRead(std::string filepath, App::Document *pcDoc) : CDxfRead(filepath.c_str()) { document = pcDoc; ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Draft"); optionGroupLayers = hGrp->GetBool("groupLayers",false); optionImportAnnotations = hGrp->GetBool("dxftext",false); optionScaling = hGrp->GetFloat("dxfScaling",1.0); } gp_Pnt DraftDxfRead::makePoint(const double* p) { double sp1(p[0]); double sp2(p[1]); double sp3(p[2]); if (optionScaling != 1.0) { sp1 = sp1 * optionScaling; sp2 = sp2 * optionScaling; sp3 = sp3 * optionScaling; } return gp_Pnt(sp1,sp2,sp3); } void DraftDxfRead::OnReadLine(const double* s, const double* e, bool /*hidden*/) { gp_Pnt p0 = makePoint(s); gp_Pnt p1 = makePoint(e); if (p0.IsEqual(p1,0.00000001)) return; BRepBuilderAPI_MakeEdge makeEdge(p0, p1); TopoDS_Edge edge = makeEdge.Edge(); AddObject(new Part::TopoShape(edge)); } void DraftDxfRead::OnReadPoint(const double* s) { BRepBuilderAPI_MakeVertex makeVertex(makePoint(s)); TopoDS_Vertex vertex = makeVertex.Vertex(); AddObject(new Part::TopoShape(vertex)); } void DraftDxfRead::OnReadArc(const double* s, const double* e, const double* c, bool dir, bool /*hidden*/) { gp_Pnt p0 = makePoint(s); gp_Pnt p1 = makePoint(e); gp_Dir up(0, 0, 1); if (!dir) up = -up; gp_Pnt pc = makePoint(c); gp_Circ circle(gp_Ax2(pc, up), p0.Distance(pc)); BRepBuilderAPI_MakeEdge makeEdge(circle, p0, p1); TopoDS_Edge edge = makeEdge.Edge(); AddObject(new Part::TopoShape(edge)); } void DraftDxfRead::OnReadCircle(const double* s, const double* c, bool dir, bool /*hidden*/) { gp_Pnt p0 = makePoint(s); gp_Dir up(0, 0, 1); if (!dir) up = -up; gp_Pnt pc = makePoint(c); gp_Circ circle(gp_Ax2(pc, up), p0.Distance(pc)); BRepBuilderAPI_MakeEdge makeEdge(circle); TopoDS_Edge edge = makeEdge.Edge(); AddObject(new Part::TopoShape(edge)); } void DraftDxfRead::OnReadSpline(struct SplineData& /*sd*/) { // not yet implemented } void DraftDxfRead::OnReadEllipse(const double* c, double major_radius, double minor_radius, double rotation, double /*start_angle*/, double /*end_angle*/, bool dir) { gp_Dir up(0, 0, 1); if(!dir) up = -up; gp_Pnt pc = makePoint(c); gp_Elips ellipse(gp_Ax2(pc, up), major_radius * optionScaling, minor_radius * optionScaling); ellipse.Rotate(gp_Ax1(pc,up),rotation); BRepBuilderAPI_MakeEdge makeEdge(ellipse); TopoDS_Edge edge = makeEdge.Edge(); AddObject(new Part::TopoShape(edge)); } void DraftDxfRead::OnReadText(const double *point, const double /*height*/, const char* text) { if (optionImportAnnotations) { Base::Vector3d pt(point[0] * optionScaling, point[1] * optionScaling, point[2] * optionScaling); if(LayerName().substr(0, 6) != "BLOCKS") { App::Annotation *pcFeature = (App::Annotation *)document->addObject("App::Annotation", "Text"); pcFeature->LabelText.setValue(Deformat(text)); pcFeature->Position.setValue(pt); } //else std::cout << "skipped text in block: " << LayerName() << std::endl; } } void DraftDxfRead::OnReadInsert(const double* point, const double* scale, const char* name, double rotation) { //std::cout << "Inserting block " << name << " rotation " << rotation << " pos " << point[0] << "," << point[1] << "," << point[2] << " scale " << scale[0] << "," << scale[1] << "," << scale[2] << std::endl; for(std::map<std::string,std::vector<Part::TopoShape*> > ::const_iterator i = layers.begin(); i != layers.end(); ++i) { std::string k = i->first; std::string prefix = "BLOCKS "; prefix += name; prefix += " "; if(k.substr(0, prefix.size()) == prefix) { BRep_Builder builder; TopoDS_Compound comp; builder.MakeCompound(comp); std::vector<Part::TopoShape*> v = i->second; for(std::vector<Part::TopoShape*>::const_iterator j = v.begin(); j != v.end(); ++j) { const TopoDS_Shape& sh = (*j)->getShape(); if (!sh.IsNull()) builder.Add(comp, sh); } if (!comp.IsNull()) { Part::TopoShape* pcomp = new Part::TopoShape(comp); Base::Matrix4D mat; mat.scale(scale[0],scale[1],scale[2]); mat.rotZ(rotation); mat.move(point[0]*optionScaling,point[1]*optionScaling,point[2]*optionScaling); pcomp->transformShape(mat,true); AddObject(pcomp); } } } } void DraftDxfRead::OnReadDimension(const double* s, const double* e, const double* point, double /*rotation*/) { if (optionImportAnnotations) { Base::Interpreter().runString("import Draft"); Base::Interpreter().runStringArg("p1=FreeCAD.Vector(%f,%f,%f)",s[0]*optionScaling,s[1]*optionScaling,s[2]*optionScaling); Base::Interpreter().runStringArg("p2=FreeCAD.Vector(%f,%f,%f)",e[0]*optionScaling,e[1]*optionScaling,e[2]*optionScaling); Base::Interpreter().runStringArg("p3=FreeCAD.Vector(%f,%f,%f)",point[0]*optionScaling,point[1]*optionScaling,point[2]*optionScaling); Base::Interpreter().runString("Draft.makeDimension(p1,p2,p3)"); } } void DraftDxfRead::AddObject(Part::TopoShape *shape) { //std::cout << "layer:" << LayerName() << std::endl; std::vector <Part::TopoShape*> vec; if (layers.count(LayerName())) vec = layers[LayerName()]; vec.push_back(shape); layers[LayerName()] = vec; if (!optionGroupLayers) { if(LayerName().substr(0, 6) != "BLOCKS") { Part::Feature *pcFeature = (Part::Feature *)document->addObject("Part::Feature", "Shape"); pcFeature->Shape.setValue(shape->getShape()); } } } std::string DraftDxfRead::Deformat(const char* text) { // this function removes DXF formatting from texts std::stringstream ss; bool escape = false; // turned on when finding an escape character bool longescape = false; // turned on for certain escape codes that expect additional chars for(unsigned int i = 0; i<strlen(text); i++) { if (text[i] == '\\') escape = true; else if (escape) { if (longescape) { if (text[i] == ';') { escape = false; longescape = false; } } else { if ( (text[i] == 'H') || (text[i] == 'h') || (text[i] == 'Q') || (text[i] == 'q') || (text[i] == 'W') || (text[i] == 'w') || (text[i] == 'F') || (text[i] == 'f') || (text[i] == 'A') || (text[i] == 'a') || (text[i] == 'C') || (text[i] == 'c') || (text[i] == 'T') || (text[i] == 't') ) longescape = true; else { if ( (text[i] == 'P') || (text[i] == 'p') ) ss << "\n"; escape = false; } } } else if ( (text[i] != '{') && (text[i] != '}') ) { ss << text[i]; } } return ss.str(); } void DraftDxfRead::AddGraphics() const { if (optionGroupLayers) { for(std::map<std::string,std::vector<Part::TopoShape*> > ::const_iterator i = layers.begin(); i != layers.end(); ++i) { BRep_Builder builder; TopoDS_Compound comp; builder.MakeCompound(comp); std::string k = i->first; std::vector<Part::TopoShape*> v = i->second; if(k.substr(0, 6) != "BLOCKS") { for(std::vector<Part::TopoShape*>::const_iterator j = v.begin(); j != v.end(); ++j) { const TopoDS_Shape& sh = (*j)->getShape(); if (!sh.IsNull()) builder.Add(comp, sh); } if (!comp.IsNull()) { Part::Feature *pcFeature = (Part::Feature *)document->addObject("Part::Feature", k.c_str()); pcFeature->Shape.setValue(comp); } } } } } <|endoftext|>
<commit_before>#include "Graphics/Shader.hpp" #include "Core/Logger.hpp" #include <GL/glew.h> #ifdef _WIN32 #include <GL/wglew.h> #endif #include <fstream> namespace dm { ProgramShader::ProgramShader() : m_linked(false), m_id(0) {} ProgramShader::~ProgramShader() { this->unload_shaders(); } bool ProgramShader::link() { Log::progress("debug", "Linking shader %d", m_id); assert(!m_shaders.empty()); glLinkProgram(m_id); GLint linked; glGetProgramiv(m_id, GL_LINK_STATUS, &linked); if (linked == GL_FALSE) { GLint length, lengthRead = 0; glGetProgramiv(m_id, GL_INFO_LOG_LENGTH, &length); char* log = new char[length]; glGetProgramInfoLog(m_id, length, &lengthRead, log); Log::result(Log::Result::ERROR); Log::debug("Error log: %s", log); delete[] log; return false; } Log::result(Log::Result::OK); m_linked = true; return true; } void ProgramShader::unload_shaders() { for (Shader& s : m_shaders) { if (s.compiled) { glDeleteShader(s.id); s.compiled = false; s.id = 0; } } } void ProgramShader::bind() { assert(m_id != 0); glUseProgram(m_id); } bool ProgramShader::load(const char* filename, Shader::Type type) { assert(m_linked == false); /* Create the program */ if (m_id == 0) { m_id = glCreateProgram(); } int size = 0; char* data = nullptr; std::ifstream file(filename, std::ios::in); if (!file.is_open()) { return false; } /* Calculate the size needed to store the file */ file.seekg(0, std::ios::end); size = file.tellg(); file.seekg(0, std::ios::beg); data = new char[size+1]; file.read(data, size); /* Check if the whole file was loaded */ if (file.tellg() != size) { delete[] data; return false; } file.close(); Log::progress("debug", "Compiling shader %s", filename); data[size] = '\0'; const bool result = this->load_source((const char*)data, type); delete[] data; return result; } bool ProgramShader::load_source(const char* data, Shader::Type type) { if (m_shaders.size() <= type) { m_shaders.resize(type + 1); } Shader& shader = m_shaders[type]; if (shader.compiled) { glDeleteShader(shader.id); } shader = Shader{type, 0, false}; /* TODO: Other shader types */ shader.id = glCreateShader( type == Shader::Type::Vertex ? GL_VERTEX_SHADER : GL_FRAGMENT_SHADER); if (shader.id == 0) { delete[] data; return false; } const GLchar* source = static_cast<const GLchar*>(data); Log::info(data); // const int sizei = static_cast<const int>(strlen(data)); glShaderSource(shader.id, 1, static_cast<const GLchar**>(&source), NULL); glCompileShader(shader.id); GLint compiled = 0; glGetShaderiv(shader.id, GL_COMPILE_STATUS, &compiled); /* Failed to compile, show the error log and exit */ if (compiled == GL_FALSE) { GLint length, lengthRead = 0; glGetShaderiv(shader.id, GL_INFO_LOG_LENGTH, &length); char* log = new char[length]; glGetShaderInfoLog(shader.id, length, &lengthRead, log); Log::result(Log::Result::ERROR); Log::debug("Error log: %s", log); glDeleteShader(shader.id); delete[] log; return false; } Log::result(Log::Result::OK); shader.compiled = true; glAttachShader(m_id, shader.id); return true; } /* GLSL Uniform setters */ void ProgramShader::set_uniform(int value, const char* name) { assert(m_id != 0); glUniform1i(glGetUniformLocation(m_id, name), value); } void ProgramShader::set_uniform(float value, const char* name) { assert(m_id != 0); glUniform1f(glGetUniformLocation(m_id, name), value); } void ProgramShader::set_uniform(const Matrix4f& value, const char* name) { assert(m_id != 0); Matrix4f transposed = value.transpose(); glUniformMatrix4fv(glGetUniformLocation(m_id, name), 1, GL_FALSE, &transposed.m[0]); } void ProgramShader::set_uniform(const Vec3f& value, const char* name) { assert(m_id != 0); glUniform3f(glGetUniformLocation(m_id, name), value.x, value.y, value.z); } void ProgramShader::set_uniform(const Vec2f& value, const char* name) { assert(m_id != 0); glUniform2f(glGetUniformLocation(m_id, name), value.x, value.y); } } /* namespace dm */ <commit_msg>fix program shader creation<commit_after>#include "Graphics/Shader.hpp" #include "Core/Logger.hpp" #include <GL/glew.h> #ifdef _WIN32 #include <GL/wglew.h> #endif #include <fstream> namespace dm { ProgramShader::ProgramShader() : m_linked(false), m_id(0) {} ProgramShader::~ProgramShader() { this->unload_shaders(); } bool ProgramShader::link() { Log::progress("debug", "Linking shader %d", m_id); assert(!m_shaders.empty()); glLinkProgram(m_id); GLint linked; glGetProgramiv(m_id, GL_LINK_STATUS, &linked); if (linked == GL_FALSE) { GLint length, lengthRead = 0; glGetProgramiv(m_id, GL_INFO_LOG_LENGTH, &length); char* log = new char[length]; glGetProgramInfoLog(m_id, length, &lengthRead, log); Log::result(Log::Result::ERROR); Log::debug("Error log: %s", log); delete[] log; return false; } Log::result(Log::Result::OK); m_linked = true; return true; } void ProgramShader::unload_shaders() { for (Shader& s : m_shaders) { if (s.compiled) { glDeleteShader(s.id); s.compiled = false; s.id = 0; } } } void ProgramShader::bind() { assert(m_id != 0); glUseProgram(m_id); } bool ProgramShader::load(const char* filename, Shader::Type type) { int size = 0; char* data = nullptr; std::ifstream file(filename, std::ios::in); if (!file.is_open()) { return false; } /* Calculate the size needed to store the file */ file.seekg(0, std::ios::end); size = file.tellg(); file.seekg(0, std::ios::beg); data = new char[size+1]; file.read(data, size); /* Check if the whole file was loaded */ if (file.tellg() != size) { delete[] data; return false; } file.close(); Log::progress("debug", "Compiling shader %s", filename); data[size] = '\0'; const bool result = this->load_source((const char*)data, type); delete[] data; return result; } bool ProgramShader::load_source(const char* data, Shader::Type type) { assert(m_linked == false); /* Create the program */ if (m_id == 0) { m_id = glCreateProgram(); } if (m_shaders.size() <= type) { m_shaders.resize(type + 1); } Shader& shader = m_shaders[type]; if (shader.compiled) { glDeleteShader(shader.id); } shader = Shader{type, 0, false}; /* TODO: Other shader types */ shader.id = glCreateShader( type == Shader::Type::Vertex ? GL_VERTEX_SHADER : GL_FRAGMENT_SHADER); if (shader.id == 0) { delete[] data; return false; } const GLchar* source = static_cast<const GLchar*>(data); glShaderSource(shader.id, 1, static_cast<const GLchar**>(&source), NULL); glCompileShader(shader.id); GLint compiled = 0; glGetShaderiv(shader.id, GL_COMPILE_STATUS, &compiled); /* Failed to compile, show the error log and exit */ if (compiled == GL_FALSE) { GLint length, lengthRead = 0; glGetShaderiv(shader.id, GL_INFO_LOG_LENGTH, &length); char* log = new char[length]; glGetShaderInfoLog(shader.id, length, &lengthRead, log); Log::result(Log::Result::ERROR); Log::debug("Error log: %s", log); glDeleteShader(shader.id); delete[] log; return false; } Log::result(Log::Result::OK); shader.compiled = true; glAttachShader(m_id, shader.id); return true; } /* GLSL Uniform setters */ void ProgramShader::set_uniform(int value, const char* name) { assert(m_id != 0); glUniform1i(glGetUniformLocation(m_id, name), value); } void ProgramShader::set_uniform(float value, const char* name) { assert(m_id != 0); glUniform1f(glGetUniformLocation(m_id, name), value); } void ProgramShader::set_uniform(const Matrix4f& value, const char* name) { assert(m_id != 0); Matrix4f transposed = value.transpose(); glUniformMatrix4fv(glGetUniformLocation(m_id, name), 1, GL_FALSE, &transposed.m[0]); } void ProgramShader::set_uniform(const Vec3f& value, const char* name) { assert(m_id != 0); glUniform3f(glGetUniformLocation(m_id, name), value.x, value.y, value.z); } void ProgramShader::set_uniform(const Vec2f& value, const char* name) { assert(m_id != 0); glUniform2f(glGetUniformLocation(m_id, name), value.x, value.y); } } /* namespace dm */ <|endoftext|>
<commit_before>#include <algorithm> #include <cctype> #include <chrono> #include <cstdlib> #include <cstdio> #include <exception> #include <iostream> #include <fstream> #include <random> #include <string> #include <unordered_map> #include "boost/algorithm/string.hpp" #include "boost/date_time/gregorian/gregorian.hpp" #include "snap.h" #include "StringHasher.h" const std::string prefix = "Data/"; const std::string output_path = "../tmp/"; const std::string suffix = "-Combined.txt"; const int max_input_size = 1000000; // hashing parameters const int A = 3; const int M = 65071; const int LEFT_HASH_WIDTH = 15; const int RIGHT_HASH_WIDTH = 25; void print_column_headers() { std::cout << "mt_cxt = matching_contexts_cnt" << '\n'; std::cout << "mt_prg = matching_programs_cnt" << '\n'; std::cout << "tot_mt = total_matches_cnt" << '\n'; std::cout << "sel_prg = selected_programs_cnt" << '\n'; std::cout << "tot_prg = total_programs_cnt" << '\n'; std::cout << "dt \tmt_cxt\tmt_prg\ttot_mt\tsel_prg\ttot_prg" << std::endl; } int main() { clock_t start_time = std::clock(); srand(time(NULL)); std::string random_id = std::to_string(rand()); snap::web::print_header(); // get user input int content_length = atoi(getenv("CONTENT_LENGTH")); char *input = new char[content_length+1]; fgets(input, content_length+1, stdin); std::string query_string(input); delete[] input; // process user input std::map<std::string, std::string> arguments = snap::web::parse_query_string(query_string); std::string search_string = snap::web::decode_uri(boost::algorithm::trim_copy(arguments["search-string"])); boost::gregorian::date from_date, to_date; try { from_date = snap::date::string_to_date(arguments["from-date"]); to_date = snap::date::string_to_date(arguments["to-date"]); } catch (snap::date::InvalidDateException &e) { std::cout << "<span class=\"error\">" << e.what() << "</span>" << std::endl; exit(-1); } int num_excerpts = stoi(arguments["num-excerpts"]); int excerpt_size = stoi(arguments["excerpt-size"]); bool random = arguments["random"] == "on"; std::vector<std::string> file_list = snap::io::generate_file_names(from_date, to_date, prefix, suffix); if (random) { unsigned seed = std::chrono::system_clock::now().time_since_epoch().count(); std::shuffle(file_list.begin(), file_list.end(), std::default_random_engine(seed)); } std::vector<snap::Expression> expressions; try { expressions.emplace_back(search_string); } catch(snap::ExpressionSyntaxError &e) { const char *error_msg = e.what(); std::cout << "<span class=\"error\">" << error_msg << "</span>" << std::endl; delete[] error_msg; exit(-1); } // display user input std::cout << "<p>" << std::endl; std::cout << "Search string: " << search_string << "<br/>" << std::endl; std::cout << "From (inclusive): " << arguments["from-date"] << "<br/>" << std::endl; std::cout << "To (inclusive): " << arguments["to-date"] << "<br/>" << std::endl; std::cout << "Number of Excerpts: " << arguments["num-excerpts"] << "<br/>" << std::endl; std::cout << "Excerpt Size: " << arguments["excerpt-size"] << "<br/>" << std::endl; std::cout << "</p>" << std::endl; // set up excerpt file std::string output_excerpt_file_name = output_path + snap::date::date_to_string(from_date) + "_excerpts_" + random_id + ".csv"; std::ofstream output_excerpt_file(output_excerpt_file_name); output_excerpt_file << "\"dt\",\"program\",\"excerpt\"" << std::endl; // begin to iteratively process files std::unordered_map<int, int> left_total_match_hashes; std::unordered_map<int, int> right_total_match_hashes; int matching_contexts_sum = 0; int matching_programs_sum = 0; int total_matches_sum = 0; int selected_programs_sum = 0; int total_programs_sum = 0; std::vector<std::vector<std::string>> search_results; std::vector<std::string> corrupt_files; std::vector<std::string> missing_files; std::vector<snap::Excerpt> excerpts; if (!random) { std::cout << "<pre>" << std::endl; print_column_headers(); } snap::StringHasher hasher("", M, A); for (auto it = file_list.begin(); it != file_list.end(); ++it) { boost::gregorian::date current_date = snap::date::string_to_date((*it).substr(prefix.length(), 10)); if (snap::io::file_exists(*it)) { std::vector<snap::Program> programs; try { programs = snap::io::parse_programs(*it); } catch (snap::io::CorruptFileException &e) { programs.clear(); corrupt_files.push_back(*it); continue; } int matching_contexts = 0; // context is distinct hash AND distinct program int matching_programs = 0; int total_matches = 0; if (random) { unsigned seed = std::chrono::system_clock::now().time_since_epoch().count(); std::shuffle(programs.begin(), programs.end(), std::default_random_engine(seed)); } std::unordered_map<int, int> left_match_hashes; std::unordered_map<int, int> right_match_hashes; for (auto p = programs.begin(); p != programs.end(); ++p) { std::map<std::string, std::vector<int>> raw_match_positions = snap::find(expressions.back().patterns, p -> lower_text); std::map<std::string, std::vector<int>> match_positions = snap::evaluate_expressions(expressions, raw_match_positions); hasher.load_text(p -> lower_text); if (match_positions[search_string].size() > 0) { ++matching_programs; total_matches += match_positions[search_string].size(); bool total_context_added = false; bool context_added = false; for (auto it = match_positions[search_string].begin(); it != match_positions[search_string].end(); ++it) { int left_match_hash = hasher.hash(*it - LEFT_HASH_WIDTH, *it); int right_match_hash = hasher.hash(*it, *it + RIGHT_HASH_WIDTH); int left_hash_cnt = left_match_hashes[left_match_hash]++; int right_hash_cnt = right_match_hashes[right_match_hash]++; int left_total_hash_cnt = left_total_match_hashes[left_match_hash]++; int right_total_hash_cnt = right_total_match_hashes[right_match_hash]++; if (left_hash_cnt == 0 && right_hash_cnt == 0) { // only add if new hash is encountered if (!context_added) { // only add once per program context_added = true; ++matching_contexts; } // only add excerpts with new completely new hashes if (left_total_hash_cnt == 0 && right_total_hash_cnt == 0) { if (!total_context_added) { total_context_added = true; ++matching_contexts_sum; } excerpts.emplace_back(*p, *it-excerpt_size, *it+excerpt_size); output_excerpt_file << '"' << excerpts.back().date << "\",\"" << excerpts.back().program_title << "\",\"" << boost::replace_all_copy(excerpts.back().text, "\"", "\"\"") << '"' << std::endl; for (auto pattern = expressions.back().patterns.begin(); pattern != expressions.back().patterns.end(); ++pattern) { excerpts.back().highlight_word(*pattern); } if (random && excerpts.size() <= num_excerpts) { snap::web::print_excerpt(excerpts.back()); } } } } } match_positions.clear(); } matching_programs_sum += matching_programs; total_matches_sum += total_matches; selected_programs_sum += programs.size(); total_programs_sum += programs.size(); search_results.push_back(std::vector<std::string>()); search_results.back().push_back(snap::date::date_to_string(current_date)); search_results.back().push_back(std::to_string(matching_contexts)); search_results.back().push_back(std::to_string(matching_programs)); search_results.back().push_back(std::to_string(total_matches)); search_results.back().push_back(std::to_string(programs.size())); search_results.back().push_back(std::to_string(programs.size())); if (!random) { std::copy(search_results.back().begin(), search_results.back().end() - 1, std::ostream_iterator<std::string>(std::cout, "\t")); std::cout << search_results.back().back() << std::endl; } programs.clear(); } else { missing_files.push_back(*it); } } sort(search_results.begin(), search_results.end(), [](std::vector<std::string> a, std::vector<std::string> b) -> bool { return a.front() < b.front(); }); if (random) { std::cout << "<pre>" << std::endl; print_column_headers(); for (auto it = search_results.begin(); it != search_results.end(); ++it) { std::copy(it -> begin(), it -> end() - 1, std::ostream_iterator<std::string>(std::cout, "\t")); std::cout << it -> back() << std::endl; } } std::cout << "Grand Total:"; std::cout << '\t' << matching_contexts_sum; std::cout << '\t' << matching_programs_sum; std::cout << '\t' << total_matches_sum; std::cout << '\t' << selected_programs_sum; std::cout << '\t' << total_programs_sum << std::endl; std::cout << "</pre>" << std::endl; // output file std::string output_file_name = output_path + search_results.front().front() + "_" + random_id + ".csv"; std::ofstream output_file(output_file_name); output_file << "dt,matching_contexts_cnt,matching_programs_cnt,total_matches_cnt,selected_programs_cnt,total_programs_cnt" << std::endl; for (auto it = search_results.begin(); it != search_results.end(); ++it) { std::copy(it -> begin(), it -> end() - 1, std::ostream_iterator<std::string>(output_file, ",")); output_file << it -> back() << '\n'; } output_file.close(); output_excerpt_file.close(); std::cout << "<a href=\"" + output_file_name + "\">Output CSV</a><br/>" << std::endl; std::cout << "<a href=\"" + output_excerpt_file_name + "\">Excerpt CSV</a><br/>" << std::endl; std::cout << "<div>"; std::cout << "<br/>" << std::endl; snap::web::print_missing_files(missing_files); std::cout << "<br/>" << std::endl; snap::web::print_corrupt_files(corrupt_files); std::cout << "</div>" << std::endl; if (!random) snap::web::print_excerpts(excerpts, num_excerpts, true); double duration = (std::clock() - start_time) / (double) CLOCKS_PER_SEC; std::cout << "<br/><span>Time taken (seconds): " << duration << "</span><br/>" << std::endl; snap::web::close_html(); return 0; } <commit_msg>added smaller random excerpt file<commit_after>#include <algorithm> #include <cctype> #include <chrono> #include <cstdlib> #include <cstdio> #include <exception> #include <iostream> #include <fstream> #include <random> #include <string> #include <unordered_map> #include "boost/algorithm/string.hpp" #include "boost/date_time/gregorian/gregorian.hpp" #include "snap.h" #include "StringHasher.h" const std::string prefix = "Data/"; const std::string output_path = "../tmp/"; const std::string suffix = "-Combined.txt"; const int max_input_size = 1000000; // hashing parameters const int A = 3; const int M = 65071; const int LEFT_HASH_WIDTH = 15; const int RIGHT_HASH_WIDTH = 25; void print_column_headers() { std::cout << "mt_cxt = matching_contexts_cnt" << '\n'; std::cout << "mt_prg = matching_programs_cnt" << '\n'; std::cout << "tot_mt = total_matches_cnt" << '\n'; std::cout << "sel_prg = selected_programs_cnt" << '\n'; std::cout << "tot_prg = total_programs_cnt" << '\n'; std::cout << "dt \tmt_cxt\tmt_prg\ttot_mt\tsel_prg\ttot_prg" << std::endl; } int main() { clock_t start_time = std::clock(); srand(time(NULL)); std::string random_id = std::to_string(rand()); snap::web::print_header(); // get user input int content_length = atoi(getenv("CONTENT_LENGTH")); char *input = new char[content_length+1]; fgets(input, content_length+1, stdin); std::string query_string(input); delete[] input; // process user input std::map<std::string, std::string> arguments = snap::web::parse_query_string(query_string); std::string search_string = snap::web::decode_uri(boost::algorithm::trim_copy(arguments["search-string"])); boost::gregorian::date from_date, to_date; try { from_date = snap::date::string_to_date(arguments["from-date"]); to_date = snap::date::string_to_date(arguments["to-date"]); } catch (snap::date::InvalidDateException &e) { std::cout << "<span class=\"error\">" << e.what() << "</span>" << std::endl; exit(-1); } int num_excerpts = stoi(arguments["num-excerpts"]); int excerpt_size = stoi(arguments["excerpt-size"]); bool random = arguments["random"] == "on"; std::vector<std::string> file_list = snap::io::generate_file_names(from_date, to_date, prefix, suffix); unsigned seed = std::chrono::system_clock::now().time_since_epoch().count(); if (random) { std::shuffle(file_list.begin(), file_list.end(), std::default_random_engine(seed)); } std::vector<snap::Expression> expressions; try { expressions.emplace_back(search_string); } catch(snap::ExpressionSyntaxError &e) { const char *error_msg = e.what(); std::cout << "<span class=\"error\">" << error_msg << "</span>" << std::endl; delete[] error_msg; exit(-1); } // display user input std::cout << "<p>" << std::endl; std::cout << "Search string: " << search_string << "<br/>" << std::endl; std::cout << "From (inclusive): " << arguments["from-date"] << "<br/>" << std::endl; std::cout << "To (inclusive): " << arguments["to-date"] << "<br/>" << std::endl; std::cout << "Number of Excerpts: " << arguments["num-excerpts"] << "<br/>" << std::endl; std::cout << "Excerpt Size: " << arguments["excerpt-size"] << "<br/>" << std::endl; std::cout << "</p>" << std::endl; // set up excerpt files std::string output_excerpt_file_name = output_path + snap::date::date_to_string(from_date) + "_all_excerpts_" + random_id + ".csv"; std::string output_random_excerpt_file_name = output_path + snap::date::date_to_string(from_date) + "_random_excerpts_" + random_id + ".csv"; std::ofstream output_excerpt_file(output_excerpt_file_name); std::ofstream output_random_excerpt_file(output_random_excerpt_file_name); output_excerpt_file << "\"dt\",\"program\",\"excerpt\"" << std::endl; output_random_excerpt_file << "\"dt\",\"program\",\"excerpt\"" << std::endl; // begin to iteratively process files std::unordered_map<int, int> left_total_match_hashes; std::unordered_map<int, int> right_total_match_hashes; int matching_contexts_sum = 0; int matching_programs_sum = 0; int total_matches_sum = 0; int selected_programs_sum = 0; int total_programs_sum = 0; std::vector<std::vector<std::string>> search_results; std::vector<std::string> corrupt_files; std::vector<std::string> missing_files; std::vector<snap::Excerpt> excerpts; if (!random) { std::cout << "<pre>" << std::endl; print_column_headers(); } snap::StringHasher hasher("", M, A); for (auto it = file_list.begin(); it != file_list.end(); ++it) { boost::gregorian::date current_date = snap::date::string_to_date((*it).substr(prefix.length(), 10)); if (snap::io::file_exists(*it)) { std::vector<snap::Program> programs; try { programs = snap::io::parse_programs(*it); } catch (snap::io::CorruptFileException &e) { programs.clear(); corrupt_files.push_back(*it); continue; } int matching_contexts = 0; // context is distinct hash AND distinct program int matching_programs = 0; int total_matches = 0; if (random) { seed = std::chrono::system_clock::now().time_since_epoch().count(); std::shuffle(programs.begin(), programs.end(), std::default_random_engine(seed)); } std::unordered_map<int, int> left_match_hashes; std::unordered_map<int, int> right_match_hashes; for (auto p = programs.begin(); p != programs.end(); ++p) { std::map<std::string, std::vector<int>> raw_match_positions = snap::find(expressions.back().patterns, p -> lower_text); std::map<std::string, std::vector<int>> match_positions = snap::evaluate_expressions(expressions, raw_match_positions); hasher.load_text(p -> lower_text); if (match_positions[search_string].size() > 0) { ++matching_programs; total_matches += match_positions[search_string].size(); bool total_context_added = false; bool context_added = false; for (auto it = match_positions[search_string].begin(); it != match_positions[search_string].end(); ++it) { int left_match_hash = hasher.hash(*it - LEFT_HASH_WIDTH, *it); int right_match_hash = hasher.hash(*it, *it + RIGHT_HASH_WIDTH); int left_hash_cnt = left_match_hashes[left_match_hash]++; int right_hash_cnt = right_match_hashes[right_match_hash]++; int left_total_hash_cnt = left_total_match_hashes[left_match_hash]++; int right_total_hash_cnt = right_total_match_hashes[right_match_hash]++; if (left_hash_cnt == 0 && right_hash_cnt == 0) { // only add if new hash is encountered if (!context_added) { // only add once per program context_added = true; ++matching_contexts; } // only add excerpts with new completely new hashes if (left_total_hash_cnt == 0 && right_total_hash_cnt == 0) { if (!total_context_added) { total_context_added = true; ++matching_contexts_sum; } excerpts.emplace_back(*p, *it-excerpt_size, *it+excerpt_size); output_excerpt_file << '"' << excerpts.back().date << "\",\"" << excerpts.back().program_title << "\",\"" << boost::replace_all_copy(excerpts.back().get_raw_text(), "\"", "\"\"") << '"' << std::endl; for (auto pattern = expressions.back().patterns.begin(); pattern != expressions.back().patterns.end(); ++pattern) { excerpts.back().highlight_word(*pattern); } if (random && excerpts.size() <= num_excerpts) { snap::web::print_excerpt(excerpts.back()); output_random_excerpt_file << '"' << excerpts.back().date << "\",\"" << excerpts.back().program_title << "\",\"" << boost::replace_all_copy(excerpts.back().get_raw_text(), "\"", "\"\"") << '"' << std::endl; } } } } } match_positions.clear(); } matching_programs_sum += matching_programs; total_matches_sum += total_matches; selected_programs_sum += programs.size(); total_programs_sum += programs.size(); search_results.push_back(std::vector<std::string>()); search_results.back().push_back(snap::date::date_to_string(current_date)); search_results.back().push_back(std::to_string(matching_contexts)); search_results.back().push_back(std::to_string(matching_programs)); search_results.back().push_back(std::to_string(total_matches)); search_results.back().push_back(std::to_string(programs.size())); search_results.back().push_back(std::to_string(programs.size())); if (!random) { std::copy(search_results.back().begin(), search_results.back().end() - 1, std::ostream_iterator<std::string>(std::cout, "\t")); std::cout << search_results.back().back() << std::endl; } programs.clear(); } else { missing_files.push_back(*it); } } sort(search_results.begin(), search_results.end(), [](std::vector<std::string> a, std::vector<std::string> b) -> bool { return a.front() < b.front(); }); if (random) { std::cout << "<pre>" << std::endl; print_column_headers(); for (auto it = search_results.begin(); it != search_results.end(); ++it) { std::copy(it -> begin(), it -> end() - 1, std::ostream_iterator<std::string>(std::cout, "\t")); std::cout << it -> back() << std::endl; } } else { // shuffle excerpts seed = std::chrono::system_clock::now().time_since_epoch().count(); std::shuffle(excerpts.begin(), excerpts.end(), std::default_random_engine(seed)); for (int i = 0; i < num_excerpts && i < excerpts.size(); ++i) { output_random_excerpt_file << '"' << excerpts[i].date << "\",\"" << excerpts[i].program_title << "\",\"" << boost::replace_all_copy(excerpts[i].get_raw_text(), "\"", "\"\"") << '"' << std::endl; } } std::cout << "Grand Total:"; std::cout << '\t' << matching_contexts_sum; std::cout << '\t' << matching_programs_sum; std::cout << '\t' << total_matches_sum; std::cout << '\t' << selected_programs_sum; std::cout << '\t' << total_programs_sum << std::endl; std::cout << "</pre>" << std::endl; // output file std::string output_file_name = output_path + search_results.front().front() + "_" + random_id + ".csv"; std::ofstream output_file(output_file_name); output_file << "dt,matching_contexts_cnt,matching_programs_cnt,total_matches_cnt,selected_programs_cnt,total_programs_cnt" << std::endl; for (auto it = search_results.begin(); it != search_results.end(); ++it) { std::copy(it -> begin(), it -> end() - 1, std::ostream_iterator<std::string>(output_file, ",")); output_file << it -> back() << '\n'; } output_file.close(); output_excerpt_file.close(); std::cout << "<a href=\"" + output_file_name + "\">Output CSV</a><br/>" << std::endl; std::cout << "<a href=\"" + output_excerpt_file_name + "\">All Excerpts CSV</a><br/>" << std::endl; std::cout << "<a href=\"" + output_random_excerpt_file_name + "\">Random Excerpts CSV</a><br/>" << std::endl; std::cout << "<div>"; std::cout << "<br/>" << std::endl; snap::web::print_missing_files(missing_files); std::cout << "<br/>" << std::endl; snap::web::print_corrupt_files(corrupt_files); std::cout << "</div>" << std::endl; if (!random) snap::web::print_excerpts(excerpts, num_excerpts, false); double duration = (std::clock() - start_time) / (double) CLOCKS_PER_SEC; std::cout << "<br/><span>Time taken (seconds): " << duration << "</span><br/>" << std::endl; snap::web::close_html(); return 0; } <|endoftext|>
<commit_before>/** * @author Ryan Huang <ryanhuang@cs.ucsd.edu> * @organization University of California, San Diego * * JNI helper functions * */ #include "JNIHelper.h" #include "Util.h" #include <stdio.h> #include <map> JNIEnv* globalEnv = NULL; typedef std::map<const char *, void *> HashMap; typedef std::map<const char *, void *>::iterator MapIter; typedef std::pair<const char *, void *> KVPair; HashMap globalClsMap; void * mapGet(HashMap& map, const char * key) { MapIter it = map.find(key); if (it == map.end()) { return NULL; } return it->second; } void mapPut(HashMap& map, const char * key, void * value) { map.insert(KVPair(key, value)); } // Create a JNI env. // // Reference: http://www.inonit.com/cygwin/jni/invocationApi/c.html JNIEnv* createJNIEnv() { JavaVM* jvm; JNIEnv* env; JavaVMInitArgs args; JavaVMOption options[1]; const char *classpath_prefix = "-Djava.class.path="; char *classpath; char *classpath_arg; jint err = 0; args.version = JNI_VERSION_1_2; args.nOptions = 1; classpath = getenv("CLASSPATH"); // read CLASSPATH env variable if (classpath == NULL) { die("CLASSPATH env variable is not set!"); } classpath_arg = concat(classpath_prefix, classpath); if (classpath_arg == NULL) { die("fail to allocate classpath arg string"); } options[0].optionString = classpath_arg; args.options = options; err = JNI_CreateJavaVM(&jvm, (void **) &env, &args); // before checking return value, we should free the allocated string free(classpath_arg); if (err != 0) { die("fail to create JVM"); } return env; } // TODO: not thread-safe JNIEnv* getJNIEnv() { if (globalEnv == NULL) { globalEnv = createJNIEnv(); } return globalEnv; } jthrowable getAndClearException(JNIEnv *env) { jthrowable exception = env->ExceptionOccurred(); if (!exception) return NULL; env->ExceptionClear(); return exception; } jthrowable getMethodId(JNIEnv *env, jmethodID *methodIdOut, const char *className, const char *methodName, const char *methodSignature, bool isStatic) { jclass cls; jthrowable exception; jmethodID mid; exception = getClass(env, &cls, className); if (exception != NULL) return exception; if (isStatic) { // find the static method mid = env->GetStaticMethodID(cls, methodName, methodSignature); } else { // find the instance method mid = env->GetMethodID(cls, methodName, methodSignature); } if (mid == 0) { exception = getAndClearException(env); } else { *methodIdOut = mid; exception = NULL; } return exception; } jthrowable getClass(JNIEnv *env, jclass *clsOut, const char *className) { jthrowable exception = NULL; jclass cls = NULL; cls = (jclass) mapGet(globalClsMap, className); if (cls != NULL) { // found in cache *clsOut = cls; return exception; } else { // not in cache, find from env cls = env->FindClass(className); if (cls == NULL) { // still can't find from env exception = getAndClearException(env); } else { // find in env, update cache mapPut(globalClsMap, className, cls); *clsOut = cls; } } return exception; } jthrowable newClassObject(JNIEnv *env, jobject *objOut, const char *className, const char *ctorSignature, ...) { va_list args; jthrowable exception; jclass cls; // need class for new object jmethodID mid; jobject obj; exception = getClass(env, &cls, className); if (exception != NULL) { return exception; } exception = getMethodId(env, &mid, className, CTORNAME, ctorSignature, false); if (exception != NULL) { return exception; } va_start(args, ctorSignature); obj = env->NewObjectV(cls, mid, args); va_end(args); if (obj == NULL) { exception = getAndClearException(env); } else { *objOut = obj; exception = NULL; } return exception; } bool getMethodRetType(char * rettOut, const char *methodSignature) { if (rettOut == NULL) return false; char t = findNext(methodSignature, ')'); if (t == '\0') { // invalid signature return false; } *rettOut = t; return true; } void printException(JNIEnv *env, jthrowable exception) { jclass cls; jclass basecls; jobject obj; jmethodID mid; jstring jClsName; jstring jMsg; cls = env->GetObjectClass(exception); mid = env->GetMethodID(cls, "getClass", "()Ljava/lang/Class;"); obj = env->CallObjectMethod(exception, mid); basecls = env->GetObjectClass(obj); mid = env->GetMethodID(basecls, "getName", "()Ljava/lang/String;"); jClsName = (jstring) env->CallObjectMethod(obj, mid); mid = env->GetMethodID(cls, "getMessage", "()Ljava/lang/String;"); jMsg = (jstring) env->CallObjectMethod(exception, mid); const char *clsName = env->GetStringUTFChars(jClsName, 0); const char *msg = env->GetStringUTFChars(jMsg, 0); printf("exception in %s: %s\n", clsName, msg); env->ReleaseStringUTFChars(jClsName, clsName); env->ReleaseStringUTFChars(jMsg, msg); } jthrowable callMethod(JNIEnv *env, jvalue *retOut, jobject obj, const char *className, const char *methodName, const char * methodSignature, bool isStatic, ...) { va_list args; jthrowable exception; jclass cls; jmethodID mid; exception = getClass(env, &cls, className); if (exception != NULL) return exception; exception = getMethodId(env, &mid, className, methodName, methodSignature, isStatic); if (exception != NULL) return exception; va_start(args, isStatic); char retType; getMethodRetType(&retType, methodSignature); switch (retType) { case J_BOOL: if (isStatic) exception = callStaticBooleanMethod(env, retOut, cls, mid, args); else exception = callBooleanMethod(env, retOut, obj, mid, args); break; case J_BYTE: if (isStatic) exception = callStaticByteMethod(env, retOut, cls, mid, args); else exception = callByteMethod(env, retOut, obj, mid, args); break; case J_CHAR: if (isStatic) exception = callStaticCharMethod(env, retOut, cls, mid, args); else exception = callCharMethod(env, retOut, obj, mid, args); break; case J_SHORT: if (isStatic) exception = callStaticShortMethod(env, retOut, cls, mid, args); else exception = callShortMethod(env, retOut, obj, mid, args); break; case J_INT: if (isStatic) exception = callStaticIntMethod(env, retOut, cls, mid, args); else exception = callIntMethod(env, retOut, obj, mid, args); break; case J_LONG: if (isStatic) exception = callStaticLongMethod(env, retOut, cls, mid, args); else exception = callLongMethod(env, retOut, obj, mid, args); break; case J_FLOAT: if (isStatic) exception = callStaticFloatMethod(env, retOut, cls, mid, args); else exception = callFloatMethod(env, retOut, obj, mid, args); break; case J_DOUBLE: if (isStatic) exception = callStaticDoubleMethod(env, retOut, cls, mid, args); else exception = callDoubleMethod(env, retOut, obj, mid, args); break; case J_VOID: if (isStatic) exception = callStaticVoidMethod(env, cls, mid, args); else exception = callVoidMethod(env, obj, mid, args); break; case J_OBJ: case J_ARRAY: if (isStatic) exception = callStaticObjectMethod(env, retOut, cls, mid, args); else exception = callObjectMethod(env, retOut, obj, mid, args); break; default: // TODO: throw a new exception to handle unrecognized return type break; } va_end(args); return exception; } /* vim: set ts=4 sw=4 : */ <commit_msg>make global reference for finding class<commit_after>/** * @author Ryan Huang <ryanhuang@cs.ucsd.edu> * @organization University of California, San Diego * * JNI helper functions * */ #include "JNIHelper.h" #include "Util.h" #include <stdio.h> #include <map> JNIEnv* globalEnv = NULL; typedef std::map<const char *, void *> HashMap; typedef std::map<const char *, void *>::iterator MapIter; typedef std::pair<const char *, void *> KVPair; HashMap globalClsMap; void * mapGet(HashMap& map, const char * key) { MapIter it = map.find(key); if (it == map.end()) { return NULL; } return it->second; } void mapPut(HashMap& map, const char * key, void * value) { map.insert(KVPair(key, value)); } // Create a JNI env. // // Reference: http://www.inonit.com/cygwin/jni/invocationApi/c.html JNIEnv* createJNIEnv() { JavaVM* jvm; JNIEnv* env; JavaVMInitArgs args; JavaVMOption options[1]; const char *classpath_prefix = "-Djava.class.path="; char *classpath; char *classpath_arg; jint err = 0; args.version = JNI_VERSION_1_2; args.nOptions = 1; classpath = getenv("CLASSPATH"); // read CLASSPATH env variable if (classpath == NULL) { die("CLASSPATH env variable is not set!"); } classpath_arg = concat(classpath_prefix, classpath); if (classpath_arg == NULL) { die("fail to allocate classpath arg string"); } options[0].optionString = classpath_arg; args.options = options; err = JNI_CreateJavaVM(&jvm, (void **) &env, &args); // before checking return value, we should free the allocated string free(classpath_arg); if (err != 0) { die("fail to create JVM"); } return env; } // TODO: not thread-safe JNIEnv* getJNIEnv() { if (globalEnv == NULL) { globalEnv = createJNIEnv(); } return globalEnv; } jthrowable getAndClearException(JNIEnv *env) { jthrowable exception = env->ExceptionOccurred(); if (!exception) return NULL; env->ExceptionClear(); return exception; } jthrowable getMethodId(JNIEnv *env, jmethodID *methodIdOut, const char *className, const char *methodName, const char *methodSignature, bool isStatic) { jclass cls; jthrowable exception; jmethodID mid; exception = getClass(env, &cls, className); if (exception != NULL) return exception; if (isStatic) { // find the static method mid = env->GetStaticMethodID(cls, methodName, methodSignature); } else { // find the instance method mid = env->GetMethodID(cls, methodName, methodSignature); } if (mid == 0) { exception = getAndClearException(env); } else { *methodIdOut = mid; exception = NULL; } return exception; } jthrowable getClass(JNIEnv *env, jclass *clsOut, const char *className) { jthrowable exception = NULL; jclass cls = NULL; cls = (jclass) mapGet(globalClsMap, className); if (cls != NULL) { // found in cache *clsOut = cls; return exception; } else { // not in cache, find from env cls = env->FindClass(className); if (cls == NULL) { // still can't find from env exception = getAndClearException(env); } else { // find in env, first create a global reference (otherwise, the reference will be // can be dangling), then update cache jclass globalCls = (jclass) env->NewGlobalRef(cls); if (globalCls == NULL) { exception = getAndClearException(env); } else { mapPut(globalClsMap, className, globalCls); *clsOut = globalCls; env->DeleteLocalRef(cls); // delete local reference } } } return exception; } jthrowable newClassObject(JNIEnv *env, jobject *objOut, const char *className, const char *ctorSignature, ...) { va_list args; jthrowable exception; jclass cls; // need class for new object jmethodID mid; jobject obj; exception = getClass(env, &cls, className); if (exception != NULL) { return exception; } exception = getMethodId(env, &mid, className, CTORNAME, ctorSignature, false); if (exception != NULL) { return exception; } va_start(args, ctorSignature); obj = env->NewObjectV(cls, mid, args); va_end(args); if (obj == NULL) { exception = getAndClearException(env); } else { *objOut = obj; exception = NULL; } return exception; } bool getMethodRetType(char * rettOut, const char *methodSignature) { if (rettOut == NULL) return false; char t = findNext(methodSignature, ')'); if (t == '\0') { // invalid signature return false; } *rettOut = t; return true; } void printException(JNIEnv *env, jthrowable exception) { jclass cls; jclass basecls; jobject obj; jmethodID mid; jstring jClsName; jstring jMsg; cls = env->GetObjectClass(exception); mid = env->GetMethodID(cls, "getClass", "()Ljava/lang/Class;"); obj = env->CallObjectMethod(exception, mid); basecls = env->GetObjectClass(obj); mid = env->GetMethodID(basecls, "getName", "()Ljava/lang/String;"); jClsName = (jstring) env->CallObjectMethod(obj, mid); mid = env->GetMethodID(cls, "getMessage", "()Ljava/lang/String;"); jMsg = (jstring) env->CallObjectMethod(exception, mid); const char *clsName = env->GetStringUTFChars(jClsName, 0); const char *msg = env->GetStringUTFChars(jMsg, 0); printf("exception in %s: %s\n", clsName, msg); env->ReleaseStringUTFChars(jClsName, clsName); env->ReleaseStringUTFChars(jMsg, msg); } jthrowable callMethod(JNIEnv *env, jvalue *retOut, jobject obj, const char *className, const char *methodName, const char * methodSignature, bool isStatic, ...) { va_list args; jthrowable exception; jclass cls; jmethodID mid; exception = getClass(env, &cls, className); if (exception != NULL) return exception; exception = getMethodId(env, &mid, className, methodName, methodSignature, isStatic); if (exception != NULL) return exception; va_start(args, isStatic); char retType; getMethodRetType(&retType, methodSignature); switch (retType) { case J_BOOL: if (isStatic) exception = callStaticBooleanMethod(env, retOut, cls, mid, args); else exception = callBooleanMethod(env, retOut, obj, mid, args); break; case J_BYTE: if (isStatic) exception = callStaticByteMethod(env, retOut, cls, mid, args); else exception = callByteMethod(env, retOut, obj, mid, args); break; case J_CHAR: if (isStatic) exception = callStaticCharMethod(env, retOut, cls, mid, args); else exception = callCharMethod(env, retOut, obj, mid, args); break; case J_SHORT: if (isStatic) exception = callStaticShortMethod(env, retOut, cls, mid, args); else exception = callShortMethod(env, retOut, obj, mid, args); break; case J_INT: if (isStatic) exception = callStaticIntMethod(env, retOut, cls, mid, args); else exception = callIntMethod(env, retOut, obj, mid, args); break; case J_LONG: if (isStatic) exception = callStaticLongMethod(env, retOut, cls, mid, args); else exception = callLongMethod(env, retOut, obj, mid, args); break; case J_FLOAT: if (isStatic) exception = callStaticFloatMethod(env, retOut, cls, mid, args); else exception = callFloatMethod(env, retOut, obj, mid, args); break; case J_DOUBLE: if (isStatic) exception = callStaticDoubleMethod(env, retOut, cls, mid, args); else exception = callDoubleMethod(env, retOut, obj, mid, args); break; case J_VOID: if (isStatic) exception = callStaticVoidMethod(env, cls, mid, args); else exception = callVoidMethod(env, obj, mid, args); break; case J_OBJ: case J_ARRAY: if (isStatic) exception = callStaticObjectMethod(env, retOut, cls, mid, args); else exception = callObjectMethod(env, retOut, obj, mid, args); break; default: // TODO: throw a new exception to handle unrecognized return type break; } va_end(args); return exception; } /* vim: set ts=4 sw=4 : */ <|endoftext|>